2

Can anyone please explain me the meaning of this line "assert(balanceReceived[msg.sender] + msg.value >= balanceReceived[msg.sender]);" in the below code in the function receiveMoney and also the meaning of the line "assert(balanceReceived[msg.sender] >= balanceReceived[msg.sender] - _amount);" in the withdrawMoney function. Is it something related to the wrapping of uint?

pragma solidity ^0.8.16;

contract FunctionExample{
    mapping(address => uint) public balanceReceived;//Storage Variable

    address payable owner;//Storage Variable

    constructor() {
        owner = payable(msg.sender);
    }

    function destroySmartContract() public{
        require(msg.sender == owner,"Only Owner is allowed to do this!");
        selfdestruct(owner);
    }

// A view function can access the state but only in reading way.
// A view function can call the other pure function but a view function cannot call the other writing function.
// A writhing function can call both the view function and the pure function.

    function getOwner() public view returns(address){
        return owner;
    }

// Pure function is the function that don't interact with any storage variable.
// A pure function can call another pure function but a pure function cannot call another view function or a writing function.
    function convertWeiToEther(uint _amountInWei) public pure returns(uint){
        return _amountInWei/1 ether;
    }

    function recieveMoney() 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(balanceReceived[msg.sender] >= _amount,"You dont have enough funds!!");
        assert(balanceReceived[msg.sender] >= balanceReceived[msg.sender] - _amount);
        _to.transfer(_amount);
        balanceReceived[msg.sender] -= _amount;
    }

    fallback () external payable {
        recieveMoney();
    }

    receive () external payable {
        // withdrawMoney(_to, _amount);
    }


}
1

1 Answer 1

2

Yes. It is guarding against underflow and overflow, which is not necessary with the Solidity version that contract is using (^0.8.16). So, it's weird that that contract is using that guard since it's not needed.

If it's your contract, you can remove that check since the version of Solidity the contract is using checks for under and overflows automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.