Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 47 ยท Language Basics

Integers, Overflow and Checked Math

How Solidity 0.8 checks arithmetic, what a panic is, when to use unchecked, how division rounds and how wad and ray fixed-point math works, with BigInt demos.

Integers in a computer have a fixed size, so arithmetic can go out of range. An 8-bit unsigned number tops out at 255, and 255 + 1 does not fit. What a language does at that moment is a design decision, and on a blockchain it is a security decision, because the numbers are often money. For years, Solidity contracts silently wrapped around (255 + 1 became 0), and attackers turned that into real thefts of tokens.

Since Solidity 0.8.0, arithmetic is checked by default: an overflow or underflow stops the transaction and undoes everything. This lesson explains how that works, the escape hatch called unchecked, how division rounds, and how to handle fractions (which the EVM does not have) with fixed-point math. It follows Value Types.

What can go wrong

Overflow The result is above the maximum.
Underflow A uint goes below zero.
Rounding Division drops the remainder.

Each one has caused real losses.

1 / 2

Checked arithmetic

In Solidity 0.8 and later, +, -, *, /, %, ** and the increment operators check their results. If the result would not fit the type, the transaction reverts with a panic, a special kind of error with a numeric code.

SOLIDITY
uint8 x = 255;
x = x + 1;       // reverts: Panic(0x11), arithmetic overflow

uint256 balance = 5;
balance = balance - 6;   // reverts: Panic(0x11), underflow

The panic codes you are likely to meet are:

Code Meaning
0x11 Arithmetic overflow or underflow
0x12 Division or modulo by zero
0x01 A failed assert
0x21 Converting an out-of-range value to an enum
0x32 Array index out of bounds

A panic is not meant to happen in correct code. A well-written contract uses require for things users can get wrong, and panics point at bugs. (More in Control Flow, require, revert and Custom Errors.)

Because the check protects the whole transaction, the old defensive tool called SafeMath (a library that wrapped every operation) is no longer needed for 0.8 code. You will still see it in older contracts, which you may have to read.

Where checks do not apply

Not everything is checked. Two traps stay in Solidity 0.8:

  1. Explicit type conversions truncate. uint8(300) does not revert. It keeps the low 8 bits and gives 44. Converting a big value into a smaller type is a classic place where precision silently disappears.
  2. Shifts do not check overflow. x << 1 can lose high bits without reverting.

When you narrow a type on purpose, check the range yourself first, or use a library that does it.

unchecked blocks

Checks cost gas, because the compiler adds extra instructions to every operation. When you can prove an overflow is impossible, you may switch the checks off inside a block:

SOLIDITY
function sumTo(uint256 n) external pure returns (uint256 total) {
    for (uint256 i = 0; i < n; ) {
        total += i;
        unchecked { ++i; }   // i < n, so i + 1 cannot overflow
    }
}

Here i is always less than n, which is at most 2^256 - 1, so i + 1 cannot wrap. Inside unchecked, overflow wraps around silently, exactly like pre-0.8 Solidity.

Treat unchecked as a sharp tool. Use it only for small, provable spots, usually loop counters, and write a comment that states the proof. Never wrap code that contains user-supplied numbers just to save gas. Gas Costs and Optimization shows how little you save and where it is worth it.

Division and rounding

Integer division truncates toward zero, so for unsigned numbers it always rounds down:

SOLIDITY
uint256 a = 7 / 2;     // 3
uint256 b = 1 / 3;     // 0
uint256 c = 7 % 2;     // 1 (the remainder)
int256 d = -7 / 2;     // -3, truncated toward zero, not -4

The rounding direction matters in finance. If a contract calculates a user's share as amount * rate / 100, the dropped remainder stays in the contract. A safe design rounds in the contract's favor (for example, rounds fees up and withdrawals down), so small errors can never add up to a drain.

Always multiply before you divide to keep precision. Compare (a * 100) / b with (a / b) * 100: the first keeps two digits of fraction, the second throws them away early. The only risk of multiplying first is overflow, and checked math turns that into a revert instead of a wrong answer.

Fixed-point math

There is no float or decimal type for general use, because floating point is not exactly reproducible and rounding can differ across hardware. Contracts store fractions as integers scaled by a power of ten. You decide the scale, and the integer 1,500,000,000,000,000,000 can mean 1.5 when the scale is 10^18.

Two scales are popular in DeFi code:

  • wad: 18 decimals (1.0 is 1e18), the same scale as ether, and common for token amounts and prices.
  • ray: 27 decimals (1.0 is 1e27), used when more precision is needed, such as interest rates compounding over time.

To multiply two wad numbers you multiply the raw integers and divide by the scale once, otherwise the result carries the scale twice:

SOLIDITY
uint256 constant WAD = 1e18;

function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
    return (a * b) / WAD;      // rounds down
}

function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
    return (a * WAD) / b;
}

Adding and subtracting wads needs no adjustment. The intermediate product a * b can overflow even when the final result fits, which is why serious libraries use a "full precision" mulDiv that widens the intermediate value. Libraries such as OpenZeppelin's Math.mulDiv do exactly that, and Using OpenZeppelin shows how to import it.

Wrap-around versus revert, side by side

The first stand-in models fixed-width integers with BigInt. It offers two versions of every operation: the old wrapping behavior (& mask) and the checked behavior that throws. This is the same difference as unchecked versus the 0.8 default, shown in numbers.

JS Wrapping versus checked arithmetic

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The cast line shows why narrowing a type is dangerous: 300 turned into 44 with no error at all.

Wad and ray by hand

The second stand-in implements wadMul, wadDiv and a round-up variant. The key habit is to scale once. Run it and compare 1.5 times 2.25 in real decimal arithmetic with the integer version, and see how rounding direction changes tiny leftovers.

JS Fixed-point wad math

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What is real: checked arithmetic reverting with panic codes, unchecked wrapping, truncating division and casts, and the wad/ray scale idea follow Solidity 0.8. What is the stand-in: BigInt has no width, so the code enforces limits by hand, and nothing here costs gas. Real contracts should reuse audited math libraries instead of copying this toy code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens in Solidity 0.8 when a uint8 holding 255 is incremented by 1 outside an unchecked block?

    Checked arithmetic is the default since 0.8. An overflow reverts the whole transaction with Panic(0x11).
  2. 2. When is an unchecked block appropriate?

    unchecked removes the safety net and saves a little gas. Use it for small, provable spots and say why in a comment.
  3. 3. What is -7 / 2 in Solidity for signed integers?

    Integer division rounds toward zero, so -7 / 2 is -3. For unsigned values this means rounding down.
  4. 4. Why is (a * 100) / b usually safer for precision than (a / b) * 100?

    Dividing early truncates the fractional part, and multiplying afterwards cannot bring it back. Multiply first, divide last, and let checked math catch overflow.
  5. 5. What does uint8(300) give in Solidity 0.8?

    Explicit narrowing conversions keep the low bits and do not revert, so 300 (0x12C) becomes 44 (0x2C).

Summary

  • Since 0.8, arithmetic reverts on overflow, underflow and division by zero with panic codes.
  • Explicit narrowing casts and shifts are not checked, so validate ranges yourself.
  • unchecked { ... } wraps silently and saves gas; use it only for provable spots like loop counters.
  • Integer division truncates toward zero, so round in the contract's favor and multiply before dividing.
  • Fractions are scaled integers: wad is 18 decimals, ray is 27, and you scale only once per multiplication.
  • Use audited libraries such as mulDiv for full-precision math.

Next: Strings, Bytes, Arrays and Structs.