Oracles and Chainlink Price Feeds
Suggest an editSmart contracts are sandboxed. They cannot fetch a stock price, call a REST API, or read a database. Anything that comes from outside the chain has to be put on chain by something, and that something is called an oracle.
The oracle problem
The EVM is a deterministic state machine. Every node must execute every transaction and arrive at the same result, otherwise consensus breaks. That requirement rules out anything that could return different values to different nodes: HTTP requests, random number generators, file system reads, system clocks beyond block.timestamp. None of these are available inside Solidity, and no compiler flag will give them to you.
This is a problem because most interesting financial applications depend on real-world data. A lending protocol needs to know what its collateral is worth, in dollars, right now, so it can liquidate undercollateralized loans.
This data does not exist on chain natively. The only way to get it there is for someone outside to write a transaction that puts it there. That someone is an oracle.
An oracle is a contract and an operator who writes to it
An oracle is two things:
- A contract on chain that holds some data in storage.
- An off-chain operator who sends transactions that update that storage.
Your contract reads from the oracle contract the same way you read from any other contract: a normal view call. The read is an ordinary function call, so the question that matters is who you trust to do the writing.
The simplest possible oracle is one contract, one operator. The operator queries one data source, signs a transaction with the result, and writes it on chain. Your contract has no way to check the number it reads, so this oracle fails in three ways:
- The source is wrong. Even reputable exchanges have brief glitches. An API returns the price of a different asset for a few seconds. Volume thins out and the last trade is far from fair value. If your oracle pulls from one place, you inherit every glitch from that place. A single source can also be moved on purpose. In 2020 Harvest Finance lost $24M because its contracts took the price from a single on-chain market, and an attacker moved that price with borrowed money, as the flash loans lesson describes.
- The operator is malicious. A single party with the ability to push any number on chain has every incentive to do so when the payoff is large enough. The history of DeFi exploits includes cases where compromised oracle keys were used to drain protocols of tens of millions of dollars in single transactions.
- The operator goes offline. The oracle stops updating. Your contract continues to operate using an increasingly stale price. By the time anyone notices, positions that should have been liquidated have moved against the protocol.
The engineering effort around production oracle systems is about reducing how much you have to trust any single party.
How Chainlink answers each failure
A Chainlink price feed replaces the single source with many exchanges and the single operator with many independent nodes.
The source is wrong. Each node pulls the price from many exchanges, so one exchange that glitches or goes down does not decide the answer.
The operator is malicious. Many independent nodes report in parallel, and the feed stores the median of their answers, which is the middle value after sorting. If four nodes report 3,499, 3,500, 3,500 and 3,501 and a fifth reports 1,000,000, the average is 202,800 and the median is still 3,500. As long as fewer than half of the answers are false, the median stays inside the range of the honest ones.
The operator goes offline. There is no single operator: many nodes report, and one of them writes the agreed answer. If the feed stops updating anyway, your contract can notice, because every answer carries the time it was written.
The OCR step (Off-Chain Reporting) is the part that matters for cost. Without it, every node would have to write its own answer on chain, paying gas, and your contract would have to read all of them and compute the median itself. OCR lets the nodes do the median calculation off chain via a peer-to-peer protocol, agree on a single answer, and have one of them write that answer to the aggregator in one transaction. The on-chain footprint is a single write per update, regardless of how many nodes participated.
The on-chain side is split into two contracts: an aggregator that does the actual storage and verification, and a proxy that consumers point at. The proxy address never changes, and the aggregator behind it can be swapped out for upgrades, so production code always reads from the proxy address rather than the aggregator directly. The full list of proxy addresses per network is on the supported networks page.
Reading a feed
Consuming a price feed is one interface and one function call. Your contract wraps the feed's proxy address in Chainlink's AggregatorV3Interface and calls latestRoundData(). The function returns five values, and most consumers need two of them: answer, the price itself, and updatedAt, the time the answer was last updated.
The price comes back as int256, not uint256, because the interface also serves feeds whose values can legitimately be negative (interest rate differentials, for example). Price feeds for assets like ETH/USD will never return a negative number, but the type allows one, so require answer > 0 once at the read site. The check makes converting to uint256 safe, and it catches the edge case where a misconfigured feed reports zero or negative.
The answer returned is an integer, with the decimal point implicit. Each feed has a decimals() function that tells you how many digits to interpret as decimals. For ETH/USD, the convention is 8 decimals. If the feed returns answer = 350000000000, the actual price is 3500.00000000 USD. To use this in computation alongside an 18-decimal token amount, you have to either scale the price up or scale the token amount down. The typical approach is to multiply the price by 10^10 to bring it to 18-decimal precision. Decimals do not change for a given feed, so if you call decimals() once at construction and store it, you avoid one external call on every price read.
The on-chain price can be stale
Every update is a transaction that costs gas, so a feed does not write a new price in every block. It updates when either the price moves enough or enough time has passed. It does not need both.
For ETH/USD on mainnet the deviation threshold is 0.5% and the heartbeat is one hour. So in normal operation the on-chain price can sit almost 0.5% away from the real price without triggering an update, and it can be up to an hour old if the price hasn't moved enough. For less active feeds, heartbeats can be 24 hours or longer.
This means stale data is a real possibility, even under normal operation. Your contract must validate that the data is recent enough for its purposes. In the code below, priceFeed is the feed's proxy typed as AggregatorV3Interface, which you import from @chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol:
function getValidatedPrice() public view returns (uint256) {
(, int256 answer, , uint256 updatedAt, ) = priceFeed.latestRoundData();
require(answer > 0, "invalid price");
require(block.timestamp - updatedAt < 1 hours + 10 minutes, "stale price");
return uint256(answer);
}The staleness threshold depends on the feed's heartbeat and your protocol's tolerance. A lending protocol that liquidates on small price moves needs fresher data than a settlement contract that runs once a day. Here the threshold is the one-hour ETH/USD heartbeat plus ten minutes. Because an update can arrive slightly after the heartbeat under normal operation, production code usually sets the threshold a little above the heartbeat so a late-but-healthy update is not rejected as stale. Setting it too low causes false reverts during normal operation. Setting it too high lets your protocol act on data that may no longer reflect reality.
What you still trust
Chainlink reduces how much you trust any single party, but your contract still trusts the feed as a whole. It trusts that most of the nodes report honestly. It also trusts whoever can swap the aggregator behind the proxy, because a new aggregator can report any number to every contract that reads the proxy.
Chainlink also doesn't have a feed for every asset. For a token without one, the TWAP lesson builds a price from an AMM pool.
Before you ship a contract that reads a feed, answer two questions about it. What does the contract do if the price stops updating for longer than the heartbeat? Can it lose money when the real price is a deviation threshold away from the price it read?