Skip to content

Add partial Withdrawals

Sending all funds is fun, but it isn't very useful. Sometimes, like with a Bank Account, you don't want to send out all the funds you have. You just want to send a little bit. We can do this quite easily with our new mapping.

Add the following things to the Smart Contract:

//SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;

contract MappingsStructExample {

    mapping(address => uint) public balanceReceived;

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

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

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


    function withdrawAllMoney(address payable _to) public {
        uint balanceToSend = balanceReceived[msg.sender];
        balanceReceived[msg.sender] = 0;
        _to.transfer(balanceToSend);
    }
}

To understand what's going on here:

When someone withdraws funds, we check if the amount he wants to withdraw is smaller or equal than the amount he previously deposited. If yes, then we deduct the amount from his balance and send out the funds.

Deploy the new Smart Contract

Head over to the "Deploy & Run Transactions" Plugin and deploy a new Instance.

Deposit and Withdraw 50%

We will deposit 1 Ether from Account#1 and Withdraw 50% to Account#3. I won't provide Screenshots for the first few steps, since it's exactly the same as previously:

  1. select Account#1 from the Accounts Dropdown
  2. Value: 1 Ether
  3. Hit the "sendMoney" button
  4. Select Account#3 from the Accounts Dropdown
  5. Copy the Address And Paste it in the "withdrawMoney" Input field
  6. Add "500000000000000000" as amount
  7. Switch back to Account#1 and hit the "withdrawMoney" button.
  8. Check the Balance of "Account#3"

If you are wondering why my input fields look like in the picture: There is a little down-arrow next to the input fields, so it will open an extended view.

If you followed along in this lab, then you have 102.5 Ether (102.5 * 10^18 Wei) in the Account#3. If you just started with this step, then you have 100.5 Ether in Account#3.

Now, that's all good so far. Let's add another level of complexity to it by using Structs. We define our own Datatypes so we can track single payments from users.


Last update: March 28, 2022