1

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 ?

2 Answers 2

2

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.

2

That's a nasty way to do it and I don't think it's reliable.

Use the SafeMath method.

If a + b = c, then c must be more than a or an overflow has occured.

From SafeMath:

function add(uint256 a, uint256 b) internal pure returns (uint256) {
  uint256 c = a + b;
  require(c >= a);
  return c;
}

Hope it helps.

1
  • Thanks a lot for your answer. I am aware of SafeMath from OpenZeppelin. I was curious to learn if there is any meaning behind the specific choice of number or it's totally arbitrary.
    – Laxmana
    Apr 23, 2019 at 11:51

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.