Solidity needs a dedicated math library

I believe it is about time we talked about a math library for solidity:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
library math
{
//dedicated math library
function add(uint a, uint b) internal view returns(uint)
{
//begin function
return a+b;
}
//end function
function sub(uint a, uint b) internal view returns(uint)
{
//begin function
return a-b;
}
//end function
function mult(uint a, uint b) internal view returns(uint)
{
//begin function
return ab;
}
//end function
function div(uint a, uint b) internal view returns(uint)
{
//begin function
require(a > b, “cannot divide this”);
return a/b;
}
//end function
function random(uint n) internal view returns(uint)
{
//begin function
//not cryptographically secure
return n
9+1;
}
//end function
function abs(uint n) internal view returns(uint)
{
//begin function
//absolute value
return 0+n;
}
//end function

}
//end library

2 Likes

Do you think it should be builtin or an open source library? You’re welcome to publish to GitHub. There’s some similar stuff out there, like this: GitHub - barakman/solidity-big-number

I’m not certain but I think this might use a lot more gas for the function calls, and I don’t know if the compiler can automatically inline function calls. It’s worth looking into.

2 Likes

I think building them in is worth looking into. After all, other languages have internal calls that use under the hood algorithms. Using something like safemath would cancel out such internal functions and you can still set gas limits.

So, a couple of points. Firstly, there are definitely plans for a Solidity standard library, and there’s even a prototype PR that moves the cryptographic (SHA256, RIPEMD160, etc.) builtins into the standard library; take a look at this test for an example of usage.

However (and this is a big however), the prerequisite for a proper standard library is the implementation of generics, which is going to be a trigger for the major 1.0.0 release, and this is quite a ways away. Having said that, the draft PR I linked above will certainly be merged as an experimental feature prior to the implementation of generics, but it’s really not going to have much of any use until said generics are implemented.

Also, the standard library is not going to be a builtin per se, although I guess our definitions of builtins may be different. The goal is for the standard library to be shipped with the compiler, but fully implemented in Solidity, so it technically won’t be builtin (at least as per our definition of builtin).

In the meantime, I suggest using the existing external math libraries, as @mikebolt mentioned.

2 Likes

Thank you for that information. It is a good thing to see that some sort of standard library is a part of the project roadmap.