My assigment of safe math

pragma solidity 0.8.0;
pragma abicoder v2;
import “./Ownable.sol”;
import “./safe_math.sol”

contract Bank is Ownable{

mapping(address => uint) balance;
address[] customers;

event depositDone(uint amount, address indexed depositedTo);

function deposit() public payable returns (uint)  {
    balance[msg.sender].add(msg.value);
    emit depositDone(msg.value, msg.sender);
    return balance[msg.sender];
}

function withdraw(uint amount) public onlyOwner returns (uint){
    require(balance[msg.sender] >= amount);
    balance[msg.sender].sub(amount);
    payable(msg.sender).transfer(amount);
    return balance[msg.sender];
}

function getBalance() public view returns (uint){
    return balance[msg.sender];
}

function transfer(address recipient, uint amount) public {
    require(balance[msg.sender] >= amount, "Balance not sufficient");
    require(msg.sender != recipient, "Don't transfer money to yourself");
    
    uint previousSenderBalance = balance[msg.sender];
    
    _transfer(msg.sender, recipient, amount);
    
    assert(balance[msg.sender] == previousSenderBalance.sub(amount));
}

function _transfer(address from, address to, uint amount) private {
    balance[from].sub(amount);
    balance[to].add(amount);
}

}

1 Like

nice solution. u can just remebe that versions of solidity from 0.8.0 and above have overflow checks buld in so you actually dont need to use safematch here. but its a great learning excercise all the same because the more you interact with other ppls contracts the more diferet versions of solididty youll be playing with so its generally a good idea to use safemath in these scenarios

thanks brother its helps alot

1 Like