Logo

Fallback and Receive Functions

Learn how to use fallback() and receive() functions in Solidity to handle Ether transfers and unexpected function calls.

Fallback and Receive Functions

In Solidity, the fallback() and receive() functions are special functions that handle calls to functions that do not exist on the contract or direct Ether transfers.

  • receive() is called when the contract receives Ether with empty calldata.
  • fallback() is called when no other function matches the call, or when Ether is sent with non-empty calldata andreceive() is not defined.
  • Both functions must be marked external payable to receive Ether.
  • Using transfer or send imposes a 2300 gas limit on the fallback function, while call forwards all gas.

Why Use fallback() and receive()?

They allow contracts to handle unexpected calls and direct Ether transfers gracefully. Events can be emitted to log such occurrences, and the contract can react accordingly.

Challenge:

  1. Implement a fallback() function that is markedexternal payable and emits an event LogFallback with the remaining gas.
  2. Implement a receive() function that is markedexternal payable and emits an event LogReceive with the remaining gas.
  3. Implement a getBalance() function that returns the contract's Ether balance.