DEV Community

Cover image for Fallback with Examples
MOYED
MOYED

Posted on

Fallback with Examples

fallback is Backup function of contract

Features

  • anonymous
     

  • external : we send ether or call function from outside of the contract
     

  • payable : it receives ether

Why use fallback

  • It makes smart contract to receive ether
     

  • It makes smart contract to receive ether and do some action
     

  • If unregistered function is called by call method, we can set backup action


After 0.6 version

fallback function has divided into receive and fallback.

receive

Triggered for pure ether transfer

fallback

  1. Triggered when function is called & ether transferred

  2. When non-registered function is called

fallback() external payable {
    // Something
}
receive() external payable {
    // Something
}

Enter fullscreen mode Exit fullscreen mode

Examples

Example 1

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract Bank {
    event JustFallback(address _from, string message);
    event ReceiveFallback(address _from, uint256 _value);
    event JustFallbackWithFunds(address _from, uint256 _value, string message);

    fallback() external payable {
        emit JustFallbackWithFunds(msg.sender, msg.value, "JustFallabackwithFUnds is called");
    }
    receive() external payable {
        emit ReceiveFallback(msg.sender, msg.value);
    }
}

contract You {

    function depositEther(address payable _to) public payable {
        _to.transfer(1 ether);
    }

    function justGiveMessage(address _to) public {
        (bool success, ) = _to.call("HI");
        require(success, "Failed");
    }

    function justGiveMessageWithFunds(address payable _to) public payable {
        (bool success, ) = _to.call{value:msg.value}("HI");
        require(success, "Failed");
    }
}
Enter fullscreen mode Exit fullscreen mode
  • For pure ether transferring function like depositEther, receive handles it.
     

  • For function called related fallbacks like justGiveMessage and justGiveMessage, fallback handles it.
     

  • ANOTHER KEY POINT

msg.sender => entity that triggers smart contract

For Bank contract, msg.sender is You, because What really triggered Bank's receive and fallback functions are You's functions.

Example 2

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;

contract Chest {

    receive() external payable {
    }

    function getBalance() public view returns (uint256) {
        return address(this).balance;
    }
}

contract A {
    function sendEther(Chest chest) public payable {
        address payable chestPayable = payable(address(chest));
        chestPayable.transfer(1 ether);
    }
}
Enter fullscreen mode Exit fullscreen mode

When inside of receive function is empty, it automatically stores the transferred ether inside contract's balance.

Top comments (0)