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:
- Deploy a new Version
- Enter 1 Ether in the value field
- Hit the Transact button
- 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!
Last updated on