Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

Setting Up Chainlink Data Feeds for Real-Time Event Resolution

A technical guide for developers on integrating Chainlink Data Feeds to automatically resolve prediction market outcomes for financial, sports, and political events.
Chainscore © 2026
introduction
INTRODUCTION

Setting Up Chainlink Data Feeds for Real-Time Event Resolution

Learn how to integrate Chainlink Data Feeds to access secure, real-world data for on-chain event triggers and automation.

Chainlink Data Feeds provide decentralized oracles that deliver real-time price data for assets like ETH/USD, BTC/USD, and hundreds of other pairs directly to smart contracts. This data is aggregated from numerous premium data providers, making it highly reliable and resistant to manipulation. For developers building applications that require real-time event resolution—such as triggering a loan liquidation when collateral value drops, executing a limit order, or settling a prediction market—these feeds are an essential infrastructure component. They eliminate the need to trust a single centralized data source.

The core mechanism is the AggregatorV3Interface, a standardized Solidity interface that allows your contract to read the latest round data from a feed. Each data feed is updated by a decentralized network of oracle nodes at regular intervals (e.g., every heartbeat or when price deviations exceed a threshold). When you call functions like latestRoundData(), you receive a data structure containing the answer, timestamp, and round ID. It's critical to check that the answeredInRound matches the current roundId to ensure you are using fresh, non-stale data in your logic.

To get started, you must first identify the correct feed address for your target network and asset pair. These addresses are listed in the Chainlink Data Feeds documentation. For example, the mainnet ETH/USD feed address is 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419. In your contract, you import the interface, instantiate it with the feed address, and then call it to fetch data. Always use the latestRoundData function and implement proper error handling for edge cases like stale or incomplete data.

A basic implementation involves importing @chainlink/contracts and declaring the interface. Here's a minimal example:

solidity
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceConsumerV3 {
    AggregatorV3Interface internal priceFeed;

    constructor(address feedAddress) {
        priceFeed = AggregatorV3Interface(feedAddress);
    }

    function getLatestPrice() public view returns (int) {
        (
            uint80 roundId,
            int price,
            uint startedAt,
            uint updatedAt,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        require(updatedAt >= block.timestamp - 3600, "Stale price");
        require(answeredInRound >= roundId, "Stale round");
        return price;
    }
}

The checks for staleness are crucial for production systems.

For advanced event resolution, you can combine data feeds with Chainlink Automation or your own keeper network. Instead of polling the price on-chain (which is gas-inefficient), you can set up an off-chain monitor that watches the feed. When a specific condition is met (e.g., price < threshold), it calls a function on your contract to execute the desired action. This pattern is far more efficient and is the standard for DeFi protocols that require precise, gas-aware execution. Chainlink Automation provides a decentralized network for this, allowing you to register Upkeeps that perform these checks and executions reliably.

Key considerations for production use include understanding the feed's deviation thresholds and heartbeat intervals, which determine update frequency. Always use the feed's decimals() function to correctly format the returned price value. For maximum security, consider using multiple data feeds or a data feed aggregator for critical financial logic. By properly integrating Chainlink Data Feeds, you enable your smart contracts to react to real-world events with the same security guarantees as the underlying blockchain, creating robust and trustworthy automated systems.

prerequisites
SETUP

Prerequisites

Before integrating Chainlink Data Feeds for real-time event resolution, you must configure your development environment and understand the core components involved.

To follow this guide, you need a foundational understanding of Ethereum development. This includes familiarity with Solidity for writing smart contracts, using Hardhat or Foundry for development and testing, and a basic grasp of JavaScript/TypeScript for writing deployment scripts and interacting with contracts. You should also have Node.js (v18 or later) and npm/yarn installed on your machine. If you are new to these tools, consider reviewing the Hardhat documentation or the Foundry book first.

You will need access to an Ethereum node for deploying and testing contracts. For development, you can use a local node via Hardhat Network or a testnet provider like Alchemy or Infura. Securing a testnet RPC URL and funding a wallet with test ETH (e.g., Sepolia ETH) is essential. For mainnet deployment, you will need real ETH to pay for gas. This guide will primarily use the Sepolia testnet for examples, as it is the recommended network for testing Chainlink Data Feeds.

The core dependency is the Chainlink Contracts library. Install it in your project using npm: npm install @chainlink/contracts. This package contains the AggregatorV3Interface, which is the standard interface for interacting with price feed consumer contracts. You will also need the @chainlink/contracts package for accessing the feed proxy addresses on different networks. Verify your package.json includes these dependencies before proceeding.

Chainlink Data Feeds are updated by decentralized oracle networks. To use them, your contract needs the correct proxy address for the desired asset pair (e.g., ETH/USD) on your target network. You can find the latest proxy addresses in the Chainlink Documentation. It is critical to use the verified proxy address, not the aggregator address, as the proxy is the upgradeable point your contract will call. Bookmark this page for reference.

Finally, set up a .env file to manage sensitive configuration. You will need to store your RPC URL (e.g., from Alchemy) and the private key of your deployer wallet. Use the dotenv package to load these variables in your scripts. Never commit your .env file to version control. With these prerequisites in place, you are ready to write and deploy a smart contract that consumes real-time data from Chainlink.

key-concepts-text
TECHNICAL GUIDE

How Chainlink Data Feeds Work for Resolution

Learn how to integrate Chainlink Data Feeds into your smart contracts to resolve real-world events with secure, decentralized price data.

Chainlink Data Feeds provide decentralized oracle networks that deliver tamper-proof price data directly to smart contracts on-chain. For event resolution, such as determining the outcome of a prediction market or a parametric insurance trigger, contracts need a reliable, real-time source of truth for asset prices. Data Feeds aggregate data from numerous premium data providers, securing it through a decentralized network of independent node operators. The aggregated data is updated on-chain at regular intervals, creating a verifiable and manipulation-resistant price point that smart contracts can trust for final settlement.

To set up a Data Feed, you first need the correct AggregatorV3Interface contract address for your desired price pair and blockchain network. These addresses are listed in the Chainlink Data Feeds documentation. For example, the ETH/USD feed on Ethereum mainnet is 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419. Your smart contract imports the interface and uses its functions, primarily latestRoundData(), to fetch the latest price. This function returns a tuple containing the answer, the round ID, timestamps, and other metadata, allowing you to verify the freshness and completeness of the data.

Here is a basic Solidity contract example that reads the ETH/USD price:

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceConsumerV3 {
    AggregatorV3Interface internal priceFeed;

    constructor(address _priceFeedAddress) {
        priceFeed = AggregatorV3Interface(_priceFeedAddress);
    }

    function getLatestPrice() public view returns (int) {
        (
            /*uint80 roundID*/,
            int price,
            /*uint startedAt*/,
            /*uint timeStamp*/,
            /*uint80 answeredInRound*/
        ) = priceFeed.latestRoundData();
        return price;
    }
}

The constructor sets the feed address, and getLatestPrice() calls the oracle to retrieve the current value.

For robust event resolution, your contract should implement data freshness checks and circuit breaker logic. Always check the updatedAt timestamp from latestRoundData() to ensure the price is recent enough for your application's requirements (e.g., not older than 1 hour). You should also validate that answeredInRound is equal to roundId to confirm the answer is from the latest completed round. Implementing a deviation threshold—where you only accept a new price if it moves beyond a certain percentage—can prevent settlement based on minor, insignificant price fluctuations, adding another layer of reliability.

Integrating Data Feeds for resolution extends beyond simple price checks. You can build complex conditional logic. For instance, a binary options contract might resolve to "yes" if the BTC/USD price is above $70,000 at expiry, pulling that final price directly from the feed. A decentralized insurance protocol could automatically trigger a payout if a weather data feed reports a hurricane exceeding a specific wind speed in a predefined region. The key is that the resolution logic is executed autonomously based on the external data provably supplied by the Chainlink network, removing any need for manual intervention or a trusted third party.

When deploying, consider gas costs, update intervals, and network coverage. Data Feeds on L2s like Arbitrum or Optimism have lower gas costs for reading data. Each feed has a heartbeat (e.g., every hour) and a deviation threshold that triggers an update; understand these parameters for your use case. Always use the official, verified contract addresses from Chainlink's documentation, and consider using the Chainlink Data Feeds library for easier management of addresses across chains. This setup ensures your event resolution is secure, cost-effective, and reliable.

FEATURE COMPARISON

Selecting the Right Data Feed for Your Market

Key differences between Chainlink Data Feed types for real-time price resolution.

Feature / MetricDecentralized Data FeedSingle-Source Data FeedProof of Reserve Feed

Primary Use Case

On-chain DeFi pricing (e.g., ETH/USD)

Off-chain event resolution

Asset collateral verification

Update Threshold

0.5% price deviation

Customizable

1% reserve change

Update Interval

< 1 hour (or on threshold)

On-demand via request

24 hours

Oracle Network Size

31 independent nodes

1 designated node

3-7 auditor nodes

Data Aggregation

Decentralized median consensus

Single source truth

Multi-source attestation

Typical Latency

1-60 seconds on new block

< 1 second on request

Up to 24 hours

Gas Cost for Consumer

~50k-100k gas per read

~200k+ gas per request

~80k gas per read

Example Feed

ETH/USD on Ethereum Mainnet

Sports match outcome

wBTC Reserve on Ethereum

PRACTICAL IMPLEMENTATIONS

Resolution Contract Examples by Event Type

Handling Price Feed Updates

Price feed resolution contracts listen for AnswerUpdated events from Chainlink aggregators. The primary use case is updating on-chain state, like collateral ratios or liquidation thresholds, based on fresh market data.

Key Implementation Steps:

  • Import the AggregatorV3Interface.
  • Store the aggregator address and the last recorded answer.
  • In the resolution function, call latestRoundData() to get the current price.
  • Compare with the stored value and execute logic (e.g., rebalance, liquidate) if a deviation threshold is met.

Example Trigger Logic:

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceResolution {
    AggregatorV3Interface internal priceFeed;
    int256 public lastPrice;
    uint256 public deviationThresholdBps = 500; // 5%

    constructor(address _aggregator) {
        priceFeed = AggregatorV3Interface(_aggregator);
        (,int256 price,,,) = priceFeed.latestRoundData();
        lastPrice = price;
    }

    function checkAndResolve() external {
        (,int256 currentPrice,,,) = priceFeed.latestRoundData();
        uint256 deviation = uint256(
            (abs(currentPrice - lastPrice) * 10000) / uint256(abs(lastPrice))
        );
        
        if (deviation > deviationThresholdBps) {
            // Execute resolution logic
            lastPrice = currentPrice;
        }
    }

    function abs(int x) private pure returns (int) {
        return x >= 0 ? x : -x;
    }
}
implementation-steps
STEP-BY-STEP IMPLEMENTATION

Setting Up Chainlink Data Feeds for Real-Time Event Resolution

This guide details the process of integrating Chainlink Data Feeds into a smart contract to resolve real-world events with reliable, decentralized data.

Chainlink Data Feeds provide decentralized price oracles that deliver aggregated market data directly to smart contracts. For event resolution—such as determining if a sports team won or if a weather threshold was met—you need a feed that provides the specific data point required. Start by identifying the correct data feed for your use case on the Chainlink Data Feeds page. For example, to resolve a bet on an NBA game's total points, you would use a feed like NBA Total Points on a supported network like Ethereum or Polygon.

Once you have the feed address, you must import the AggregatorV3Interface into your Solidity contract. This interface defines the functions to read the feed. In your contract, declare a data feed variable and initialize it in the constructor with the feed's proxy address. The core function for reading data is latestRoundData(), which returns the price, timestamp, and round ID. For event resolution, your contract's logic should compare the returned answer (the data point) against a predefined condition to trigger an outcome.

A critical implementation detail is handling data freshness and security. Always check the updatedAt timestamp from latestRoundData() to ensure the data is recent enough for your application's needs, a practice known as stale data checks. Furthermore, consider implementing a circuit breaker pattern that pauses resolution if the data is too old, protecting against oracle downtime. For high-value events, using multiple data feeds and calculating a median value can increase security and decentralization.

Testing your integration is essential. Use a forked mainnet environment with tools like Hardhat or Foundry to simulate reading from the live feed address. You can also utilize Chainlink's testnet feeds on Sepolia or Mumbai for development. Write unit tests that mock the feed's response to verify your contract correctly resolves events based on different data values (e.g., a score above or below a line).

Finally, consider gas optimization and user experience. Reading a data feed is a simple call, but if your resolution function is permissioned or involves complex logic, gas costs can add up. For applications requiring frequent checks, an off-chain trigger (like a Chainlink Automation upkeep) can monitor the feed and call the resolution function on-chain only when the condition is met, saving gas and ensuring timely execution.

CHAINLINK DATA FEEDS

Handling Data Formats and Precision

Chainlink Data Feeds provide decentralized, real-world data to smart contracts. This guide addresses common developer questions about data formats, precision handling, and troubleshooting feed integration.

A Chainlink Aggregator returns data as a tuple of three int256 values: (roundId, answer, updatedAt). The answer is the primary data point, scaled by the feed's decimals value.

  • roundId: A unique identifier for the data round.
  • answer: The aggregated data value (e.g., the ETH/USD price).
  • updatedAt: The timestamp when the answer was last updated.

You must account for the feed's decimal precision. For an ETH/USD feed with 8 decimals, an answer of 350000000000 represents $3,500.00. Always retrieve the decimals() from the aggregator contract to scale the value correctly in your application.

CHAINLINK DATA FEEDS

Troubleshooting Common Issues

Common problems developers encounter when integrating Chainlink Data Feeds for real-time price or event resolution, with actionable solutions.

A Chainlink Data Feed returns stale data when the latest round's timestamp is older than the feed's heartbeat or deviation threshold. This is a safety feature, not a failure. Check the latestRoundData() return values.

Primary Causes:

  • Heartbeat Not Met: The price hasn't changed enough to trigger an update within the maximum time window (e.g., 1 hour for ETH/USD).
  • Deviation Threshold Not Met: The price change is smaller than the required percentage (e.g., 0.5%).

How to Check:

solidity
( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) = aggregator.latestRoundData();
require(updatedAt >= block.timestamp - STALE_PRICE_DELAY, "Stale price");
require(answer > 0, "Invalid price");

Always use both updatedAt and answer > 0 checks. The answeredInRound must equal roundId for fresh data.

CHAINLINK DATA FEEDS

Frequently Asked Questions

Common questions and solutions for developers integrating Chainlink Data Feeds to resolve real-world events on-chain.

A Chainlink Data Feed is a decentralized oracle network that provides aggregated, real-world data to smart contracts on-chain. It works by sourcing data from multiple premium data providers, which is then aggregated and delivered by a decentralized set of independent node operators. This process ensures high availability and manipulation resistance.

Key components:

  • Aggregator Contract: The on-chain contract that holds the latest aggregated answer (e.g., the ETH/USD price).
  • Oracle Nodes: Independent operators that retrieve data from sources and submit it on-chain.
  • Data Sources: Reputable off-chain APIs and data providers.

Your smart contract reads the latest answer by calling functions like latestRoundData() on the Aggregator's address, receiving a signed, time-stamped value.

conclusion
IMPLEMENTATION SUMMARY

Conclusion and Next Steps

You have successfully integrated Chainlink Data Feeds to resolve real-time events in your smart contract. This guide covered the core concepts and implementation steps.

Integrating Chainlink Data Feeds provides your smart contracts with a secure and reliable connection to real-world data. By using the AggregatorV3Interface, you can access price data for assets like ETH/USD, BTC/USD, or any of the hundreds of available feeds. This architecture decouples your contract's logic from data sourcing, significantly reducing oracle-related risks and maintenance overhead. The key takeaways are using the correct proxy address for your network, understanding the data structure returned by latestRoundData(), and handling the returned values (answer, decimals) appropriately in your calculations.

For production deployments, consider these advanced practices. Implement robust error handling by checking the answeredInRound and roundId to guard against stale data. Use the decimals() function dynamically instead of hardcoding values to future-proof your contract against feed updates. For high-value transactions, you may want to add circuit breakers or use a deviation threshold oracle that triggers updates only when the price moves beyond a specified percentage. Review Chainlink's Best Practices for automation-ready contracts to prepare for more complex logic.

Your next steps should involve testing and securing your implementation. Deploy your contract to a testnet like Sepolia or Goerli and use testnet faucets to fund it with LINK and native gas tokens. Verify all price calculations off-chain before locking funds. For mainnet deployment, conduct a thorough audit or use formally verified contract templates. To expand beyond price data, explore other Chainlink services like VRF for verifiable randomness for gaming/NFTs or Automation for time-based or condition-based contract execution, enabling fully autonomous DeFi applications.

How to Use Chainlink Data Feeds for Prediction Markets | ChainScore Guides