0
0
Blockchain / Solidityprogramming~5 mins

Receive and fallback functions in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Receive and fallback functions let a smart contract accept money and handle calls that don't match any other function.

When your contract needs to accept plain Ether transfers without data.
When you want to handle unexpected calls or wrong function names gracefully.
When you want to log or react to any call that doesn't match existing functions.
When you want to prevent Ether from being sent to your contract accidentally.
When you want to provide a default behavior for unknown function calls.
Syntax
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.

Examples
This receive function allows the contract to accept Ether transfers without any data.
Blockchain / Solidity
receive() external payable {
    // Accept Ether and do nothing else
}
This fallback function logs when it is called, useful for debugging unexpected calls.
Blockchain / Solidity
fallback() external payable {
    // Log that fallback was called
    emit FallbackCalled(msg.sender, msg.value);
}
This example accepts Ether via receive and rejects unknown function calls with an error.
Blockchain / Solidity
receive() external payable {
    balance += msg.value;
}

fallback() external {
    revert("Function does not exist");
}
Sample Program

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.

Blockchain / Solidity
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);
    }
}
OutputSuccess
Important Notes

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.

Summary

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.