DEV Community

Cover image for Day 25 - Fallback and receive Functions
Vedant Chainani
Vedant Chainani

Posted on • Edited on

Day 25 - Fallback and receive Functions

GitHub logo Envoy-VC / 30-Days-of-Solidity

30 Days of Solidity step-by-step guide to learn Smart Contract Development.

This is Day 25 of 30 in Solidity Series
Today I Learned About fallback and receive Functions in Solidity.

The solidity fallback function is executed if none of the other functions match the function identifier or no data was provided with the function call. Only one unnamed function can be assigned to a contract and it is executed whenever the contract receives plain Ether without any data. To receive Ether and add it to the total balance of the contract, the fallback function must be marked payable. If no such function exists, the contract cannot receive Ether through regular transactions and will throw an exception.

Properties of a fallback function:

  • Has no name or arguments.
  • If it is not marked payable, the contract will throw an exception if it receives plain ether without data.
  • Can not return anything.
  • Can be defined once per contract.
  • It is also executed if the caller meant to call a function that is not available
  • It is mandatory to mark it external.
  • It is limited to 2300 gas when called by another function. It is so for as to make this function call as cheap as possible.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract Receiver{
    mapping(address => uint) public addressToAmount;

    receive() external payable {
        addressToAmount[msg.sender] += msg.value;
    }
}

contract Sender {
    uint amount = 1 ether;
    address payable _receiver = payable(0xcD6a42782d230D7c13A74ddec5dD140e55499Df9);
    function sendEther() public payable {
        _receiver.transfer(amount);
    }
}
Enter fullscreen mode Exit fullscreen mode

fallback()

This function is called for all messages sent to this contract, except plain Ether transfers (there is no other function except the receive function). Any call with non-empty calldata to this contract will execute

receive()

This function is called for plain Ether transfers, i.e. for every call with empty calldata.


Top comments (0)