Skip to main content

发送以太币

发送以太币

转账、发送、调用

1.如何发送以太币?

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

  1. transfer(2300 Gas,抛出错误)
  2. send(2300 Gas,返回布尔值)
  3. call(转发所有gas或设置gas,返回bool)

2.如何接收以太币?

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

  1. receive() external payable
  2. fallback() external payable

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

3.您应该使用哪种方法?

call与重入防护结合使用是 2019 年 12 月之后推荐使用的方法。

防止重入

  • 在调用其他合约之前更改所有状态
  • 使用可重入保护修饰符
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

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");
}
}