跳转至

26.SendETH

How to send Ether?

// SPDX-License-Identifier: MITpragma solidity ^0.8.18;contract Payable {    // payable 标记函数:接收以太币,接收以后存储到合约中    function deposit1() external payable {        // 处理接收到的以太币   }​    function deposit2() external {}​    // payable 标记函数    function withdraw() external {        // msg.sender合约的调用者        // 把当前合约的所有余额全部转到调用者        payable(msg.sender).transfer(address(this).balance);   }​    // 通过balance属性来查看余额    function getBalance() external view returns (uint256) {        return address(this).balance;   }}solidity

transfer (2300 gas, throws error)

send (2300 gas, returns bool)

call (forward all gas or set gas, returns bool)

How to receive Ether?

A contract receiving Ether must have at least one of the functions below

receive() external payable

fallback() external payable

receive() is called if msg.data is empty, otherwise fallback() is called.

Which method should you use?

call in combination with re-entrancy guard is the recommended method to use after December 2019.Guard against re-entrancy by

  • making all state changes before calling other contracts
  • using re-entrancy guard modifier