I have a solidity smart contract like this pragma solidity >=0.7.0 <0.9.0;
can I still import SafeMath even if it's not needed for 0.8+ ? Since SafeMath is working with 0.7, but my contract specifies it accepts 0.7.0 up to lower than 0.9.0 what will SafeMath do in this case.
The SafeMath library validates if an arithmetic operation would result in an integer overflow/underflow. If it would, the library throws an exception, effectively reverting the transaction.
Since Solidity 0.8, the overflow/underflow check is implemented on the language level - it adds the validation to the bytecode during compilation.
You don't need the SafeMath library for Solidity 0.8+. You're still free to use it in this version, it will just perform the same validation twice (one on the language level and one in the library).
And it's strongly recommended to use it in 0.7, since the validation is not performed on the language level in this version yet.
So if you allow your contract to be compiled in both versions, you should include the library.
pragma solidity >=0.7.0 <0.9.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract MyContract {
using SafeMath for uint256;
function foo() external pure {
uint256 number = 1;
number.add(1);
}
}