使用 ethers js 运行安全帽测试时,合约事件侦听器不会触发

For*_*ero 6 solidity ethers.js hardhat

这是一个非常小的存储库来显示该问题: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);
    }

}
Run Code Online (Sandbox Code Playgroud)

这是我的测试代码:

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))
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

我期望###########将其打印到控制台,但事实并非如此,因此侦听器函数由于某种原因没有被执行。

如果我深入研究 ContractReceipt ,就会发现正确的事件数据:

//SPDX-License-Identifier: UNLICENSED;
pragma solidity 0.8.4;

contract ContractA {

    event TokensMinted(uint amount);

    function mint(uint amount) public {
        emit TokensMinted(amount);
    }

}
Run Code Online (Sandbox Code Playgroud)

For*_*ero 8

完整的答案在这里:https://github.com/nomiclabs/hardhat/issues/1692#issuecomment-905674692

但总而言之,这不起作用的原因是 ethers.js 默认情况下使用轮询来获取事件,轮询间隔为 4 秒。如果您在测试结束时添加此内容:

await new Promise(res => setTimeout(() => res(null), 5000));
Run Code Online (Sandbox Code Playgroud)

该事件应该触发。

然而!您还可以调整给定合约的轮询间隔,如下所示:

// at the time of this writing, ethers' default polling interval is
// 4000 ms. here we turn it down in order to speed up this test.
// see also
// https://github.com/ethers-io/ethers.js/issues/615#issuecomment-848991047
const provider = greeter.provider as EthersProviderWrapper;
provider.pollingInterval = 100;
Run Code Online (Sandbox Code Playgroud)

如下所示:https: //github.com/nomiclabs/hardhat/blob/master/packages/hardhat-ethers/test/index.ts#L642

然而!(再次)如果您想从事件中获取结果,以下方法不需要更改轮询或任何其他基于“时间”的解决方案,根据我的经验,这可能会导致不稳定的测试:

it('testcase', async() => {
  const tx = await contract.transfer(...args); // 100ms
  const rc = await tx.wait(); // 0ms, as tx is already confirmed
  const event = rc.events.find(event => event.event === 'Transfer');
  const [from, to, value] = event.args;
  console.log(from, to, value);
})
Run Code Online (Sandbox Code Playgroud)

这是我的 TypeScriptyfied 版本(根据我自己的合同,事件和参数略有不同):

const contractTx: ContractTransaction = await tokenA.mint(owner.address, 500)
const contractReceipt: ContractReceipt = await contractTx.wait()
const event = contractReceipt.events?.find(event => event.event === 'TokensMinted')
const amountMintedFromEvent: BigNumber = event?.args!['amount']
Run Code Online (Sandbox Code Playgroud)

这是与上述内容一致的 Solidity 事件声明:

event TokensMinted(uint amount);
Run Code Online (Sandbox Code Playgroud)