Skip to content

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.

  1. Deploy the Contract
  2. Ether 1 Ether in the input field
  3. Send it to the receive Money Function

Great, you have 1 Ether in your on-chain Wallet. Let's bring it back out!

  1. Copy your address
  2. Enter it into the withdraw money address field
  3. 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:

  1. Enter 1 Ether into the input field
  2. 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...


Last update: May 23, 2021