这是一个非常小的仓库来显示这个问题:https ://github.com/adamdry/ethers-event-issue
但我也会在这里解释。这是我的合同:
//SPDX-License-Identifier: UNLICENSED;
pragma solidity 0.8.4;
contract ContractA {
event TokensMinted(uint amount);
function mint(uint amount) public {
emit TokensMinted(amount);
}
}
这是我的测试代码:
import * as chai from 'chai'
import { BigNumber, ContractTransaction } from 'ethers'
import { ethers } from 'hardhat'
import { ContractA, ContractAFactory } from '../typechain'
const expect = chai.expect
describe("Example test", function () {
it("should fire the event", async function () {
const [owner] = await ethers.getSigners();
const contractAFactory = (await ethers.getContractFactory(
'ContractA',
owner,
)) as ContractAFactory
const contractA: ContractA = await contractAFactory.deploy()
contractA.on('TokensMinted', (amount: BigNumber) => {
// THIS LINE NEVER GETS HIT
console.log('###########')
})
const contractTx: ContractTransaction = await contractA.mint(123)
const contractReceipt: ContractReceipt = await contractTx.wait()
for (const event of contractReceipt.events!) {
console.log(JSON.stringify(event))
}
});
});
我期待它###########
被打印到控制台,但它没有,所以监听器函数由于某种原因没有被执行。
如果我深入了解 ContractReceipt 正确的事件数据:
{
"transactionIndex": 0,
"blockNumber": 2,
"transactionHash": "0x55d118548c8200e5e6c19759d9aab56cb2e6a274186a92643de776d617d51e1a",
"address": "0x5FbDB2315678afecb367f032d93F642f64180aa3",
"topics": [
"0x772f66a00a405709c30e7f18feadcc8f123b20c09c7260165d3eec36c9f21372"
],
"data": "0x000000000000000000000000000000000000000000000000000000000000007b",
"logIndex": 0,
"blockHash": "0x808e6949118509b5a9e482e84cf47921a2fcffbcd943ebbd8ce4f6671469ee01",
"args": [
{
"type": "BigNumber",
"hex": "0x7b"
}
],
"event": "TokensMinted",
"eventSignature": "TokensMinted(uint256)"
}