如何发送以太币?
您可以通过以下方式将以太币发送到其他合约
transfer
(2300 gas,抛出错误)send
(2300 gas,返回布尔值)call
(转发所有gas或设置gas,返回布尔值)接收 Ether 的合约必须至少具有以下功能之一
receive() external payable
fallback() external payable
receive()
如果msg.data
为空则调用,否则fallback()
调用。
call
2019 年 12 月后推荐使用与重入防护结合使用的方法。
通过以下方式防止重新进入
pragma solidity ^0.8.10;
contract ReceiveEther {
/*
Which function is called, fallback() or receive()?
send Ether
|
msg.data is empty?
/ \
yes no
/ \
receive() exists? fallback()
/ \
yes no
/ \
receive() fallback()
*/
// Function to receive Ether. msg.data must be empty
receive() external payable {}
// Fallback function is called when msg.data is not empty
fallback() external payable {}
function getBalance() public view returns (uint) {
return address(this).balance;
}
}
contract SendEther {
function sendViaTransfer(address payable _to) public payable {
// This function is no longer recommended for sending Ether.
_to.transfer(msg.value);
}
function sendViaSend(address payable _to) public payable {
// Send returns a boolean value indicating success or failure.
// This function is not recommended for sending Ether.
bool sent = _to.send(msg.value);
require(sent, "Failed to send Ether");
}
function sendViaCall(address payable _to) public payable {
// Call returns a boolean value indicating success or failure.
// This is the current recommended method to use.
(bool sent, bytes memory data) = _to.call{value: msg.value}("");
require(sent, "Failed to send Ether");
}
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!