fallback is Backup function of contract
Features
anonymous
external
: we send ether or call function from outside of the contract
payable
: it receives ether
Why use fallback
It makes smart contract to receive ether
It makes smart contract to receive ether and do some action
If unregistered function is called by
call
method, we can set backup action
After 0.6 version
fallback
function has divided into receive
and fallback
.
receive
Triggered for pure ether transfer
fallback
Triggered when function is called & ether transferred
When non-registered function is called
fallback() external payable {
// Something
}
receive() external payable {
// Something
}
Examples
Example 1
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Bank {
event JustFallback(address _from, string message);
event ReceiveFallback(address _from, uint256 _value);
event JustFallbackWithFunds(address _from, uint256 _value, string message);
fallback() external payable {
emit JustFallbackWithFunds(msg.sender, msg.value, "JustFallabackwithFUnds is called");
}
receive() external payable {
emit ReceiveFallback(msg.sender, msg.value);
}
}
contract You {
function depositEther(address payable _to) public payable {
_to.transfer(1 ether);
}
function justGiveMessage(address _to) public {
(bool success, ) = _to.call("HI");
require(success, "Failed");
}
function justGiveMessageWithFunds(address payable _to) public payable {
(bool success, ) = _to.call{value:msg.value}("HI");
require(success, "Failed");
}
}
For pure ether transferring function like
depositEther
,receive
handles it.
For function called related fallbacks like
justGiveMessage
andjustGiveMessage
,fallback
handles it.
ANOTHER KEY POINT
msg.sender => entity that triggers smart contract
For Bank
contract, msg.sender
is You, because What really triggered Bank
's receive
and fallback
functions are You
's functions.
Example 2
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract Chest {
receive() external payable {
}
function getBalance() public view returns (uint256) {
return address(this).balance;
}
}
contract A {
function sendEther(Chest chest) public payable {
address payable chestPayable = payable(address(chest));
chestPayable.transfer(1 ether);
}
}
When inside of receive
function is empty, it automatically stores the transferred ether inside contract's balance.
Top comments (0)