guys, I am developing ERC-20 token and I am wondering why SafeMath is used as as library in the OpenZeppelin implementation? Will not it be more optimal if we supply it as a base contract on the inheritance chain?
SafeMath's functions are all declared as
internal. That means that the library doesn't actually have to be deployed, as the functions are 'inlined' by the compiler: their code is just copied from the library code to the calling function.
An inheritance relationship like
contract A is B,
A is a
B. In case of
SafeMath, that does not hold if I just want to use
SafeMath's functionality in another contract.
Actually, as far as gas cost is concerned, it is more optimal when used as a library, since you do not make external function calls (the library functions reside within your contract).
In addition, SafeMath is a "library by nature", i.e., it supplies a specific yet general kind of functionality, so it makes a lot more sense to declare it as a library.
The only down side of it being a library, is that if you ever want to make changes in it, then you will have to redeploy the entire contract, since it does not contain a reference to a SafeMath contract, for which you can add a setter function in advance.