4

I see many ICOs using SafeMath.sol. An example function in this contract is:

function safeAdd(uint256 x, uint256 y) internal returns(uint256) {
  uint256 z = x + y;
  assert((z >= x) && (z >= y));
  return z;
}

What is the reason for this function at all? Why not just add the two values? What additional functionality does this safeAdd function provide?

http://zeppelin-solidity.readthedocs.io/en/latest/safemath.html

7

Update: Solidity 0.8.0 has added built-in support for checked math and SafeMath is no longer needed.

This prevents unsigned integer overflow issue.

Ethereum Virtual Machine (EVM) itself doesn't do anything if you add two integers together that together exceed the max integer value (2^256-1). Instead, the summed integer will overflow and sum calculation result will be incorrect.

  • 1
    That being said, people use it indiscriminately when it is not needed and create contracts that need more gas than necessary. – Dave Appleton Sep 10 '17 at 9:47
  • @DaveAppleton can you provide any particular examples of when it shouldn't be used? I think it's still within the scope of the original question ("Why not just add the two values?") to indicate circumstances under which we should do exactly that. – Daniel Hume Feb 5 '18 at 20:33
  • 1
    @DaveAppleton I feel a proper fix would be include carry detection etc. in EVM so that you can enable safe math throughout the code. This SafeMath stuff feels just like a fix on a wrong layer. – Mikko Ohtamaa Feb 6 '18 at 8:39
  • 1
    There are certain occasions where you have already put the constraints in place and are absolutely certain that the overflow cannot occur - most particularly when the calculation depends on NO user input. However - the number of places where people have screwed up has made me soften my position a bit. – Dave Appleton Apr 25 '18 at 13:40
  • 1
    Please note that Solidity v0.8.0 checks arithmetic operations by default, which means that overflow and underflow will cause a revert. SafeMath is no longer required after v0.8.0. – Shane Fontaine Dec 17 '20 at 14:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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