fallback is a function that takes no arguments and returns nothing.
It executes when a function that does not exist or ether is sent directly to the contract, but receive() does not exist or msg.data is not empty fallback is called with a limit of 2300 gas when transfer or send is called.
fallback
是一个不接受任何参数且不返回任何内容的函数。
它在何时执行
调用不存在的函数或
以太币直接发送到合约,但
receive()
不存在或
msg.data
不为空
fallback
被调用时有 2300 气体限制
transfer
或者
send
.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
contract Fallback {
event Log(uint gas);
// Fallback function must be declared as external.
fallback() external payable {
// send / transfer (forwards 2300 gas to this fallback function)
// call (forwards all of the gas)
emit Log(gasleft());
}
// Helper function to check the balance of this contract
function getBalance() public view returns (uint) {
return address(this).balance;
}
}
contract SendToFallback {
function transferToFallback(address payable _to) public payable {
_to.transfer(msg.value);
}
function callFallback(address payable _to) public payable {
(bool sent, ) = _to.call{value: msg.value}("");
require(sent, "Failed to send Ether");
}
}