Contract Example¶
Let's start with a simple wallet-like Smart Contract that you probably know already from previous labs:
//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);
}
}
Try the Smart Contract¶
What does the contract do? Let's give it a try! Head over to the Deploy and Run Transactions tab.
- Deploy the Contract
- Ether 1 Ether in the input field
- Send it to the receive Money Function
Great, you have 1 Ether in your on-chain Wallet. Let's bring it back out!
- Copy your address
- Enter it into the withdraw money address field
- Enter 1 Ether in Wei (10^18): 1000000000000000000 into the amount field
Superb, you got your Ether back out.
Problem¶
Right now, if you want to deposit Ether into the Smart Contract, you need to directly interact with the receiveMoney function. There is no way to simple send 1 Ether to the Contract address and let it deal with the rest. It would simply error out! Give it a try:
- Enter 1 Ether into the input field
- Hit the "transact" button within the low-level interaction section
You will see it will produce an error that looks like this or similar:
Let's add a low level fallback function so we can simply send Ether to our Wallet...