Skip to Content
๐ŸŒ Web3๐Ÿ”ฎ Oracles

๐Ÿ”ฎ Oracles

Oracles bring off-chain data (prices, weather, events) onto the blockchain so smart contracts can use it. Contracts cannot fetch URLs or APIs by themselves; oracles provide a trusted or decentralized bridge between the real world and on-chain logic.


๐ŸŽฏ Why Oracles Matter

  • DeFi โ€” Lending, derivatives, and swaps need price feeds (e.g. ETH/USD)
  • Gaming & NFTs โ€” Randomness, events, or external triggers
  • Risk โ€” A single centralized price source can be manipulated; decentralized oracles reduce that risk

๐Ÿ“š Core Concepts

TermDescription
Price feedOn-chain data (e.g. latest ETH/USD) updated by the oracle
AggregationMany sources combined (e.g. median) for a single answer
DecentralizationMultiple independent nodes or data sources; no single point of failure
ConsumptionYour contract reads the oracle contract (e.g. latestRoundData())

๐Ÿ› ๏ธ Oracle Options

Chainlink Data Feedsย  provide decentralized price feeds and other data on many chains (Ethereum, Polygon, Arbitrum, etc.). Contracts read from a feed contract (aggregator).

Other providers


// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; contract PriceConsumer { AggregatorV3Interface internal priceFeed; // Sepolia ETH/USD feed constructor() { priceFeed = AggregatorV3Interface( 0x694AA1769357215DE4FAC081bf1f309aDC325306 ); } function getLatestPrice() public view returns (int256) { ( /* uint80 roundID */, int256 price, /* uint256 startedAt */, /* uint256 timeStamp */, /* uint80 answeredInRound */ ) = priceFeed.latestRoundData(); return price; // e.g. 2000_00000000 = $2000 (8 decimals) } }

Install: npm install @chainlink/contracts. Use the correct feed addressย  for your network.


const { ethers } = require("ethers"); const abi = [ "function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)", ]; const provider = new ethers.JsonRpcProvider(process.env.RPC_URL); const feed = new ethers.Contract( "0x694AA1769357215DE4FAC081bf1f309aDC325306", // Sepolia ETH/USD abi, provider ); const data = await feed.latestRoundData(); const price = Number(data.answer) / 1e8; console.log("ETH/USD:", price);

โš ๏ธ Security Notes

  • Donโ€™t use a single API in a contract via a custom oracle unless you fully trust it and accept manipulation risk.
  • Staleness โ€” Check updatedAt (or equivalent) and reject data that is too old.
  • Decentralized feeds โ€” Prefer aggregated, decentralized oracles (e.g. Chainlink) for critical pricing.
  • See Smart Contract Security and EVM Smart Contract Security for general practices.

๐Ÿ”— Resources

Last updated on