我试图在使用硬质await owner.sendTransaction({to: greeter.address, value: "1000000"})的测试中将ETH发送到一个契约,但是它会返回到“函数选择器未被识别”错误。
你可以用一个基本的项目来复制-
npm init -y
npm i -D hardhat
npx hardhat # use defaults编辑test/sample-test.js并添加以下测试用例-
it("Should send ETH to the contract", async function () {
[owner] = await ethers.getSigners();
const Greeter = await ethers.getContractFactory("Greeter");
const greeter = await Greeter.deploy("Hello, world!");
await greeter.deployed();
await owner.sendTransaction({to: greeter.address, value: "1000000"});
});运行测试npx hardhat test,新添加的测试将在Error: Transaction reverted: function selector was not recognized and there's no fallback nor receive function中失败。
全测试日志-
Deploying a Greeter with greeting: Hello, world!
Changing greeting from 'Hello, world!' to 'Hola, mundo!'
✔ Should return the new greeting once it's changed (626ms)
Deploying a Greeter with greeting: Hello, world!
1) Should send ETH to the contract
1 passing (745ms)
1 failing
1) Greeter
Should send ETH to the contract:
Error: Transaction reverted: function selector was not recognized and there's no fallback nor receive function
at Greeter.<unrecognized-selector> (contracts/Greeter.sol:6)
at EthModule._estimateGasAction (/Users/tal/dev/solidity/SendEthToContract/node_modules/hardhat/src/internal/hardhat-network/provider/modules/eth.ts:425:7)
at HardhatNetworkProvider.request (/Users/tal/dev/solidity/SendEthToContract/node_modules/hardhat/src/internal/hardhat-network/provider/provider.ts:118:18)
at EthersProviderWrapper.send (/Users/tal/dev/solidity/SendEthToContract/node_modules/@nomiclabs/hardhat-ethers/src/internal/ethers-provider-wrapper.ts:13:20)知道怎么把ETH送去合同吗?
发布于 2022-04-29 06:01:45
更新:正如@Nergon所指出的,有一个回答解释了这种现象。
若要在不使用payable函数的情况下将ETH发送到契约,则需要有一个使用特殊solidity关键字receive的函数,以允许在不调用函数的情况下接收ETH。
receive() external payable似乎合同只能通过payable函数接收ETH。
ETH接收功能应该像这样-
function receiveETH() public payable {
// code
}然后,它可以在测试中接收ETH,使用-
await farmer.receiveETH({value: ethers.utils.parseEther("1.0")});发布于 2022-12-02 16:15:49
当我在一个分叉的硬件网络上写一个测试时,我无意中遇到了这个问题,我想把ETH发送到一个没有接收功能或应付回扣功能的第三方合同中。我需要这样做,因为我想模拟这个合同,以便在另一个只接受第一个合同调用的合同上调用一个许可的方法。
如果有人处于相同的情况下,我将使用硬帽_setBalance RPC方法,通过硬顶帽网络助手库共享我的解决方案。这可以任意设置任何平衡。
import * as helpers from "@nomicfoundation/hardhat-network-helpers";
// ...
await helpers.setBalance(MyContract.address, hre.ethers.utils.parseEther("1"));https://ethereum.stackexchange.com/questions/127143
复制相似问题