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 and
receive()
is not defined. - Both functions must be marked
external payable
to receive Ether. - Using
transfer
orsend
imposes a 2300 gas limit on the fallback function, whilecall
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:
- Implement a
fallback()
function that is markedexternal payable
and emits an eventLogFallback
with the remaining gas. - Implement a
receive()
function that is markedexternal payable
and emits an eventLogReceive
with the remaining gas. - Implement a
getBalance()
function that returns the contract's Ether balance.