我有这个代码,我已经输入到 Remix IDE 中,作为 ReceivedEther.sol,一个独立的智能合约。
我已经使用 MetaMask 将 0.02 以太币转移到智能合约中。
当我检查智能合约的余额时,它按预期返回 200000000000000000。
但是,如果我尝试使用 transferEther 函数并输入一个小于此值的数字 - 例如,0.005 ETH 或 500000000000000000 作为数量 - 它无法使用 MetaMask。
当 MetaMask 提示我时,它永远不会是那个数量。这是 0 ETH 和 0.00322 gas 费(或任何 gas 费用)。基本上它总是将 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 中的金额,您可以使用“部署和运行事务”选项卡中的“值”输入。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句