I'm going through the Ethernaut challenges to learn Solidity, and in challenge 3 ("Coin Flip"), they show the following code which subtracts 1 from the current block number:
I assumed that this "sub()" function was a built-in subtraction function, but it seems like it must be defined in OpenZeppelin's SafeMath.sol library, because when I comment out the use of SafeMath in this simple example, I get a compiler warning:
However, when I look in SafeMath.sol, I do not see a single-parameter version of the sub() function. There is only a two-parameter and three-parameter version of sub() defined there:
Where is this single-parameter version of the sub() function defined?
Best Answer
The function you have seen in SafeMath.sol :
Is the one that is implicitly called with
block.number.sub(1)
. That is the case because SafeMath.sol is alibrary
that is attached to the typeuint256
. You can see it in the Etherenaut challenge contract at this line :It is described in the documentation, for the mismatching number of parameters, this is the relevant part to read :
But you can also use the library directly, the two syntax shown in this example are entirely equivalent :
Obviously, using the
variable.sub(...)
syntax is way more convenient, and it is the intended goal of theusing X for Y;
statement.I hope that answers your question.