Solidity

在安全帽測試網路上使用 ethers.js 監聽事件

  • October 30, 2021

我目前正在將一個松露項目遷移到安全帽。我在收聽事件時遇到了問題。我有一個簡單的 ERC20 代幣,想听聽這個Transfer事件。我在安全帽測試網路上執行契約。這是我的測試程式碼,它沒有擷取Transfer事件。高度讚賞我做錯了什麼:

import { ethers } from "hardhat";
import chai from "chai";
import { solidity } from "ethereum-waffle";
import { FlanToken } from "../typechain/MyToken";
import { BigNumber} from "ethers";

chai.use(solidity);
const { assert } = chai;


describe("MyToken", () => {

   let myToken: MyToken;
   let accounts: any;

   beforeEach(async () => {
       accounts = await ethers.getSigners();
       const tokenFactory = await ethers.getContractFactory("MyToken", accounts[0]);
       myToken = (await myToken.deploy()) as MyToken;
       await myToken.deployed();
   });

   describe("token transfer", async () => {

       it("valid transfer", async () => {
           myToken.on("Transfer", (_from,_to,_value) => {
               console.log(_from,_to,_value);
           });

           await myToken.connect(accounts[0]).transfer(accounts[1].address, 1);

           // balance checks
           let balanceSender: BigNumber = await myToken.balanceOf(accounts[0].address);
           let balanceReceiver: BigNumber = await myToken.balanceOf(accounts[1].address);
           assert.equal(balanceSender.toNumber(), 999999, "Unexpected balance of sender afer token transfer.");
           assert.equal(balanceReceiver.toNumber(), 1, "Unexpected balance of receiver afer token transfer.");
       })
   });

});

雖然我沒有找到有關該.on()方法為何不起作用的解決方案,但我找到了使用事務的receipt. 以下程式碼描述了此解決方法:

let tx: ContractTransaction = await myToken.connect(accounts[0]).transfer(accounts[1].address, 1);

let receipt: ContractReceipt = await tx.wait();
console.log(receipt.events?.filter((x) => {return x.event == "Transfer"}));

據我所知,實際上不可能使用發出的參數,但是您可以使用以下 chai 程式碼範例測試它們是否發出:

await expect(token.transfer(walletTo.address, 7))
 .to.emit(token, 'Transfer')
 .withArgs(wallet.address, walletTo.address, 7);

這是參考

引用自:https://ethereum.stackexchange.com/questions/93757