🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Blockchain Oracles: Price Feeds, VRF, and Design Patterns

Oracle NetworksđŸŸĸ Free Lesson
Oracle Networks

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 shapeLatencyCostTrust surfaceTypical use
Push price feedSecondsSponsored by usageReporter set plus aggregationLiquidations, spot references
Pull request (Functions)Seconds to minutesPer requestOff-chain compute adapterArbitrary APIs, web data
VRF randomnessOne to two blocksPer requestCoordinator plus subscriptionGames, raffles, allocation
Messaging (CCIP)MinutesPer messageRelayer and lane validatorsCross-chain state
Optimistic oracleHours (challenge window)BondedDispute resolution processLong-tail prices, assertions
TWAP on chainConfigured windowGas per observationThe pool being observedThin 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.

FailureSymptomDefense
Feed stops updatingStale updatedAt, frozen priceStaleness check that halts sensitive actions
Single reporter malfunctionsAnswer deviates from peersMulti-source comparison with a band
Thin market movedSpot price spikes, feed lagsTWAP or deviation bound before acting
Gateway or RPC outageReads revert or time outRedundant providers, circuit breaker
Coordinated compromiseConsistent but false answerIndependent 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement