2026-10-16

How Clean Is Your Code? Dirty Bits in Solidity

What an addition computes should be obvious. With inline assembly in Solidity, it turns out it isn’t always. The culprit is dirty bits: leftover bits outside a value’s type. Solidity hides them, but assembly sees them. This post expands on our talk at DeFi Security Summit 2026 in Mumbai.

A small puzzle

What does z hold at the end of this snippet: A) 1, B) 257, or C) a revert?

uint256 x = 1;
uint8   y = 0x80;             // y is a uint8: it holds only 8 bits
y = y << 1;                   // 0x80 << 1 = 0x100; truncated to 0 in a uint8

uint256 z;
assembly { z := add(x, y) }   // 1 + 0 = ?

It depends:

  • A) 1 with forge build --via-ir.
  • B) 257 with forge build (legacy pipeline, the default).

The source code and Solidity version are the same and Solidity treats y as 0 in both pipelines. Only the assembly part sees the different values depending on the pipeline. The legacy pipeline leaves the dirty 256 on the stack.

What are dirty bits

Every EVM stack value occupies a 256-bit word. A uint8 uses only the right 8 bits. The other 248 bits fall outside its type. Solidity does not guarantee what those bits contain when assembly reads the value. The Solidity documentation is explicit:

“You cannot make any assumptions about bits not part of the encoding of the type. Especially, do not assume them to be zero.”

The 256-bit stack word holding uint8 y after y << 1 in the legacy pipeline: 30 zero bytes, then a dirty byte 01 produced by the shift, then the clean byte 00 that is the uint8 value. Solidity reads 0, assembly reads 256.

A value is clean when the bits outside its type hold the expected values:

TypeClean formExample
uintNvalue in the right N bits, the rest zerouint8 5 = 0x00…05
intNvalue in the right N bits, the rest copies the sign bitint8 -5 = 0xff…fb
boolexactly 0 or 1true = 0x00…01
addressvalue in the right 160 bits, the left 96 bits zero0x00…00 + 20 address bytes
bytesNvalue in the left N bytes, the rest zerobytes4 0xa9059cbb = 0xa9059cbb00…00

Why the compiler leaves dirt

Solidity and inline assembly both compile to EVM opcodes, which work on full 256-bit words. Cleaning costs gas, so Solidity only cleans where the dirt would change the result. Take uint8 y = 0, held either as the clean word 0x000 or as the dirty word 0x100:

CodeClean y (0x000)Dirty y (0x100)Dirt matters?
Solidity:
bool z;
z = (y == 0);
z = truez = trueno
Assembly:
bool z;
assembly { z := eq(y, 0) }
z = truez = falseyes

Both rows compare y with 0, but only Solidity cleans y first: it compares just the right 8 bits, so the dirt cannot change the result. Assembly’s eq compares the full 256-bit word, and 0x100 is not 0. Plain Solidity always cleans where the dirt would matter. Assembly never cleans for you.

For integers and addresses, like y:

  • The dirt doesn’t matter for add, sub, mul, and, or, xor and not, as long as the result is read back as the same narrow type. Dirt stays in the left bits, and the bits of the type are still correct.
  • The dirt can change the result of comparisons (eq, lt, slt), division (div, mod), right shifts (shr, sar), hashing (keccak256), storing (sstore, mstore), and using y as an index or shift amount.

The two code generator pipelines in solc handle cleanup differently:

Two roommates, two cleaning habits. Legacy (default) leaves the dishes in the sink and washes right before guests arrive: y = y << 1 compiles to shl(1, y), so 0x100 stays on the stack, and y == 0 compiles to eq(and(y, 0xff), 0), washed only there. via-IR washes up right after cooking and never leaves dirty dishes in the sink: y = y << 1 compiles to and(shl(1, y), 0xff), giving 0x00, and y == 0 compiles to eq(y, 0), already clean. Optimized output shown; without --optimize, via-IR also masks before eq.

The via-IR example shows optimized output. Without the optimizer, via-IR masks y a second time before eq. The optimizer can remove redundant cleanup steps.

Reading the raw word from assembly after common Solidity operations shows the difference between the two pipelines:

Plain SolidityRaw word, legacyRaw word, via-IR
uint8 y = 0x80; y = y << 1;2560
uint8 y = 0; y = ~y;2256 − 1255
uint8 y = uint8(uint256(0x1ff));511255
int8 y = 127; unchecked { y += 1; }+128−128
address y = address(uint160(uint256(hash)));full hashlast 160 bits

The legacy pipeline is still common

This is not just a historical concern:

  • Foundry defaults to via_ir = false, and Hardhat likewise leaves Solidity’s viaIR disabled unless explicitly enabled in the compiler settings. Consequently, a standard forge build or Hardhat build uses the legacy Solidity compilation pipeline by default.
  • On a partial sample of contracts verified on Sourcify for Ethereum mainnet (14 October 2026), 61% of the 206 unique bytecodes were compiled with the legacy pipeline.
  • In the Solidity Developer Survey 2025, 35% of respondents said they don’t know what the IR pipeline is.

The front door: ABI decoder v1 and v2

Besides the two pipelines, a second component decides what happens to dirty bits: the ABI decoder. Dirty values can also arrive in calldata, and what happens next depends on the receiving contract’s ABI decoder. The Solidity documentation describes the difference:

“ABI coder v2 supports more types than v1 and performs more sanity checks on the inputs. […] it can also make contract calls revert that did not revert with ABI coder v1 when they contain data that does not conform to the parameter types.”

Compiled withDecoderDirty argument
solc < 0.8v1cleaned
solc ≥ 0.8v2reverted

Above table is a simplification. The exact behaviour depends on the type. The Solidity docs only state that v2 “performs more sanity checks on the inputs” than v1 which can lead to reverts on dirty arguments in v2. Pragmas and flags can change which decoder is used in addition:

  • pragma experimental ABIEncoderV2 selects v2 for solc < 0.8.
  • pragma abicoder v1 selects v1 for solc ≥ 0.8.
  • --via-ir ignores pragma abicoder v1 and uses v2.

The rest of this section walks through a real example of how the receiving contract’s decoder decides what happens to a dirty argument. Consider a router that tries to send a token to a Uniswap V2 pair. The pair is the receiver, called to: the address the router wants to send the ERC-20 tokens to. The router, the sending contract, constructs to itself:

  1. The router computes the pair address from its CREATE2 inputs, like Uniswap V2’s pairFor and V3’s PoolAddress.computeAddress: to = address(uint160(uint256(keccak256(create2Input)))).

  2. With the legacy pipeline, this cast leaves the full hash on the stack, so to is dirty. This is the dirty-bit source.

  3. To pay the pair, the router calls safeTransfer(token, to, amount) from an old version of Solmate’s SafeTransferLib. This library function then calls token.transfer(to, amount), building the calldata in assembly and copying to without a mask:

    assembly {
        mstore(add(p, 4), to)                 // token receiver address `to` is copied raw: may be dirty
        // ...
        call(gas(), token, 0, p, 68, 0, 32)   // token.transfer(to, amount)
    }
  4. The token receives a dirty address. Its decoder is the dirty-bit sink:

    • Tokens with decoder v1 mask the address, and the transfer works.
    • Tokens with decoder v2 revert. UNI, COMP and FRAX were compiled before 0.8 but enable v2 with pragma experimental ABIEncoderV2. CRV (Vyper) also rejects the dirty address.

The same router therefore works with some tokens and reverts with others. Solmate fixed this (in PR #347) by masking every address argument:

and(to, 0xffffffffffffffffffffffffffffffffffffffff)

A second example shows another detail, namely that the decoder only checks declared input parameters. Both functions below read the same address raw from calldata, but only withdraw declares it:

function withdraw(address) external {
    assembly { let to := calldataload(4) }
}

fallback() external {
    assembly { let to := calldataload(4) }
}
Dirty address in calldataDecoder v1Decoder v2
withdraw(address)gets throughrevert
fallback()gets throughgets through

The fallback declares no parameter, so no decoder runs, in any version.

Where dirty-bit bugs hide

A dirty-bit bug needs both a source that leaves dirt and a sink that uses it incorrectly. Many false-positive reports show only one of the two.

Sources:

  • Solidity, legacy pipeline only: narrowing or sign-changing casts, shifts (<<, >>), ~ and unchecked arithmetic. Which of the opcodes leave dirt depends on the type.
  • Assembly, both pipelines: calldataload, sload of a packed slot, mload, and arithmetic or shifts that push bits outside the type. Which of the opcodes leave dirt depends on the type.
  • Outsiders: crafted calldata, and return data from other contracts.
  • The compiler: cleanup bugs.

Sinks:

  • Comparisons: eq, lt, gt, slt, sgt and iszero.
  • Type-specific opcodes: some opcodes are sinks for some types, for example division and right shifts (div, sdiv, mod, smod, shr, sar) for numbers.
  • Hashing: keccak256, for example mapping keys, blacklists/whitelists and signatures.
  • Locations: slot, index and offset arithmetic, and shift amounts.
  • Packed storage writes: dirt in an sstore spills into the neighbouring field.
  • Handing data over: calldata or return data built in assembly for another contract.
  • The compiler: cleanup bugs.

Usually the source, the sink, or both are inline assembly. Without assembly, a dirty-bit bug typically needs a compiler bug. The compiler has a decade of dirty laundry of its own: Solidity’s known-bugs list records many cleanup-related bugs that can act as sources or sinks as well.

Each row shows where the source and the sink are:

Where dirty-bit bugs hide. Solidity to assembly: legacy is a bug risk, assembly reads the dirt; via-IR cleans right after a dirt-producing step. Assembly to assembly: bug risk in both pipelines, nobody washes in between. Assembly to Solidity: legacy cleans right before a dirt-sensitive step; via-IR mostly cleans, except a storage array index.

The last row has a surprising exception. Take a storage array arr of type uint256[4], inject a dirty “1” in assembly, then use it as an index:

// arr is a storage array: uint256[4] arr;
arr[1] = 42;
uint8 d;  assembly { d := 0x101 }   // "1" plus a dirty bit

require(d < 4);                     // passes in both pipelines: compares 1 < 4
uint256 v = arr[d];                 // legacy reads arr[1] = 42; via-IR reads arr[257] and panics
Legacyvia-IR
require(d < 4)sees 1, passessees 1, passes
arr[d]sees 1, returns 42sees 257, Panic(0x32)

This is an open issue in the Solidity compiler.

Case study: a bitmap that forgets

Many AMMs and order books use a TickBitmap derived from Uniswap V3. Prices are represented by signed int24 ticks, and the bitmap marks ticks with liquidity. Uniswap V3 maps each tick to a storage word and bit as follows:

function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {
    wordPos = int16(tick >> 8);    // which storage word
    bitPos = uint8(tick % 256);    // which bit in that word; legacy: can be dirty for negative ticks
}
One bit per tick, 256 ticks per storage word. Tick 100 maps to wordPos 0, which holds ticks 0 to 255, at bitPos 100. Tick 300 maps to wordPos 1, which holds ticks 256 to 511, at bitPos 44.

Take tick −100. The tick itself is clean. In Solidity, % keeps the sign, so tick % 256 is −100, and casting −100 to uint8 gives 156 (0x9c). Solidity sees 156 in both pipelines, but the legacy pipeline leaves the sign-extended word on the stack, so bitPos is dirty:

position(-100)Legacyvia-IR
bitPos as Solidity sees it156156
bitPos on the stack0xff…ff9c0x00…009c

The bitmap toggles bit bitPos in its storage word: on when a tick gets liquidity, off when its last liquidity is removed. Whether that works depends on who reads bitPos:

ReaderToggle codeLegacyvia-IR
Solidityword ^= 1 << bitPos;bit 156 flippedbit 156 flipped
assemblyword := xor(word, shl(bitPos, 1))no flip: shl returns 0bit 156 flipped

Uniswap V3 uses the Solidity version, which washes bitPos before the shift, so it is safe. Use the above assembly line instead, a common gas optimisation, and the legacy pipeline shifts left by 2256 − 100. shl(bitPos, 1) returns 0, the xor changes nothing, and the tick is never toggled. Nothing reverts here: the transaction succeeds, but because no toggle happened, the bitmap silently records the wrong liquidity state.

Wrong washing program: masking a signed value

Cleaning is type-specific, and a mask is the wrong program for signed values. Uniswap V3 packs the price and the int24 tick into one storage slot, slot0. Reading the tick −100 from that slot in assembly and shifting it to the right leaves 0xffff9c in the right three bytes and other fields further left:

The Uniswap V3 slot0 storage word holding tick −100: other fields on the left, the three tick bytes FF FF 9C, and sqrtPriceX96 (uint160) on the right. Both programs first load the tick with let tick := shr(160, sload(slot0.slot)). Wrong program: let wrongTick := and(tick, 0xffffff) gives wrongTick 16,777,116. Right program: let correctTick := signextend(2, tick) gives correctTick −100.

A mask cleans unsigned values. Signed values need signextend for clean-up, in both the legacy and the via-IR pipeline.

Care labels for your assembly

Every type has its own washing instructions:

Care labels for Solidity types in assembly: uint8, and(x, 0xff), mask the left; address, shr(96, shl(96, a)), do not tumble 96 bits; int24, signextend(2, x), never mask; bool, iszero(iszero(b)), 2 is not a boolean; bytes4, and(x, shl(224, 0xffffffff)), rinse the right

Before you start the next wash cycle:

  1. Wash at both doors. Clean narrow values when they enter and when they leave assembly, so that no sensitive sink gets a dirty value.
  2. Fuzz with dirt. Solady’s Brutalizer dirties inputs and memory in tests.
  3. Test what you ship. Legacy and via-IR clean differently, so test with your deployed compiler settings, and fork-test against the real contracts you integrate with as they might use different decoders.
  4. Audit both ends. Dirt is only a bug once it reaches a sink.

Key takeaways

  • Same code, different result: legacy and via-IR clean differently.
  • Calldata parsing changed in 0.8: decoder v1 masks dirty arguments, v2 reverts.
  • Dirty-bit bugs exist in the wild: each needs a source and a sink.

Solidity does its own laundry. Assembly is a laundromat.

Watch the talk

References

Working on assembly-heavy code and want a second pair of eyes? Request an audit.

← Back to Blog Overview