Understanding Receive function and Fallback function in Solidity

Posted by Andylinee on Thursday, January 25, 2024

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 one receive() 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 include external and payable: receive() external payable { ... }.
  • When the contract receives $ETH, the receive() function is triggered. Due to the 2300 gas limit issue when sending $ETH using send() or transfer(), it is advisable to avoid complex logic in the receive() 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: Receive or Fallback

In summary, when a contract receives $ETH:

  • If msg.data is empty and a receive() function exists, receive() will be triggered.
  • If msg.data is not empty or there is no receive() function, fallback() will be triggered. In this case, fallback() must be payable.
  • If both receive() and fallback() 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

Smart Contract