How to use chainlink on your own evm contract
what is blockchain oracle?
As we know , blockchains are self-contained worlds.Smart contract can’t get information by invoking api like we do in web2.At the same time,centralized data providers are also not very reliable.For example,we need to know the price ETH/USDC when we swaping on defi like uniswap.Can we trust one single centralized data provider?The answer is obvious.So we need some decentralized data providers.Oracel act as an message bridge between blockchain and off-chain data provider.
why do SMART CONTRACTS need oracle?
To achieve deterministic execution, blockchains limit nodes to reaching consensus on simple binary (true/false) questions using only data stored on the blockchain itself.If blockchain get information from external data provider it would be impossible to achieve determinism.Different blockchain node maybe return different executes result.To solve those problems we create oracles.Oracle smart contract taking information from off-chain sources and then store the information on the blockchain.Since information stored on-chain is unalterable and publicly available, Ethereum nodes can safely use the oracle imported off-chain data to compute state changes without breaking consensus
how to use chainlink data feed oracle?
Let’s dive into an example,assume that we need to get the BTC/USD price on our smart contract.
Chainlink provide data feed server on several networks.
- Ethereum Mainnet
- Sepolia Testnet
- Gogerli Testnet
We gonna test the data feed server on goerli testnet by foundry tool.
First we need to import chainlink contract interface @chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol
.
Secondly,let’s init the smart contract using a specify target smart contract address which we copy from chainlink official document website.
Lastly,we just need invoke latestRoundData
function which return the current price about BTC/USD.
Here is the whole code:
1 | // SPDX-License-Identifier: UNLICENSED |
we can use forge create
command to deploy the contract.And then we invoke the getLatestData
function via cast call
command.Trust me you’ll get some return like this:
1 | eth_goerli |
If you are using Chainlink Data Feeds on L2 networks like Arbitrum, Optimism, and Metis, you must also check the latest answer from the L2 Sequencer Uptime Feed to ensure that the data is accurate in the event of an L2 sequencer outage
origin
https://oneclicktoken.xyz/23-07-28.html
contact me
Twitter:https://twitter.com/coffiasse
Github:https://github.com/coffiasd
TG:@coffiasd