Oracles and price feeds
Smart contracts cannot call websites. They only know what is already on the chain. An oracle is a service that brings outside data, such as the price of ETH in dollars, on-chain so contracts can use it.
Chainlink price feeds are the most common choice. Each feed is a contract with its own address on each network. You call latestRoundData to read the newest price, which comes back as an integer with a fixed number of decimals, usually 8 for USD pairs.
Never read a price from a single decentralized exchange pool for important decisions, because one large trade can move it for a moment. Check that the data is fresh by comparing updatedAt with block.timestamp, and make sure the price is positive.
The interface below is declared inside the file so you can compile it here. In a real project you would import it from the Chainlink package.
interface AggregatorV3Interface { function decimals() external view returns (uint8); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound); } contract PriceReader { AggregatorV3Interface public immutable feed; constructor(address feedAddress) { feed = AggregatorV3Interface(feedAddress); } function latestPrice() public view returns (int256) { (, int256 answer, , uint256 updatedAt, ) = feed.latestRoundData(); require(answer > 0, "Bad price"); require(block.timestamp - updatedAt < 1 hours, "Stale price"); return answer; } }
Try it yourself
Add a function that takes an amount of ETH in wei and returns its value in USD using the feed's decimals, then compile.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.