为什么我不能使用此 transferEther 功能将 Ether 发送到智能合约?

Why can't I use this transferEther function to send Ether to the smart contract?

我有这段代码,我已经输入 Remix IDE,作为 ReceivedEther.sol,一个独立的智能合约。

我已经使用 MetaMask 将 0.02 以太币转入智能合约。

当我检查智能合约的余额时,它 returns 200000000000000000,正如预期的那样。

但是,如果我尝试使用 transferEther 函数,并输入一个小于此的数字 - 例如 0.005 ETH 或 50000000000000000 作为数量 - 它无法使用 MetaMask。

当 MetaMask 提示我时,它永远不会是那个数量。它适用于 0 ETH 和 0.00322 汽油费(或任何汽油)。基本上它总是将ETH的数量设置为0并且只收取费用。

为什么我不能在带有 MetaMask 的 Remix IDE 中使用此功能转移一定数量的 ETH?

pragma solidity ^0.8.0;


contract ReceivedEther {

    function transferEther(address payable _recipient, uint _amount) external returns (bool) {
        require(address(this).balance >= _amount, 'Not enough Ether in contract!');
        _recipient.transfer(_amount);
        return true;
    }
    
    /**
    * @return contract balance
    */
    function contractBalance() external view returns (uint) {
        return address(this).balance;
    }
}

您的代码将 ETH(在 _amount 变量中说明)从智能合约发送到 _recipient。因此它不需要发送任何 ETH 来执行 transferEther() 函数。


如果你想让你的合约接受ETH,接受它的函数(或者一般的fallback()receive()函数)需要标记为payable.

示例:

pragma solidity ^0.8.0;

contract ReceivedEther {

    receive() external payable {} // note the `payable` keyword

    // rest of your implementation
}

然后您可以发送任意数量的 ETH 到智能合约地址(无需指定要执行的任何函数)。

https://docs.soliditylang.org/en/v0.8.5/contracts.html#receive-ether-function

查看更多

如果您想从 Remix IDE 中预填充 MetaMask 中的金额,您可以使用“部署和 运行 交易”选项卡中的“值”输入。