Back

blockchain - solidity - 特殊函数:receive(), fallback(), payable (modifier)

发布时间: 2024-04-14 10:10:00

refer to:
https://shishirsingh66g.medium.com/solidity-part-2-payable-fallback-and-receive-42c00cb75108#d763-5d1cfd4634ff

payable: 这是一个modifier, 对于任何可以接受ETH的方法,都要有该修饰符,否则无法接受ETH

例如:

receive(): 特殊函数,用来处理某个contract接收ETH时所触发的行为。

例子:

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.13;

contract Receive {
    event GotEther(uint256 amount);
    uint256 public lastPaymentAmount;
    receive() external payable{
      lastPaymentAmount = msg.value;
      emit GotEther(msg.value);
    }
}

向该contract转账:

contract ReceiveTest is Test{
  Receive myContract;

  function setUp() public {
    myContract = new Receive();
  }

  function testReceive() public {

    console2.log("== current address:", address(this));
    console2.log("== balance: ", address(this).balance);
    vm.deal(address(this), 1000 ether);
    console2.log("== balance2:", address(this).balance);
    address(myContract).call { value: 1 ether } ("");
    assertEq(1 ether, myContract.lastPaymentAmount());
    assertEq(1 ether, address(myContract).balance);

  }
}

结果:

fallback(): 当某个contract被调用不存在的函数或者 发送的data是空时,被调用。

例子:

Back