Solidity – Handling Integer Overflow in Smart Contracts

overflowsolidity

In the code of Coin contract at:

https://solidity.readthedocs.io/en/latest/introduction-to-smart-contracts.html#subcurrency-example

there is the following function which requires the amount to be smaller than 10^60.

function mint(address receiver, uint amount) public {
        require(msg.sender == minter);
        require(amount < 1e60);
        balances[receiver] += amount;
    }

I thought that the maximum number an uint can hold is 2^256 ~= 10^77. According to doc:

The second call to require ensures that there will not be too many
coins, which could cause overflow errors later.

What kind of overflow can be caused when the amount is bigger than 10^60 ~= 2^200 ?

Best Answer

I think it's a totally arbitrary number for the sake of the example, probably because someone will need to call the mint function 1.157920892373162e+17 times to actually have an overflow (if they mint an amount just under 1e60).

Plus, it doesn't take in account potential overflow if you transfer tokens to someone else, but again this snippet of code in the solidity docs is just for example.

You should use the SafeMath library whenever you do sensitive arithmetical operations.

Related Topic