Skip to content

The Receive Fallback Function

Solidity 0.6/0.8 Update

Prior Solidity 0.6 the fallback function was simply an anonymous function that looked like this:

function () external {

}

It's now two different functions. receive() to receive money and fallback() to just interact with the Smart Contract without receiving Ether. This example uses the updated version.

Let's add a receive fallback function to the Smart Contract so we can simply send 1 Ether to the Contract without directly interacting with a concrete function.

//SPDX-License-Identifier: MIT

pragma solidity 0.8.3;

contract FunctionsExample {

    mapping(address => uint) public balanceReceived;

    function receiveMoney() public payable {
        assert(balanceReceived[msg.sender] + msg.value >= balanceReceived[msg.sender]);
        balanceReceived[msg.sender] += msg.value;
    }

    function withdrawMoney(address payable _to, uint _amount) public {
        require(_amount <= balanceReceived[msg.sender], "not enough funds.");
        assert(balanceReceived[msg.sender] >= balanceReceived[msg.sender] - _amount);
        balanceReceived[msg.sender] -= _amount;
        _to.transfer(_amount);
    } 

    receive() external payable {
        receiveMoney();
    }
}
Let's try this again:

  1. Deploy a new Version
  2. Enter 1 Ether in the value field
  3. Hit the Transact button
  4. Observe the Transaction Log, see that the transaction goes through now.

Did you see it? Just works like this. It even says .(receive) in the transaction. That's great!

Now onto the constructor!