【发布时间】:2022-11-10 14:49:04
【问题描述】:
我有一个 Solidity 智能合约 Demo,我正在 Hardhat 开发它并在 RSK Testnet 上进行测试。
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
contract Demo {
event Error(string);
fallback() external {
emit Error("call of a non-existent function");
}
}
我想确保调用fallback 函数并发出事件Error。为此,我试图在智能合约上调用nonExistentFunction:
const { expect } = require('chai');
const { ethers } = require('hardhat');
describe('Demo', () => {
let deployer;
let demoContract;
before(async () => {
[deployer] = await ethers.getSigners();
const factory = await ethers.getContractFactory('Demo');
demoContract = await factory.deploy().then((res) => res.deployed());
});
it('should invoke the fallback function', async () => {
const tx = demoContract.nonExistentFunction();
await expect(tx)
.to.emit(demoContract, 'Error')
.withArgs('call of a non-existent function');
});
});
然而,Hardhat 甚至在它实际连接到 RSK 上的智能合约之前就抛出了 TypeError:
Demo
1) should invoke the fallback function
0 passing (555ms)
1 failing
1) Demo
should invoke the fallback function:
TypeError: demoContract.nonExistentFunction is not a function
at Context.<anonymous> (test/Demo.js:13:29)
at processImmediate (internal/timers.js:461:21)
我怎样才能超越 Hardhat/Ethers.js 并最终能够调用不存在的函数,从而在智能合约中调用 fallback 函数?
作为参考,这是我的hardhat.config.js
require('@nomiclabs/hardhat-waffle');
const { mnemonic } = require('./.secret.json');
module.exports = {
solidity: '0.8.4',
networks: {
hardhat: {},
rsktestnet: {
chainId: 31,
url: 'https://public-node.testnet.rsk.co/',
accounts: {
mnemonic,
path: "m/44'/60'/0'/0",
},
},
},
mocha: {
timeout: 600000,
},
};
【问题讨论】:
-
使用修改后的 ABI 初始化
ethers.Contract实例,该 ABI 包含实际合约中不存在的函数签名。这样你就可以编写这个测试了。
标签: solidity ethers.js hardhat rsk