pragmasolidity ^0.8.10;contract Fallback {eventLog(uint gas);// Fallback function must be declared as external.fallback() externalpayable {// send / transfer (forwards 2300 gas to this fallback function)// call (forwards all of the gas)emitLog(gasleft()); }// Helper function to check the balance of this contractfunctiongetBalance() publicviewreturns (uint) {returnaddress(this).balance; }}contract SendToFallback {functiontransferToFallback(address payable _to) publicpayable { _to.transfer(msg.value); }functioncallFallback(address payable _to) publicpayable { (bool sent, ) = _to.call{value: msg.value}("");require(sent,"Failed to send Ether"); }}
Fallback Function 有以下的特性:
可視性只能為external
當我們沒有任何payable 的 Function 符合調用,那就會觸發例外處理(exception),除非我們擁有 Fallback function
Fallback Function 就像catch,當我們沒有和任何payable function互動,或沒有任何函式符合交易的encoded data field,就會觸發
pragmasolidity ^0.8.11;contract FunctionsExample{mapping(address=>uint) public balanceReceived;addresspayable owner;constructor() public { owner =payable(msg.sender); }functiongetOwner () publicviewreturns(address){return owner; }functionconvertWeiToEther(uint_amountInWei) publicpurereturns(uint){return _amountInWei /1ether;// alternatively:// return _amountInWei / 10**18; // pure function call only interacte with the variables in this scope like _amountInWei, but not the state variables outside the scope
}functiondestroyContract() public {require(msg.sender == owner,"You are not the owner");selfdestruct(owner); }functionreceiveMoney() publicpayable {assert(balanceReceived[msg.sender] + msg.value >= balanceReceived[msg.sender]); balanceReceived[msg.sender] += msg.value; }functionwithdrawMoney(address payable _to,uint_amount) public {require(balanceReceived[msg.sender] <= _amount,"You don't have enough ether");assert(balanceReceived[msg.sender] >= balanceReceived[msg.sender] - _amount); balanceReceived[msg.sender] -= _amount; _to.transfer(_amount); }fallback () externalpayable{receiveMoney();// fallback function will have input fill(in remix IDE) even we didn't declare any input arguments in function// because the fallback function is triggered automatically no matter have arguments or not.// arguments data is in msg.data }}