The one-line mental model
A blockchain cannot see the outside world, so every protocol that depends on a price, a random number, or an API response inherits the trust assumptions, latency, and failure modes of whatever oracle feeds it.
Prerequisites
- !Solidity interfaces and external contract calls
- !Why block timestamps and block hashes are predictable
What You'll Learn
- 1Explain why on-chain code cannot fetch its own external data
- 2Read a price feed with staleness, round, and deviation checks
- 3Describe the VRF request-and-fulfill cycle and why blockhash is insecure randomness
- 4Choose between push feeds, pull requests, and compute adapters for a given problem
The oracle problem in one paragraph
Consensus gives a chain agreement about its own state, and nothing more. A contract that wants to know the ETH/USD price, the winner of a match, or the temperature in a city must ask something outside the chain, and that act of asking breaks the purity of the model: the chain is trusting a data source it cannot inspect, at a moment it cannot control, for a claim it cannot independently verify. Everything an oracle design does â decentralize the reporters, aggregate multiple observations, publish signed attestations, price the updates â exists to shrink the size of that trust gap, not to eliminate it.
The practical consequence for protocol authors is that an oracle is a dependency with a security rating. A feed that liquidations depend on is load-bearing infrastructure in the same sense that a database replication topology is: you choose it, you monitor it, and you have a plan for when it degrades.
Push feeds: reading a Chainlink price correctly
Chainlink data feeds are pushed on chain by a decentralized reporter network that signs observations, and a consumer contract reads the latest aggregated result. The naive read gets three things wrong, and each one has caused real losses:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract PriceOracleConsumer {
AggregatorV3Interface internal feed;
uint256 public constant MAX_STALENESS = 3600; // seconds
uint256 public constant MAX_DEVIATION = 500; // 5% in basis points
error StalePrice();
error BadRound();
error PriceTooFar();
constructor(address _feed) {
feed = AggregatorV3Interface(_feed);
}
function latestPrice() external view returns (uint256 price) {
(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = feed.latestRoundData();
if (answer <= 0) revert BadRound();
if (answeredInRound < roundId) revert BadRound();
if (updatedAt == 0 || block.timestamp - updatedAt > MAX_STALENESS) {
revert StalePrice();
}
uint256 decimals = uint256(feed.decimals());
price = uint256(answer) / (10 ** decimals);
startedAt; // present for completeness; some feeds use it for windows
}
function priceWithinBand(uint256 reference, uint256 candidate)
external
pure
returns (bool)
{
uint256 delta = candidate > reference ? candidate - reference : reference - candidate;
return delta * 10_000 <= reference * MAX_DEVIATION;
}
}
decimals matters more than it looks: most USD feeds report eight decimals, so reading the raw answer as a whole-dollar figure inflates the number by a factor of a hundred million. updatedAt is the staleness check, and answeredInRound guards against a partial round where the answer exists but has not been finalized. Both checks belong in a modifier you apply to every consumer, not in one function you remember to call.
Randomness: why block variables are not random
block.timestamp, blockhash, and prevrandao are visible to every participant before the block is finalized, so anyone building an NFT rarity, a lottery, or a game outcome on them is running a raffle whose ticket numbers are printed in advance. Verifiable randomness replaces that with a request-and-fulfill cycle in which the random value is committed before the request and revealed afterward:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
contract RandomLoot is VRFConsumerBaseV2 {
VRFCoordinatorV2Interface public immutable coordinator;
uint64 public immutable subscriptionId;
bytes32 public immutable keyHash;
uint32 public immutable callbackGasLimit = 200_000;
uint16 public immutable requestConfirmations = 3;
mapping(uint256 => address) public requestToRequester;
uint256 public lastRandom;
event RandomnessFulfilled(uint256 indexed requestId, uint256 randomValue);
constructor(address _coordinator, uint64 _subId, bytes32 _keyHash)
VRFConsumerBaseV2(_coordinator)
{
coordinator = VRFCoordinatorV2Interface(_coordinator);
subscriptionId = _subId;
keyHash = _keyHash;
}
function requestLoot() external returns (uint256 requestId) {
requestId = coordinator.requestRandomWords(
keyHash,
subscriptionId,
requestConfirmations,
callbackGasLimit,
1
);
requestToRequester[requestId] = msg.sender;
}
function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords)
internal
override
{
lastRandom = randomWords[0];
emit RandomnessFulfilled(requestId, randomWords[0]);
}
}
The security property comes from ordering: the coordinator stores a verifiable delay function output before your request is registered, then reveals it in the callback, so no participant â including the node fulfilling the request â can grind a favorable result after seeing who asked. The cost is an asynchronous two-transaction flow, which is why game designs that need randomness must tolerate a wait rather than assuming an instant answer.
There is a second, subtler failure to design around: requesting randomness more often than the network can cheaply fulfill it. Each request carries a subscription fee and a callback gas budget, so a contract that requests a random word on every user action will either drain its subscription or, if the callback runs out of gas, emit a fulfillment that reverts and leaves the request permanently unanswered. Batch requests where the design allows, set the callback gas limit with a measured worst case rather than a guess, and keep a way for a stuck request to be cancelled and retried so that one expensive operation cannot wedge a user's flow.
Choosing the right oracle shape
Different problems want different plumbing, and using a price feed for something it was not designed for is a recurring source of incidents:
| Oracle shape | Latency | Cost | Trust surface | Typical use |
|---|---|---|---|---|
| Push price feed | Seconds | Sponsored by usage | Reporter set plus aggregation | Liquidations, spot references |
| Pull request (Functions) | Seconds to minutes | Per request | Off-chain compute adapter | Arbitrary APIs, web data |
| VRF randomness | One to two blocks | Per request | Coordinator plus subscription | Games, raffles, allocation |
| Messaging (CCIP) | Minutes | Per message | Relayer and lane validators | Cross-chain state |
| Optimistic oracle | Hours (challenge window) | Bonded | Dispute resolution process | Long-tail prices, assertions |
| TWAP on chain | Configured window | Gas per observation | The pool being observed | Thin markets, manipulation resistance |
A useful rule: if a value is needed every block by many users, a push feed is cheaper and more reliable than polling an API; if a value is needed rarely and cannot be predicted, a pull request avoids polluting shared infrastructure; if the value must be unpredictable, only a VRF or an equivalent commitment scheme belongs in the design.
Fallbacks, monitoring, and graceful degradation
The failure mode that costs money is not a feed going dark â it is a protocol continuing to act on the last value it saw. Production consumers therefore layer defenses: staleness bounds that halt liquidations when data ages out, deviation limits that reject absurd single-observation moves, a secondary feed compared against the primary so disagreement triggers a pause, and a documented operational procedure for when the pause engages.
That operational procedure deserves as much design attention as the on-call alert itself. A pause without a defined unpause path becomes a permanent outage; a pause that any single operator can toggle becomes a lever an attacker can pull. Write the criteria for resuming activity â a fresh observation from both sources, a deviation inside the band for a stated number of rounds, a human sign-off recorded on chain â and practice the drill before you need it. Protocols that paused within minutes of an oracle anomaly limited damage that otherwise compounded for hours, because the response was a rehearsed step rather than an improvised argument.
| Failure | Symptom | Defense |
|---|---|---|
| Feed stops updating | Stale updatedAt, frozen price | Staleness check that halts sensitive actions |
| Single reporter malfunctions | Answer deviates from peers | Multi-source comparison with a band |
| Thin market moved | Spot price spikes, feed lags | TWAP or deviation bound before acting |
| Gateway or RPC outage | Reads revert or time out | Redundant providers, circuit breaker |
| Coordinated compromise | Consistent but false answer | Independent second feed, human circuit breaker |
â ī¸Never liquidate on a stale or single-block price
Liquidations move markets by design, so they are the highest-value target for oracle manipulation. Require a fresh timestamp, an acceptable round, and agreement with a second source before letting a liquidation execute, and accept that pausing during chaos is cheaper than liquidating at a fabricated price.
Common Mistakes
Reading the raw feed answer without applying decimals
Fix: Call decimals and scale explicitly, and unit-test against a known historical value so a factor-of-10 error cannot ship
Using block.timestamp or prevrandao as a randomness source for anything of value
Fix: Use a VRF and design the calling flow to tolerate an asynchronous fulfillment rather than blocking on an immediate answer
Trusting one feed with no staleness or deviation checks
Fix: Wrap every read in a modifier that enforces freshness and bounds, and compare against an independent second source for critical actions
Polling a public API from a contract via a generic adapter without a fallback
Fix: Keep a secondary adapter, set a circuit breaker that halts dependent actions, and monitor fulfillment latency alerts
Best Practices
- Put oracle checks in shared modifiers so every consumer of a feed inherits the same protections
- Simulate feed failure in tests by advancing the clock and asserting your contract halts rather than proceeding
- Document which oracle assumptions your protocol depends on, including acceptable staleness and deviation, as part of the design review
- Budget for the second feed even if you launch with one; adding redundancy under incident pressure is how mistakes happen
Interview Questions
Q1: Why can a contract not simply call a web API for its data?
Ethereum execution is deterministic and every node must reach the same result, so a contract cannot perform an I/O call that might return different answers on different machines. External data must be delivered by a transaction, which is exactly what an oracle network provides.
Q2: What does the staleness check protect against?
A feed that stops updating while your protocol keeps acting on the last value it saw. Halting liquidations or borrows when the timestamp ages out converts a bad data situation into a temporary pause rather than a sequence of decisions made on obsolete prices.
Q3: Why is VRF randomness unbiasable while block variables are not?
VRF output is committed before the request is registered and revealed afterward, so nobody can grind a favorable result after seeing the request. Block variables are visible in the mempool before the block is produced, letting a miner or searcher choose among candidate outcomes.
Key Takeaways
- Consensus resolves state; oracles move the trust problem outward rather than solving it
- Correct price reads require decimals, round, and staleness handling on every consumer
- Verifiable randomness needs a request-then-fulfill cycle because on-chain block fields are predictable
- Choose push feeds, pull requests, or VRF based on latency, cost, and unpredictability requirements
- Layer staleness bounds, deviation limits, and a second source so degraded data halts actions instead of poisoning them