Hey Jon. Thanks for the feedback!
- I have read the post and understand the concept of why the order is important.
- I intentionally kept the onlyOwner because I thought the msg.sender (= the person actually trying to call the withdraw function) is any fund-owner not only the smart contract owner. Thanks for clearing it up!
- The comment was unintentionally left from trying something out.
I am pasting the updated code below.
(Edited again, according to the next comment)
pragma solidity 0.7.5;
contract mappings {
mapping(address => uint) balance;
address owner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
constructor(){
owner = msg.sender;
}
event depositDone(uint howMuch, address depositedTo);
function deposit() public payable returns(uint){
balance[msg.sender] += msg.value;
emit depositDone(msg.value, msg.sender);
return balance[msg.sender];
}
function getBalance() public view returns(uint){
return balance[msg.sender];
}
function withdraw(uint _toWithdraw) public returns (uint) {
require(balance[msg.sender] >= _toWithdraw);
balance[msg.sender] -= _toWithdraw;
msg.sender.transfer(_toWithdraw);
return balance[msg.sender];
}
function transfer(address recipient, uint amount) public {
require(balance[msg.sender] >= amount, "Insufficient ammount");
require(msg.sender != recipient);
uint previousSenderBalance = balance[msg.sender];
_transfer(msg.sender, recipient, amount);
assert(balance[msg.sender] == previousSenderBalance - amount);
}
function _transfer(address from, address to, uint amount) private {
balance[from] -= amount;
balance[to] += amount;
}
}