๐Ÿ”ฎ
Implementing an Oracle
Start using Chainlink data feeds, VRF and more โ›“

Challenge 4 - Implementing an Oracle ๐Ÿ”ฎ

Getting Started

1
git clone https://github.com/scaffold-eth/scaffold-eth-challenges.git app
2
cd app
3
git checkout challenge-4-oracle
4
yarn install
Copied!

How Do Smart Contracts Use Oracles?

Oracles are most popularly used with Data Feeds. DeFi platforms like AAVE and Synthetix use Chainlink data feed oracles to obtain accurate real-time asset prices in their smart contracts.
Chainlink data feeds are sources of data aggregated from many independent Chainlink node operators. Each data feed has an on-chain address and functions that enable contracts to read from that address. For example, the ETH / USD feed.
An Aggregator Page for ETH / USD
The following code is from the Get the Latest Price page. It describes a contract which obtains the latest ETH / USD price using the Kovan testnet.
1
// SPDX-License-Identifier: MIT
2
pragma solidity ^0.8.7;
3
โ€‹
4
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
5
โ€‹
6
contract PriceConsumerV3 {
7
โ€‹
8
AggregatorV3Interface internal priceFeed;
9
โ€‹
10
/**
11
* Network: Kovan
12
* Aggregator: ETH/USD
13
* Address: 0x9326BFA02ADD2366b30bacB125260Af641031331
14
*/
15
constructor() {
16
priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331);
17
}
18
โ€‹
19
/**
20
* Returns the latest price
21
*/
22
function getLatestPrice() public view returns (int) {
23
(
24
uint80 roundID,
25
int price,
26
uint startedAt,
27
uint timeStamp,
28
uint80 answeredInRound
29
) = priceFeed.latestRoundData();
30
return price;
31
}
32
}
Copied!
Notice how the code imports an interface called AggregatorV3Interface. In this case, AggregatorV3Interface defines that all V3 Aggregators will have the function latestRoundData. You can see all of the functions that a V3 Aggregator exposes in theAggregatorV3Interface file on Github.
Our contract is initialized with the hard-coded address of the Kovan data feed for ETH / USD prices. Then, getLatestPrice uses latestRoundData to obtain the most recent round of price data. We're interested in the price, so the function returns that.

How To Deploy To Testnet

There are a few things that are needed to deploy a contract to a testnet:
โ€‹
  • โ€‹
Last modified 2mo ago