# What is unsafe casting in Solidity?

URL: https://shield.quillaudits.com/learn/vulnerabilities/unsafe-casting/

Unsafe casting in Solidity is an explicit type conversion that silently changes a value, such as `uint128(x)` keeping only the low 128 bits of a larger number, or `uint256(x)` turning a negative `int256` into a huge one. Solidity 0.8 checks arithmetic for overflow, but it never checks explicit conversions, so the wrong value is stored without a revert. Bound every input, then cast through a function that reverts when the value doesn't fit, as OpenZeppelin's SafeCast does.

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

## Why doesn't Solidity 0.8 catch it?

Solidity 0.8 checks arithmetic such as `+`, `-` and `*` for overflow. An explicit conversion is not checked: converting to a smaller unsigned type keeps the low-order bits, and converting between signed and unsigned types of the same size reads the same bits the other way. The compiler only refuses a literal that doesn't fit, so `uint128(2**128 + 5)` fails to compile, but the same conversion of a variable compiles and returns 5.

| Conversion | Input | Result |
| --- | --- | --- |
| `uint256` to `uint128` | `2**128 + 5` | `5` |
| `uint256` to `uint64` | `2**64` | `0` |
| `uint256` to `uint32` | `2**32 + 100` | `100` |
| `int256` to `uint256` | `-1` | `2**256 - 1` |
| `uint256` to `int256` | `2**255` | `-2**255` |
| `int256` to `int8` | `200` | `-56` |

Each result above comes from a Foundry test compiled with solc 0.8.28, with the input held in a variable. None of the conversions reverts.

## Where does unsafe casting do damage?

- Packed storage. Structs that squeeze an amount into `uint128` or `uint96` and a timestamp into `uint32` or `uint40` to save gas. A value above the type's maximum is stored as a much smaller one.
- Time. A `uint32` count of seconds runs out on 7 February 2106, and a sum such as `block.timestamp + duration` wraps far sooner when the caller picks the duration.
- Signed values. Profit and loss, funding and price changes are signed. Converting a negative one to `uint256` without a check turns a loss into an enormous number, which either reverts later or, worse, passes a comparison.
- Oracle answers. Price feeds return `int256`, and `uint256(answer)` of a negative answer wraps.
- Assembly and `unchecked` blocks, where even arithmetic isn't checked.

## What does vulnerable code look like?

This vote-escrow lock gives more votes for longer locks and stores the time each lock ends in 32 bits.

**Vulnerable: the lock's end time is cut to 32 bits without a check (illustrative, not audited code)** `TruncatingVoteLock.sol`

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

contract TruncatingVoteLock {
    struct Lock {
        uint128 amount;
        uint32 unlockTime;
    }

    mapping(address => Lock) public locks;
    mapping(address => uint256) public votingPower;

    function lock(uint256 amount, uint256 duration) external {
        require(locks[msg.sender].amount == 0, "already locked");
        // ... pull `amount` tokens from msg.sender
        // A longer lock earns more votes...
        votingPower[msg.sender] = amount * duration / 365 days;
        // ...but both values are cut down without a check. A huge duration makes
        // block.timestamp + duration wrap past 2**32 to a time long gone.
        locks[msg.sender] = Lock(uint128(amount), uint32(block.timestamp + duration));
    }

    function withdraw() external {
        Lock memory l = locks[msg.sender];
        require(l.amount > 0, "nothing locked");
        require(block.timestamp >= l.unlockTime, "still locked");
        delete locks[msg.sender];
        votingPower[msg.sender] = 0;
        // ... send l.amount tokens back to msg.sender
    }
}
```

At 00:00 UTC on 4 December 2026, `block.timestamp` is 1,796,342,400. An attacker locks 1,000 tokens for 2,498,624,897 seconds, about 79 years. The sum is `2**32 + 1`, which `uint32` stores as 1, a moment in 1970. The attacker gets 79,230 votes, uses them, and can withdraw in the same block. Foundry's linter, which runs on `forge build`, flags both casts in this contract as unsafe-typecast warnings.

## How do you fix it?

**Fixed: the duration is bounded and every narrowing cast is checked (illustrative, not audited code)** `CheckedVoteLock.sol`

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

// The same checks OpenZeppelin's SafeCast makes, inlined to keep the example self-contained.
library CheckedCast {
    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);
    }

    function toUint48(uint256 x) internal pure returns (uint48) {
        require(x <= type(uint48).max, "does not fit in uint48");
        // forge-lint: disable-next-line(unsafe-typecast)
        return uint48(x);
    }
}

contract CheckedVoteLock {
    using CheckedCast for uint256;

    struct Lock {
        uint128 amount;
        uint48 unlockTime; // 48 bits of seconds lasts millions of years, unlike 32
    }

    uint256 public constant MAX_LOCK = 4 * 365 days;
    mapping(address => Lock) public locks;
    mapping(address => uint256) public votingPower;

    function lock(uint256 amount, uint256 duration) external {
        require(locks[msg.sender].amount == 0, "already locked");
        // Bound the input first, then cast with a check, so nothing wraps silently.
        require(duration > 0 && duration <= MAX_LOCK, "bad duration");
        // ... pull `amount` tokens from msg.sender
        votingPower[msg.sender] = amount * duration / 365 days;
        locks[msg.sender] = Lock(amount.toUint128(), (block.timestamp + duration).toUint48());
    }

    function withdraw() external {
        Lock memory l = locks[msg.sender];
        require(l.amount > 0, "nothing locked");
        require(block.timestamp >= l.unlockTime, "still locked");
        delete locks[msg.sender];
        votingPower[msg.sender] = 0;
        // ... send l.amount tokens back to msg.sender
    }
}
```

- Bound the input first. A lock can't be longer than `MAX_LOCK`, so whatever the caller passes, the sum stays where the protocol intends.
- Cast with a check. `toUint128` and `toUint48` revert when a value doesn't fit, which is what OpenZeppelin's SafeCast library does for each integer size.
- Pick types with room. 48 bits of seconds lasts millions of years, unlike 32, and `uint128` holds most token amounts, but only a check makes that true for every input.
- Check the sign. Convert a signed value to unsigned only after checking it isn't negative, or branch on the sign and handle both cases.
- Cast once, at the edge. Do arithmetic in `uint256` and narrow the result once, where it is stored, through a checked function.
- Silence the linter only after the check. The fixed library turns off Foundry's unsafe-typecast warning for the single line after each `require`, so every other cast in the codebase still gets flagged.

In the same test, the fixed lock rejected the 79-year duration and accepted a one-year lock.

## How has unsafe casting been exploited?

| Protocol | Notional Finance V1 |
| --- | --- |
| Date | 3 September 2026 |
| Chain | Ethereum |
| Loss | about $1.73M |
| What happened | Between 23:58 UTC on 3 September and 00:01 UTC on 4 September 2026, an attacker drained roughly $1.73M in DAI and USDC from Notional Finance's legacy V1 escrow contract in two transactions. According to [Merkle Science](https://www.merklescience.com/blog/hack-track-notional-finances-legacy-v1-escrow-drained-for-1-7m), the attack ran through two `mintfCashPair()` calls whose debts summed to exactly `2**128`, which overflowed an unchecked `uint128` downcast in the contract's collateral check and truncated a huge liability to zero. [QuillAudits' analysis](https://www.quillaudits.com/blog/hack-analysis/notional-finance-integer-overflow-exploit) places the cast in `ExchangeRate._convertToETH()`, as `uint128 absBalance = uint128(balance.abs())`, and notes that the same file used the reverting `SafeCast.toUint128()` elsewhere. Merkle Science wrote on 7 September that Notional had published no statement or post-mortem. |
| Sources | [Merkle Science](https://www.merklescience.com/blog/hack-track-notional-finances-legacy-v1-escrow-drained-for-1-7m), [QuillAudits](https://www.quillaudits.com/blog/hack-analysis/notional-finance-integer-overflow-exploit) |

The fix was already in the same file, where other conversions went through a checked cast. One raw downcast in the code that values debt was enough to make a debt of `2**128` look like zero.

## What should a reviewer check?

- Find every explicit conversion to a narrower integer type and every conversion between signed and unsigned types.
- For each one, is the value bounded or checked before the cast, and can a caller influence it?
- Are timestamps and durations stored in types that can hold `block.timestamp` plus the longest allowed duration?
- Are signed values such as profit and loss, funding and oracle answers checked for sign before they become unsigned?
- Does any `unchecked` block or assembly rely on a cast elsewhere having been safe?
- Do fuzz tests pass values just above each type's maximum, such as `type(uint128).max + 1` held in a `uint256`?
- Are the unsafe-typecast warnings from `forge build` reviewed one by one rather than silenced in bulk?

## How does QuillShield check for unsafe casting?

A truncating cast is one line, but the damage depends on where the value came from and where the stored result goes next, so a cast has to be read together with its inputs and every later use. QuillShield runs a full audit of a Solidity codebase in a Foundry project. It builds a security graph of the code and lists the invariants the code must keep.

A separate reviewer agent tries to disprove every finding before you see it, and each finding that holds up comes with the exact lines, the impact, a recommended fix and, on full audits, a proof of concept. For a cast, the question a finding has to answer is whether a caller can actually reach it with a value that doesn't fit.

It then checks every pull request on GitHub or GitLab.com against that graph. Gas work that packs a struct tighter is a common source of new casts, so it deserves the same review as new features. [Run a full audit](https://shield.quillaudits.com/register). New accounts get $50 in credit, good for up to half of an order.

## FAQ

### Does Solidity 0.8 check type conversions?

No. It checks arithmetic operators and rejects a literal that doesn't fit, but an explicit conversion of a variable keeps the low-order bits without reverting.

### What is SafeCast?

A library in [OpenZeppelin's utilities](https://docs.openzeppelin.com/contracts/api/utils) with functions such as `toUint128` and `toInt256` that revert when a value doesn't fit the target type. Use it, or the same check written by hand, for every narrowing or sign-changing conversion.

### Is uint32 enough for a timestamp?

For the current time, until 7 February 2106. For the current time plus a duration the caller picks, no: use `uint40` or `uint48` and bound the duration.

### Which SWC and OWASP entries cover unsafe casting?

Neither list has an entry of its own. The nearest are SWC-101 and [SC09:2026](https://scs.owasp.org/sctop10/), both for integer overflow and underflow, because a truncating cast wraps the same way an overflow does.

## Sources

- [Hack Track: Notional Finance's Legacy V1 Escrow Drained for $1.7M, Merkle Science](https://www.merklescience.com/blog/hack-track-notional-finances-legacy-v1-escrow-drained-for-1-7m) · checked 3 December 2026
- [Notional Finance $1.73M Free Collateral Integer Overflow Exploit (Explained), QuillAudits](https://www.quillaudits.com/blog/hack-analysis/notional-finance-integer-overflow-exploit) · checked 3 December 2026
- [Smart Contract Weakness Classification Registry, SWC Registry](https://swcregistry.io/) · checked 3 December 2026
- [Utilities, OpenZeppelin docs](https://docs.openzeppelin.com/contracts/api/utils) · checked 3 December 2026
- [OWASP Smart Contract Top 10: 2026, OWASP](https://scs.owasp.org/sctop10/) · checked 3 December 2026
