UnsafeMath for Solidity 0.8.0+


UPDATE: Check out the @0xdoublesharp/unsafe-math module available on NPM for an easy to use, prepackaged, and tested version of this library!

UnsafeMath is a Solidity library used to perform unchecked, or “unsafe”, math operations. Prior to version 0.8.0 all math was unchecked meaning that subtracting 1 from 0 would underflow and result in the max uint256 value. This behavior led many contracts to use the OpenZeppelin SafeMath library to performed checked math – using the prior example subtracting 1 from 0 would throw an exception as a uint256 is unsigned and therefore cannot be negative. In Solidity 0.8.0+ all math operations became checked, but at a cost of more gas used per operation.

Unchecked Math Library

The UnsafeMath library allows you to perform unchecked math operations where you are confident the result will not be an underflow or an overflow of the uint256 space – saving gas in your contracts where checked math is not needed.

[remote_content url='https://gist.githubusercontent.com/doublesharp/d118d865f9bf0af18d93880c9233278b/raw/UnsafeMath.sol' decode_atts="true" htmlentities="true"]

Gas Usage Tests

This test contract uses the UnsafeMath.unsafe_decrement() and Unsafe.unsafe_decrement() functions alongside their checked counterparts to test the difference in gas used between the different methods.

[remote_content url='https://gist.githubusercontent.com/doublesharp/d118d865f9bf0af18d93880c9233278b/raw/TestUnsafeMath.sol' decode_atts="true" htmlentities="true"]

Using a simple Mocha setup, our tests will call each of the contract functions with an argument for 100 iterations.

[remote_content url='https://gist.githubusercontent.com/doublesharp/d118d865f9bf0af18d93880c9233278b/raw/TestUnsafeMath.ts' decode_atts="true" htmlentities="true"]

The results show that a checked incrementing loop used 60276 gas, checked decrementing used 59424 gas, unchecked incrementing used 58117 gas, and unchecked decrementing came in at 57473 gas.

That’s a savings of 2803 gas on a 100 iteration loop, or 4.55% of the total gas used.

[remote_content url='https://gist.githubusercontent.com/doublesharp/d118d865f9bf0af18d93880c9233278b/raw/TestResults.txt' decode_atts="true" htmlentities="true"]

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *