如何在Hardhat部署中读取Chainlink AggregatorV3Interface数据
解决Hardhat中调用Chainlink价格喂料函数并打印结果的问题
你之前的写法错误在于直接调用getLatestPrice(),这个函数是合约实例的成员方法,不是全局函数,而且因为是Solidity的view函数,在ethers.js中调用需要用异步方式(加await)。
修正后的部署脚本代码如下:
const { ethers } = require("hardhat"); async function main() { const TestChainlink = await ethers.getContractFactory("TestChainlink"); const testChainlink = await TestChainlink.deploy(); await testChainlink.deployed(); // 等待合约部署完成 console.log("合约地址:", testChainlink.address); // 调用合约的getLatestPrice方法,注意加await const rawPrice = await testChainlink.getLatestPrice(); // Chainlink ETH/USD价格是放大了10^8倍的,转换为正常价格 const formattedPrice = ethers.utils.formatUnits(rawPrice, 8); console.log("ETH/USD价格(原始值):", rawPrice.toString()); console.log("ETH/USD价格(格式化后):", formattedPrice); } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); });
关键说明:
- 必须通过部署后的合约实例
testChainlink调用getLatestPrice(),不能直接写函数名 - 调用view函数是异步操作,必须加
await等待返回结果 - Chainlink的价格喂料返回值是放大后的整数(比如ETH/USD是乘以10^8),用
ethers.utils.formatUnits可以转换为带小数的可读格式 - 确保你的Hardhat配置已经正确连接Goerli测试网,并且部署账户有足够的测试ETH
内容的提问来源于stack exchange,提问作者Learning Smart Contracts
相关产品推荐
相关产品推荐

