13

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

https://github.com/decentraland/mana/blob/master/contracts/ContinuousSale.sol#L10

21

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 Sep 5 '17 at 7:51
  • @giuseppe-bertone thanks. I did not know 'using' meaning. – zono Sep 5 '17 at 7:55
  • 4
    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. – Daniel Hume Feb 5 '18 at 19:09
11

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 Sep 5 '17 at 7:54

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.