Receive and fallback functions let a smart contract accept money and handle calls that don't match any other function.
Receive and fallback functions in Blockchain / Solidity
receive() external payable {
// code to handle plain Ether transfers
}
fallback() external payable {
// code to handle calls with data or unknown functions
}The receive function is called when the contract receives Ether with empty calldata.
The fallback function is called when no other function matches or when Ether is sent with data.
receive() external payable {
// Accept Ether and do nothing else
}fallback() external payable {
// Log that fallback was called
emit FallbackCalled(msg.sender, msg.value);
}receive() external payable {
balance += msg.value;
}
fallback() external {
revert("Function does not exist");
}This contract has a receive function that emits an event when Ether is sent without data. The fallback function emits an event when the contract receives calls with unknown functions or data.
pragma solidity ^0.8.0;
contract ReceiveFallbackExample {
event Received(address sender, uint amount);
event FallbackCalled(address sender, uint amount, bytes data);
receive() external payable {
emit Received(msg.sender, msg.value);
}
fallback() external payable {
emit FallbackCalled(msg.sender, msg.value, msg.data);
}
}Only one receive function is allowed per contract.
If receive is not defined, fallback handles all calls including plain Ether transfers.
Both functions must be marked external and payable to accept Ether.
Receive function handles plain Ether transfers with empty data.
Fallback function handles calls with unknown functions or data.
Use these functions to safely accept Ether and handle unexpected calls.