Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 47 ยท Working With Contracts From Outside

Oracles, Randomness and Off-Chain Data

Learn why smart contracts need oracles, how price feeds get manipulated, why block data is bad randomness, and how commit-reveal and signed messages work.

A contract can only see what is on the chain. It cannot fetch a web page, ask a weather service, or look up the price of ether in dollars, because every node must run the same code and reach the same result years later. If nodes could make web requests, they would get different answers and the chain would split. This is the same determinism rule from How a Smart Contract Runs. Yet many useful contracts need outside facts: lending needs prices, insurance needs weather, games need random numbers.

An oracle is any mechanism that puts an off-chain fact on the chain so that contracts can read it. This lesson covers how oracles work, how they get attacked, why randomness is the hardest fact to get honestly, and two patterns you can build yourself: commit-reveal and signed messages. Real oracle networks cannot run on this website, so every demo is a JavaScript stand-in that shows the logic.

Facts a chain cannot see

Prices Needed by lending and trading.
Real-world events Weather, sports, flight delays.
Randomness Fair draws and games.
Identity Proofs checked off-chain.

Someone has to carry each fact onto the chain, and you must decide how far to trust them.

1 / 2

Why oracles are a trust problem

A blockchain's security comes from many parties checking each other. An oracle is a doorway where that checking stops. If a lending contract trusts a price that one server publishes, then the contract is only as honest as that server, and the whole system inherits a single point of failure. Good oracle designs fight this in three ways: many independent reporters whose answers are combined (often by taking the median), economic penalties for lying, and data sources that are hard to move.

The common arrangement is a price feed: a contract that stores the latest value of a price and a timestamp, updated by a network of reporters. Your contract calls a function on the feed and reads the answer, like a call to any other contract through an interface. Read-only sketch of the consuming side, using a feed interface of the kind major oracle networks provide:

SOLIDITY
interface IPriceFeed {
    // price has `decimals()` decimal places; updatedAt is a Unix timestamp
    function latestAnswer() external view returns (int256 price, uint256 updatedAt);
    function decimals() external view returns (uint8);
}

contract Collateral {
    IPriceFeed public immutable feed;
    uint256 public constant MAX_AGE = 1 hours;

    error StalePrice(uint256 age);
    error BadPrice();

    constructor(IPriceFeed feed_) {
        feed = feed_;
    }

    function ethPrice() public view returns (uint256) {
        (int256 price, uint256 updatedAt) = feed.latestAnswer();
        if (price <= 0) revert BadPrice();
        if (block.timestamp - updatedAt > MAX_AGE) revert StalePrice(block.timestamp - updatedAt);
        return uint256(price);
    }
}

The function names above are illustrative, because each real oracle network has its own interface, so read the documentation of the feed you use. The two checks are not optional: reject a non-positive price, and reject a price that has not been updated recently, because a stopped feed would otherwise report an old number forever.

Manipulation: why the source of a price matters

The most expensive oracle mistake is reading a price from a place an attacker can move. Suppose your contract asks a single decentralized exchange pool "what is the price of ether right now?". Those pools price assets by their reserves, so anyone with enough money can swap a huge amount into the pool and push the price, use your contract at the distorted price, then swap back. With a flash loan, the attacker does not even need the money, because the loan is borrowed and repaid inside one transaction. Many real exploits have followed exactly this recipe.

The defence is to avoid spot prices from a single venue and to use data that is expensive to move: a time-weighted average price (TWAP) over many blocks, or a feed that combines many sources. The stand-in below builds a constant-product pool with a lending check that reads either the spot price or an average over time. The pool formula is the real x * y = k idea. Everything else, such as the block times and the numbers, is simplified.

JS Spot price versus a time-weighted average

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A single block of manipulation moves the spot price by more than double, but the 10-minute average barely moves. To drag the average, the attacker would have to hold the distorted price for many blocks, which costs real money and lets arbitrageurs trade against them. That is the economics oracle designers rely on. TWAPs are not magic: a short window is cheaper to push than a long one, and thin markets are easier to move than deep ones.

Randomness: block data is not random

Games and lotteries need a number nobody can predict or steer. The tempting source is on-chain data such as block.timestamp, block.number or blockhash. Do not use it. A block producer can influence these values, and worse, another contract in the same transaction can read exactly the same values as yours and decide to act only when the result favors it.

SOLIDITY
// BROKEN: never do this for anything of value
function roll() external view returns (uint256) {
    return uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % 6;
}

Any contract can compute that same expression before calling roll() and only proceed on a winning roll. Common Vulnerabilities lists bad randomness among the classic bugs. Two honest options exist. The first is an oracle that supplies randomness together with a proof that the number was generated fairly, which a contract can verify. The second is a pattern you can build yourself for small games between participants: commit-reveal.

Commit-reveal

In commit-reveal, each player first publishes a commitment, the hash of their secret value plus a random salt. A hash reveals nothing about what is inside it, and it cannot be changed afterwards without the hash changing. Once everyone has committed, players reveal their secret and salt, and the contract checks that the hash matches. Because nobody could see the others' values before committing, no one could steer the result.

The stand-in below uses a toy hash instead of keccak256, so do not treat it as secure. The structure is the real one: commit, reveal, check, then combine all secrets into a result. It also shows the known weakness: someone who sees that the others have revealed can refuse to reveal and walk away, so real systems add a deposit that is lost when a player does not reveal.

JS Commit-reveal in two phases

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Bob tried to change his number after seeing the world move on, and the hash check rejected it. Both secrets are fixed before either is public, so the final roll is out of any single player's control.

Signed messages

A cheaper pattern is to keep data off-chain until someone needs it. An oracle (or any trusted party) signs a message containing the data, and the user who needs it submits the message and signature to your contract in their own transaction. The contract recovers the signer from the signature and checks that it is the authorized one. Nothing needs to be pushed to the chain until it is used, which saves a lot of gas for data that changes often.

A signed message must be checked for more than the signature. The message should include a deadline so old data expires, a nonce or unique id so the same message cannot be submitted twice, and the chain ID and contract address so a message meant for one deployment cannot be replayed on another. Missing replay protection is a classic bug. In Solidity the recovery step is done with the ecrecover function or a library built on it.

SOLIDITY
function claim(uint256 price, uint256 deadline, uint256 nonce, bytes calldata sig) external {
    require(block.timestamp <= deadline, "expired");
    require(!used[nonce], "already used");
    bytes32 digest = keccak256(abi.encode(block.chainid, address(this), price, deadline, nonce));
    require(recoverSigner(digest, sig) == trustedSigner, "bad signature");
    used[nonce] = true;
    // use price ...
}

The recoverSigner helper wraps ecrecover and should reject the zero address, which ecrecover returns for malformed signatures. In practice use a well-tested library for it. The stand-in below cannot do public-key cryptography, so it fakes a "signature" with a shared secret and a toy hash. That is not how real signatures work (real ones prove the signer without sharing a secret), but it lets you practice the checks around the signature.

JS Verifying signed data with deadline and replay checks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real: the checks around the signature (deadline, unique nonce, chain and contract binding) and the idea that changing any field breaks the signature. Stand-in: the "signature" is a keyed hash that the consumer could forge, because it recomputes it with the same secret. A real contract only knows the signer's public address.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can a smart contract not simply download a price from a website?

    Nodes re-run the code, possibly years later, and must all agree. A web response could differ per node and per time, so contracts rely on oracles that put data on the chain first.
  2. 2. What is the main danger of reading the price from a single DEX pool's current reserves?

    Pool prices follow reserves, which a large swap can shift temporarily. A time-weighted average or a multi-source feed is far more expensive to distort.
  3. 3. Why is keccak256(abi.encodePacked(block.timestamp, msg.sender)) % 6 a bad dice roll?

    Everything in the expression is visible to other code in the same transaction, and block producers can also nudge some of these values. It is predictable for anyone who looks.
  4. 4. What makes commit-reveal work?

    A hash hides the secret but binds the player to it. After the reveal, the contract recomputes the hash, so nobody can change their value after seeing the others.
  5. 5. Which field in a signed message prevents the same message from being accepted twice?

    Without a one-time nonce (or id), anyone can resubmit the same valid signature again and again. The contract stores used nonces and rejects repeats.

Summary

  • Contracts cannot reach outside the chain, so an oracle brings facts on-chain, and you inherit the trust you place in it.
  • Check oracle data for staleness and invalid values, and prefer feeds that combine many sources.
  • A spot price from one pool can be moved within a single transaction. Time-weighted averages are much more expensive to push.
  • Block data (block.timestamp, blockhash) is not safe randomness. Use verifiable randomness from an oracle, or commit-reveal between participants with a penalty for not revealing.
  • Signed messages move data off-chain until it is needed. Always bind them to a deadline, a unique nonce, the chain ID and the contract address.
  • The demos here use toy hashing, so they teach the structure but are not secure.

Next: Project: A Voting Contract.