# Integer overflow and underflow in Solidity: what 0.8 fixed and what it didn't

URL: https://shield.quillaudits.com/learn/vulnerabilities/integer-overflow-underflow/

An integer overflow or underflow is arithmetic that goes past the largest or smallest value its type can hold and wraps around, so a huge number becomes a small one and zero minus one becomes the maximum. Since Solidity 0.8.0 ordinary arithmetic reverts instead of wrapping, but `unchecked` blocks, explicit type conversions, shifts, inline assembly and contracts compiled with older versions still wrap or truncate without a word. Find every place where arithmetic is not checked and show that the inputs an attacker controls can't make it wrap.

Last updated 3 December 2026. 5 minute read. By the QuillAudits Team.

## How does an integer overflow happen?

Solidity integers have a fixed width. A `uint8` holds 0 to 255 and a `uint256` holds 0 to 2^256 minus 1. When a result doesn't fit, the low bits are kept and the rest are dropped: 255 + 1 in a `uint8` becomes 0, and 0 minus 1 becomes 255.

Before 0.8.0 that wrap was silent unless the code used a library such as SafeMath on that exact operation. The [Solidity docs](https://docs.soliditylang.org/en/latest/control-structures.html) now say: 'Since Solidity 0.8.0, all arithmetic operations revert on over- and underflow by default.' The default has exceptions, and they are where the bugs live today.

## Where can arithmetic still wrap in Solidity 0.8?

| Code | Checked? | What happens |
| --- | --- | --- |
| `+`, `-` and `*` in ordinary code | Yes | Reverts on overflow or underflow |
| Anything inside `unchecked { }` | No | Wraps silently; functions called from inside keep their own checks |
| Explicit conversion to a smaller type, such as `uint128(x)` | No | Truncates the high bits and never reverts |
| Shifts, `x << n` and `x >> n` | No | No overflow check; the result is truncated to the type of `x` |
| Inline assembly | No | The docs warn it bypasses several of Solidity's safety checks |
| Contracts compiled with 0.7 or earlier | No | Wraps unless that operation uses SafeMath |

Sources for each row: [checked and unchecked arithmetic](https://docs.soliditylang.org/en/latest/control-structures.html), [shifts](https://docs.soliditylang.org/en/latest/types.html) and [inline assembly](https://docs.soliditylang.org/en/latest/assembly.html).

## What does vulnerable code look like?

Two contracts, two ways to wrap. The token adds up a batch transfer inside an `unchecked` block. The ledger packs debts into `uint128` with a plain conversion.

**Vulnerable: an unchecked batch total and a truncating cast (illustrative, not audited code)** `BatchToken.sol`

```
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

contract BatchToken {
    mapping(address => uint256) public balanceOf;

    constructor(uint256 supply) {
        balanceOf[msg.sender] = supply;
    }

    // Sends `value` to every receiver. The total is computed unchecked "to save gas".
    function batchTransfer(address[] calldata receivers, uint256 value) external {
        uint256 total;
        unchecked {
            total = receivers.length * value; // 2 receivers and value = 2**255 make this 0
        }
        require(balanceOf[msg.sender] >= total, "insufficient balance");
        balanceOf[msg.sender] -= total;
        for (uint256 i = 0; i < receivers.length; i++) {
            balanceOf[receivers[i]] += value;
        }
    }
}

contract PackedLedger {
    mapping(address => uint128) public debt;
    mapping(address => uint256) public collateral;

    function borrow(uint256 amount) external {
        // The conversion keeps the low 128 bits: an amount of 2**128 is recorded as 0.
        debt[msg.sender] += uint128(amount);
        require(uint256(debt[msg.sender]) * 2 <= collateral[msg.sender], "undercollateralized");
        // ... then pays out `amount`
    }
}
```

In the token, a call with two receivers and a value of 2^255 makes the total 2^256, which wraps to 0. The balance check passes, the sender pays nothing, and each receiver is credited 2^255 tokens. In the ledger, a borrow of exactly 2^128 is stored as a debt of 0 and passes the collateral check.

## How do you fix it?

**Fixed: checked math, bounded inputs and a checked cast (illustrative, not audited code)** `BatchTokenFixed.sol`

```
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

contract BatchTokenFixed {
    uint256 public constant MAX_RECEIVERS = 200;
    mapping(address => uint256) public balanceOf;

    constructor(uint256 supply) {
        balanceOf[msg.sender] = supply;
    }

    function batchTransfer(address[] calldata receivers, uint256 value) external {
        uint256 count = receivers.length;
        require(count > 0 && count <= MAX_RECEIVERS, "bad receiver count");
        uint256 total = count * value; // checked: reverts instead of wrapping
        require(balanceOf[msg.sender] >= total, "insufficient balance");
        balanceOf[msg.sender] -= total;
        for (uint256 i = 0; i < count; ) {
            balanceOf[receivers[i]] += value;
            unchecked {
                ++i; // can't wrap: i < count <= MAX_RECEIVERS
            }
        }
    }
}

contract PackedLedgerFixed {
    mapping(address => uint128) public debt;
    mapping(address => uint256) public collateral;

    function toUint128(uint256 x) internal pure returns (uint128) {
        require(x <= type(uint128).max, "does not fit in uint128");
        // forge-lint: disable-next-line(unsafe-typecast)
        return uint128(x); // safe: bounded on the line above
    }

    function borrow(uint256 amount) external {
        debt[msg.sender] += toUint128(amount);
        require(uint256(debt[msg.sender]) * 2 <= collateral[msg.sender], "undercollateralized");
        // ... then pays out `amount`
    }
}
```

- **Leave arithmetic checked unless you can prove it can't wrap.** Keep `unchecked` for cases like the loop counter above, and write the proof in a comment next to the block.
- **Bound inputs the math assumes are small.** A maximum number of receivers, a supply cap or a maximum per call keeps every intermediate value inside its type.
- **Convert with a check.** Use a helper that reverts when a value doesn't fit the smaller type, everywhere you narrow a type.
- **Treat shifts and assembly as unchecked code.** Review them the same way as an `unchecked` block.
- **Review what you call as well as what you wrote.** A protocol that integrates an older contract inherits its arithmetic.

## How has it been exploited?

| Protocol | Truebit |
| --- | --- |
| Date | 8 January 2026 |
| Chain | Ethereum |
| Loss | about 8,535 ETH, around $26.4M at the time |
| What happened | Truebit's Purchase contract was compiled with Solidity 0.6.10, which has no automatic overflow checks. Its purchase price calculation used SafeMath for multiplications but the plain + operator for one addition in the numerator. The attacker asked for an amount that made that sum overflow, so getPurchasePrice returned 0, bought TRU through buyTRU for nothing and sold it back through sellTRU for ETH, repeating the cycle within one transaction. BlockSec counts about 240 million TRU taken for free in the first round alone, sold for 5,105 ETH. |
| Sources | [SlowMist](https://slowmist.medium.com/26-44-million-stolen-truebit-protocol-smart-contract-vulnerability-analysis-e44fe7becd8a), [BlockSec](https://blocksec.com/blog/in-depth-analysis-the-truebit-incident), [Cointelegraph](https://cointelegraph.com/news/defi-hacks-169m-q1-2026-crypto-exploits-decline) |

The contract predates Solidity 0.8, and [SlowMist](https://slowmist.medium.com/26-44-million-stolen-truebit-protocol-smart-contract-vulnerability-analysis-e44fe7becd8a) notes that the multiplications in the same calculation did use SafeMath. One addition without it was enough, and nothing in the protocol's newer code could protect an old contract that still held funds.

## What should a reviewer check?

- Search for `unchecked` and, for each block, write down why nothing inside can wrap with inputs an attacker controls.
- Search for narrowing conversions: `uint128(`, `uint96(`, `uint64(`, `int128(`, and `uint256(` applied to a signed value.
- Review every shift and every arithmetic opcode in inline assembly as unchecked code.
- Check the compiler version of every contract in scope and every contract it calls. Anything older than 0.8.0 needs SafeMath on each operation.
- Look for multiplications that can exceed 2^256 with large but valid inputs, such as squares, products of two amounts and price times quantity.
- Are user-supplied amounts capped wherever the math assumes they are small?
- Fuzz pricing and accounting functions with values at the edges: 0, 1, 2^128, 2^255 and `type(uint256).max`.

## How does QuillShield check for integer overflow and underflow?

The risky arithmetic is rarely the line that looks risky: it is an `unchecked` block or a cast that is fine for the values the author imagined and wrong for the values an attacker can pass. QuillShield's full audit works on the Solidity codebase in your Foundry project. It builds a security graph of the code, lists the invariants the code must keep and sends every finding to a separate reviewer agent that tries to disprove it, so what you receive comes with the exact lines, the impact, a recommended fix and, for full audits, a proof of concept.

Gas work is where new `unchecked` blocks appear, usually in a small pull request after the audit. QuillShield checks every pull request on GitHub or GitLab.com against the audit's security graph, and on GitHub, with branch protection or rulesets, a required QuillShield check blocks the merge while a High or Critical finding is open.

Prices are on the [pricing page](https://shield.quillaudits.com/pricing/): a full audit starts at $49, and 1,000 lines of Solidity cost $379 as of November 2026. [Start free](https://shield.quillaudits.com/register) and get the exact quote for your code before anything is charged.

## FAQ

### Does Solidity 0.8 prevent integer overflow?

For ordinary arithmetic, yes: it reverts. Not inside `unchecked` blocks, not in explicit conversions, which truncate, not in shifts or inline assembly, and not in contracts compiled with older versions.

### Is it safe to use unchecked for loop counters?

Usually, when the counter is compared with an array length before it increments, because it can't pass `type(uint256).max` first. Write that reasoning in a comment, and don't let the block grow to include other arithmetic.

### Do I still need SafeMath?

Not in 0.8 code for ordinary arithmetic. Contracts compiled with 0.7 or earlier still need it on every operation, or a migration to a newer compiler.

### Can a checked overflow still cause harm?

Yes. The revert stops the theft, but it can also stop a function for good, for example a counter that has reached its type's limit. If that function is the only way to withdraw, the funds are stuck; see [denial of service](https://shield.quillaudits.com/learn/vulnerabilities/denial-of-service/).

### Which SWC entry covers integer overflow?

[SWC-101, Integer Overflow and Underflow](https://swcregistry.io/docs/SWC-101/). Its remediation is to use vetted safe math libraries; in 0.8 code the same advice means keeping arithmetic checked. The [OWASP Smart Contract Top 10 (2025)](https://owasp.org/projects/smart-contract-top-10) lists the class as SC08, Integer Overflow and Underflow.

## Sources

- [Expressions and control structures: checked or unchecked arithmetic, Solidity documentation](https://docs.soliditylang.org/en/latest/control-structures.html) · checked 3 December 2026
- [Types: shifts, Solidity documentation](https://docs.soliditylang.org/en/latest/types.html) · checked 3 December 2026
- [Inline assembly, Solidity documentation](https://docs.soliditylang.org/en/latest/assembly.html) · checked 3 December 2026
- [SWC-101: Integer Overflow and Underflow, SWC Registry](https://swcregistry.io/docs/SWC-101/) · checked 3 December 2026
- [26.44 Million Stolen: Truebit Protocol Smart Contract Vulnerability Analysis, SlowMist](https://slowmist.medium.com/26-44-million-stolen-truebit-protocol-smart-contract-vulnerability-analysis-e44fe7becd8a) · checked 3 December 2026
- [In-Depth Analysis: The Truebit Incident, BlockSec](https://blocksec.com/blog/in-depth-analysis-the-truebit-incident) · checked 3 December 2026
- [Crypto hackers steal $169M from 34 DeFi protocols in Q1: DefiLlama, Cointelegraph](https://cointelegraph.com/news/defi-hacks-169m-q1-2026-crypto-exploits-decline) · checked 3 December 2026
- [OWASP Smart Contract Top 10 (2025), OWASP](https://owasp.org/projects/smart-contract-top-10) · checked 3 December 2026
