Fallback Function and Receive Ether Function

Published by Mario Oettler on

A fallback function is a function within a smart contract that is called if no other function in the contract matches the specified function in the call. This can happen if the call has a typo or if it specifies no function at all.

Solidity knows two different functions for that purpose – fallback() and receive().

receive()

The receive() method is used as a fallback function if Ether are sent to the contract and no calldata are provided (no function is specified). It can take any value. If the receive() function doesn’t exist, the fallback() method is used.

A contract can have at most one receive() function. The receive() function is declared:

receive() external payable{
  // your code here…
} 

The keyword external says that only EOAs and other smart contracts can call this function. Functions marked with external cannot be called from within the smart contract in which they are declared.

fallback()

The fallback() function is used if a smart contract is called and no other function matches (not even the receive() function).

It works, if calldata are included. But it is optionally payable.

The declaration looks like that:

fallback() external [payable] {
  // your code here…
}

The keyword external says that only EOAs and other smart contracts can call this function. Functions marked with external cannot be called from within the smart contract in which they are declared.

Categories: