I understand why and how to use the SafeMath library. However, I was wondering if there is a kind of best practice guide how and when to use the library and in which cases you don't have to.

From a safety aspect it would be fail resistant to just use it on any any any operation, right? Still there are so many very high quality smart contracts which are still only using the library in some cases but not all. I guess it's for gas efficient purposes?

Is there any recommendation or best practice guide when and when not to use the SafeMath library?

1 Answer 1


As you probably know, the library is used for input validation. So, you should use it when you need to validate the input.

Consider the following example:

pragma solidity ^0.4.24;

contract MyStuff {

    function safeFunc() public pure returns (uint256) {
        uint256 a = 5;
        uint256 b = 6;
        return a + b;

    function unsafeFunc(uint256 a) public pure returns (uint256) {
        uint256 b = 6;
        return a + b;

The safeFunc does not take the numbers as input parameters so it does not necessarily need to validate them. You always know the values are valid as they can't be changed.

The unsafeFunc takes one of the numbers as input parameter so you can't be sure that using the parameter causes no problems. A malicious user may give max(uint256) as parameter and cause an overflow.

Even if SafeMath is not used (even if it should be used), it can be because:

1) Nobody (outside the developers) knows there is an exploit (for example source code not published)

2) The inputs are validated in some other way

3) There is no point/benefit in exploiting the exploit

4) Nobody has noticed the exploit

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.