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?



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.

| improve this answer | |
  • 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
  • @DaveAppleton Based on experience with actual CPU architectures, the cost of executing overflow exception (interrupt) on VM level is next to nothing. I do not know if EVM would be any different. I would tackle this problem with new CPU instruction that sets EVM to no-overflow mode (maps to enable/disable overflow check command in Solidity) and then just illegally jump if an overflow is encountered. Overflows have practical use maybe only in crypto calculations that tend to be too expensive for smart contracts anyway. – Mikko Ohtamaa Apr 26 '18 at 8:21

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.