使用ChainLink预言机聚合器合约
有了使用Hardhat forking功能模拟主网的基础,我们来看一下如何在链上使用预言机聚合器合约来获取某个数字资产当前价格。
代码及讲解
https://solidity-by-example.org/defi/chainlink-price-oracle/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract ChainlinkPriceOracle {
AggregatorV3Interface internal priceFeed; //聚合器合约
constructor() {
// ETH / USD
priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
}
function getLatestPrice() public view returns (int256) {
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
// for ETH / USD price is scaled up by 10 ** 8
return price / 1e8;
}
}
interface AggregatorV3Interface {
function latestRoundData() external view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
ChainlinkPriceOracle.getLatestPrice()
合约函数提供查询最新ETH/USD价格功能,具体是在函数中通过AggregatorV3Interface
聚合器接口、传入具体的聚合器地址0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419
实例化聚合器,然后调用其latestRoundData()
获取价格。- 聚合器中维持相应的价格数据,价格数据由预言机网络从链下渠道获取、经过共识后写入聚合器合约,这样其他链上合约就可以获取到了。
使用hardhat测试
hardhat.config.js
require("@nomicfoundation/hardhat-toolbox");
require("dotenv").config();
/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
solidity: "0.8.24",
networks: {
hardhat: {
forking: {
url: "https://eth-mainnet.g.alchemy.com/v2/" + process.env.ALCHEMY_KEY,
blockNumber: 20710591
}
}
}
};
脚本
const { ethers } = require("hardhat");
async function main() {
const factory = await ethers.getContractFactory("ChainlinkPriceOracle");
const contract = await factory.deploy();
console.log("ChainlinkPriceOracle合约部署完成,地址: ", await contract.getAddress());
//const contractSigned = contract.connect(deployer);
console.log("ETH/USD价格:" + await contract.getLatestPrice());
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
输出:
npx hardhat run .\ignition\modules\oracle.js --network hardhat
ChainlinkPriceOracle合约部署完成,地址: 0x72aC6A36de2f72BD39e9c782e9db0DCc41FEbfe2
ETH/USD价格:2306