Solidity Programming Language – Fallback & Receive
In Solidity, “fallback” and “receive” are special functions related to the handling of ether transactions in smart contracts.
Fallback Function: In earlier versions of Solidity, a function marked as fallback is executed when a contract receives a message that does not match any of its function signatures, or when a contract receives ether without any accompanying data. It’s essentially a catch-all function.
Receive Function: Starting from Solidity version 0.6.0, a new feature called the “receive” function was introduced. This function is similar to the fallback function, but it is only triggered when the contract receives ether without any data. If a contract has a receive function, it cannot have a fallback function.
It’s important to note that in the latest versions of Solidity (from 0.8.0), using the receive
and fallback
functions directly is discouraged, and instead, you should use explicit function definitions. For example, you might want to use receive()
for receiving ether and have separate functions for other functionality.
Here whatever the task performed by the “receiver” function can be handled by the “fallback” function also. But in reverse whatever the function handled by the “fallback” function cannot be handled by by “Receive” function.
Fallback:
- It is executed when a non-existent function is called on the contract.
- It is required to be marked external.
- It has no name.
- It has no arguments
- It cannot return anything
- It can be defined one per contract.
- If not marked payable, it will throw exception if contract receives ether.
- It’s main use is to directly send the ETH to contract.
Code: