Hi I just started to study solidity. Can you tell me what is using SafeMath for uint256;?



2 Answers 2


SafeMath is a solidity math library especially designed to support safe math operations: safe means that it prevents overflow when working with uint. You can find it in zeppelin-solidity SafeMath.

From the official documentation:

The directive using A for B; can be used to attach library functions (from the library A) to any type (B). These functions will receive the object they are called on as their first parameter (like the self variable in Python).

The effect of using A for *; is that the functions from the library A are attached to any type.

Hope it helps~

  • great answer! I did not know about library. thanks. I will accept your answer.
    – zono
    Commented Sep 5, 2017 at 7:51
  • @giuseppe-bertone thanks. I did not know 'using' meaning.
    – zono
    Commented Sep 5, 2017 at 7:55
  • 8
    It's very important to note that your arithmetic operations do not become magically 'safe' just by including the SafeMath library and adding the line using SafeMath for uint256;. You must also replace each +, -, *, and / with the equivalent .add(), .sub(), .mul() and .div() functions. Commented Feb 5, 2018 at 19:09
  • 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. Commented Dec 17, 2020 at 14:24

using ... for ... is explained in Solidity's documentation, here, and is a way to attach library functions to a given type.

So in your case:

using SafeMath for uint256;

...means that the functions contained in the SafeMath.sol library can be used directly on objects of type uint256.

Taking an example from that contract, here we can see that weiAmount is declared as a uint256, and we can then directly call the attached .mul() function on it, rather that passing the variable as a function argument.

uint256 weiAmount = msg.value;

// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
  • thanks! yes. I did not understand '.mul()'. now I got it.
    – zono
    Commented Sep 5, 2017 at 7:54

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.