Solidity 特殊函数
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是空时,被调用。
例子: