发送eth (transfer, send, call)

如何发送以太币?

如何发送以太币?

您可以通过以下方式将以太币发送到其他合约

  • transfer(2300 gas,抛出错误)
  • send(2300 gas,返回布尔值)
  • call(转发所有gas或设置gas,返回布尔值)

如何接收以太币?

接收 Ether 的合约必须至少具有以下功能之一

  • receive() external payable
  • fallback() external payable

receive()如果msg.data为空则调用,否则fallback()调用。

您应该使用哪种方法?

call2019 年 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");
    }
}
点赞 4
收藏 3
分享

0 条评论

请先 登录 后评论
runtoweb3.com
runtoweb3.com
0x5F12...732b
江湖只有他的大名,没有他的介绍。