SafeMath to protect from overflows

Considering security is a big part of writing good Ethereum smart contracts. A common problem when dealing with numeric operations is the risk of overflow. In this article we will introduce to the SafeMath library available in the open zeppelin smart contracts collection.

What is an overflow?

An overflow/underflow happens when an arithmetic operation reach the maximum or minimum size of the type. For example if you store your number in the uint256  type, it means your number will be stored in a 256 bits unsigned number ranging from 0 to 2^256. In computer programming, an integer overflow occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of bits – either larger than the maximum or lower than the minimum representable value.

The most common result of an overflow is that the least significant representable bits of the result are stored; the result is said to wrap around the maximum (i.e. modulo power of two).

An overflow condition gives incorrect results and, particularly if the possibility has not been anticipated, can compromise a program’s reliability and security.


Let’s protect!

This could happen whenever you are doing arithmetic operations such as + , - ,  * . When using the SafeMath library, the results of this operations will be checked and an error will be thrown stopping the execution of your smart contract.

Here is the code:

To use a Solidity library, just type inside of your contrat and you can then call the public functions defined by your library:

For example this little smart contracts that does nothing but just storing safely the result of an addition:

Don’t hesitate to use the SafeMath library to protect from inputs that could make your contract do unexpected things after overflow or underflow leading arithmetic operations.




Leave a Comment