Solidity supports two types of callback functions, namely receive()
and fallback()
, primarily used for the following scenarios:
- Receiving $ETH
- Handling function calls that do not exist in the contract
Receive function: receive()
receive()
is a function called when a contract receives an $ETH transfer. A contract can have at most onereceive()
function.- The declaration of
receive()
differs from other functions; it does not require the function keyword, cannot have any parameters, cannot return any value, and must includeexternal
andpayable
:receive() external payable { ... }
. - When the contract receives $ETH, the
receive()
function is triggered. Due to the 2300 gas limit issue when sending $ETH usingsend()
ortransfer()
, it is advisable to avoid complex logic in thereceive()
function to prevent Out of Gas errors.
Fallback function: fallback()
The fallback()
function is triggered when a non-existent function in the contract is called and can also be used for “proxy contracts.”
Declaring the fallback()
function similarly does not require the function keyword, must use external modifier, and typically includes the payable modifier: fallback() external payable { ... }
.
receive() vs. fallback()
Both receive()
and fallback()
can be used to receive $ETH, and the triggering rules are illustrated in the diagram below:
In summary, when a contract receives $ETH:
- If
msg.data
is empty and areceive()
function exists,receive()
will be triggered. - If
msg.data
is not empty or there is noreceive()
function,fallback()
will be triggered. In this case,fallback()
must be payable. - If both
receive()
andfallback()
do not exist, sending $ETH directly to the contract will result in an error (but it is still possible to send $ETH to the contract through functions with the payable modifier).
Smart Contract Implementation