DEV Community

Loading Blocks
Loading Blocks

Posted on

Solidity Math & Arithmetic

Basic integer Arithmetic

Solidity provides signed(int) and unsigned(uint) integers.

Common bit widths: uint 8, uint 256(default is unit256)

Operators: + - * / %

Division / is integer division -> result is truncated (rounded down)

solidity does not support floating-point numbers.

Overflow & underflow

Since Solidity 0.8.x

All arithmetic operations have built-in overflow/underflow checks.

if overflow occurs, the transcation reverts.

Example:

uint8 x = 255;
x = x + 1; // Reverts in Solidity 0.8+
Enter fullscreen mode Exit fullscreen mode

before solidity 0.8.x:
arithmetic wrapped arount silently.
Example: uint8(255) + 1 = 0

OpenZeppelin SafeMath(legacy)

In pre-0.8.x, developers used OpenZeppelin's SafeMath to prevent overflow/underflow

In 0.8.x and later, SafeMath is not required since checks are built in.

Example:(solidity 0.7.x)

pragma solidity ^0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";

contract MyContract {
   using SafeMath for uint256;
   uint256 public total;

   function add(uint256 a, uint256 b) external    {
total = a.add(b); //safe addition
}

}
Enter fullscreen mode Exit fullscreen mode

In solidity 0.8.x:

pragma solidity ^0.8.20;

contract MyContract {
uint256 public total;

function add(uint256 a, uint256 b) external {
total = a + b; // Safe by default,Once overflow,the transaction will be reverted and total is not be updated.
}
}

Enter fullscreen mode Exit fullscreen mode

unchecked keyword

In solidity 0.8.x, you can disable overflow checks for gas savings using unchecked.

uint256 x = 255;
unchecked {
    x = x + 1; // Wraps to 0, no revert
}
Enter fullscreen mode Exit fullscreen mode

When to use:

  • Loop counters where overflow is impossible.

  • Gas optimization for safe arithmetic cases.

Common Tricks

Use OpenZeppelin's SafeCast for safe downcasting

import "@openzeppelin/contracts/utils/math/SafeCast.sol";
uint256 big = 1000;
uint128 small = SafeCast.toUint128(big);
Enter fullscreen mode Exit fullscreen mode

summary

All arithmetic operations in Solidity 0.8+ revert on overflow

In earlier versions, arithmetic wraps around silently.

Use SafeMath for explicit overflow checks in Solidity <0.8.

Unchecked blocks can save gas when overflow is impossible.

Top comments (0)