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:
- select Account#1 from the Accounts Dropdown
- Value: 1 Ether
- Hit the āsendMoneyā button
- Select Account#3 from the Accounts Dropdown
- Copy the Address And Paste it in the āwithdrawMoneyā Input field
- Add ā500000000000000000ā as amount
- Switch back to Account#1 and hit the āwithdrawMoneyā button.
- 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.