我在Kovan上部署了Remix的APIConsumer示例合约(https://docs.chain.link/docs/make-a-http-get-request/),用LINK为其提供资金,并从Remix发送了一个requestVolumeData交易。在Etherscan上可以看到,chainlinkcompleted事件被触发:https://kovan.etherscan.io/address/0xde79d39db6b5210f83acf57346d74e5c762ab895#events.
然后我在Hardhat中使用Kovan分叉(使用Alchemy API密钥)附加到相同的合约,并且它从未接收到事件。下面是我的测试脚本:
const { ethers } = require("hardhat");
describe("API", function() {
it("Should make request and get result", async function() {
const ERC20 = await ethers.getContractFactory("ERC20")
const link = await ERC20.attach("0xa36085F69e2889c224210F603D836748e7dC0088"); //Kovan
console.log("name=" + await link.name());
const APIConsumer = await ethers.getContractFactory("APIConsumer");
const apiConsumer = APIConsumer.attach("0xde79d39db6B5210F83acf57346d74E5C762AB895");
//Ensure contract has sufficient LINK
console.log("balanceOf=" + await link.balanceOf(apiConsumer.address));
//Make request
const transaction = await apiConsumer.requestVolumeData()
const tx_receipt = await transaction.wait()
const requestId = tx_receipt.events[0].topics[1]
console.log("requestId=%s", requestId)
//Optionally subscribe to events
// apiConsumer.on("ChainlinkFulfilled", id => {
// console.log("ChainlinkFulfilled: %s", id);
// })
//Wait 30 secs for oracle to callback
await new Promise(resolve => setTimeout(resolve, 30000))
//Now check the result
const result = await apiConsumer.volume()
console.log("API Consumer Volume: %s", result)
});
});
在hardhat.config.js中,blockNumber被选择在第一个ChainlinkRequested事件之前,我们可以从脚本输出中看到,合同有足够的LINK。
require("@nomiclabs/hardhat-waffle");
/**
* @type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.7",
networks: {
hardhat: {
forking: {
url: "https://eth-kovan.alchemyapi.io/v2/<API Key>",
blockNumber: 31301193
}
}
},
};
脚本输出API
name=ChainLink Token
balanceOf=1000000000000000000
requestId=0x352988e0ddfe5c4349711ed9787069b1ea55bae562f676a08f6103435a874514
API Consumer Volume: 0
为什么chainlinkfulfillment似乎没有从Hardhat测试中被解雇?