有了使用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
);
}
使用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
标签:聚合,uint256,contract,ChainlinkPriceOracle,预言,ChainLink,hardhat,ETH,const
From: https://www.cnblogs.com/lyhero11/p/18404986