Crypto Training

Rounding in DeFi: When Dust Becomes an Oracle

Every integer division discards a remainder, and the protocol decides who receives it. This post covers the direction each conversion should round, what ERC-4626 and OpenZeppelin specify, the decimals traps, and the incidents where one unit of rounding was worth millions.

Crypto Training•2026-02-11•16 min read

Rounding bias diagram

Solidity has no fractions, so every division in a protocol discards a remainder. The compiler has checked for overflow since 0.8, which leaves the remainder as the arithmetic question that still needs a human decision, because someone receives that dust and the code chooses who.

We prefer the term rounding policy over rounding error for that reason. An error is something you tolerate, while a policy can be written down, reviewed and tested.

This post covers the policy at a single site, meaning which way each conversion should round, what the standards say, and how one unit of rounding turned into millions in several incidents. The cases where every site is defensible and the sequence still leaks are in our post on compositional rounding attacks.

How one unit becomes profitable#

A favourable rounding of one unit is worth one unit, which is usually far less than the gas needed to collect it. Two things change that. The attacker may be able to repeat the operation as often as they like, in which case a consistent bias adds up linearly. Or the attacker may be able to change what one unit is worth, in which case a single rounding is enough.

The second route is behind most of the losses we checked. Share prices, exchange rates and liquidity indexes are ratios, and a ratio with a tiny denominator can be pushed very high by a donation. Radiant's USDC market on Arbitrum is the clearest case. In January 2024 an attacker emptied the newly listed market to a single share and inflated its index to about 2.7 × 10^38, after which the half-up rounding in the Aave-style rayDiv was worth roughly half an index of real USDC per operation. Our replay shows the loop depositing 271,800,000,001 units and withdrawing 407,700,000,000 on each cycle.

The caller also sees the result before committing. A contract can simulate the conversion, keep the call only when the remainder falls its way, and stop when the next iteration no longer pays. That feedback is what the title refers to: the dust tells the attacker when to continue.

Where rounding hides#

Three kinds of code carry most of the rounding in a DeFi codebase.

  1. Share accounting, meaning the conversions between shares and assets in vaults and lending markets.
  2. Pricing, including spot prices, TWAPs, virtual prices and Q64.96 square-root prices.
  3. Fee and reward accumulators, which are updated by a multiplication followed by a division on every interaction.

Inside those, the operations to search for are the plain / operator (which truncates toward zero), every mulDiv variant, and conversions between token decimals.

Algebra is not integer arithmetic#

Two expressions that are equal over the real numbers can differ over integers, because the order of operations decides when the remainder is thrown away. A fee of 30 basis points shows the size of the effect.

SOLIDITY
uint256 feeA = amount * 30 / 10_000; // multiply first
uint256 feeB = amount / 10_000 * 30; // divide first

For amount = 19_999 the first line gives 59 and the second gives 30, since the early division has already reduced 19,999 to 1. For amount = 1_999 the results are 5 and 0. A refactor that reorders a formula for readability, or to avoid an intermediate overflow, therefore changes who receives the dust and can halve a fee. This is the main reason mature codebases keep arithmetic in a small set of tested primitives.

A direction for every conversion#

The working rule is to round against the party who initiates the operation and chooses its size. ERC-4626 states it for vaults in its security considerations, where it calls favouring the vault over its users the most secure choice, and it fixes the direction of each preview function accordingly. The same reasoning extends to debt.

OperationQuantity computedDirectionBasis
deposit(assets)shares minteddownERC-4626 previewDeposit: no more than the exact amount
mint(shares)assets requiredupERC-4626 previewMint: no fewer than the exact amount
withdraw(assets)shares burnedupERC-4626 previewWithdraw: no fewer than the exact amount
redeem(shares)assets paid outdownERC-4626 previewRedeem: no more than the exact amount
borrowdebt shares recordedupthe borrower owes at least what they took
repaydebt shares cleareddowna payment never clears more debt than it covers
fee charged to a callerfee amountupUniswap v3 uses mulDivRoundingUp for the swap fee
liquidationcollateral seizeddownthe liquidator is the initiator

Each row has a matching failure in the record. Compound v2's redeemUnderlying rounds the shares burned down, which is the opposite of the withdraw row, and that is what let the attackers of Hundred Finance and Sonne recover almost their whole donation while burning one of their two shares. A Balancer V1 pool computed the assets required for a chosen amount of pool tokens rounded down, which allowed minting for one satoshi of WBTC. A review of Liquity Bold found batch debt shares rounded down, so a debt increase smaller than one share's worth was recorded as zero shares and pushed onto existing borrowers.

A team can deviate from the table for a documented reason. What the code cannot afford is two paths for the same conversion that round differently, since entering through one and leaving through the other then pays the difference.

The decimals trap#

Tokens with 6 or 8 decimals inside 18-decimal math add conversions that are easy to overlook, since they often appear as a bare constant.

ConversionCommon bugEffect
amount18 = amount6 * 1e12done after a divisionprecision is lost before scaling
amount6 = amount18 / 1e12floors when collecting a paymentthe protocol under-collects
mixed-decimal formuladivides before multiplying on one path onlydeposit and withdrawal disagree

Two small cases make the first rows concrete. Scaling 1.999999 USDC as (amount6 / 1e6) * 1e18 yields 1e18, where amount6 * 1e12 yields 1.999999e18, so half the deposit is ignored. Collecting a debt of 1,900,000,000,000 internal units as debt18 / 1e12 takes 1 unit of USDC where 2 are owed, which is why amounts the protocol collects need a ceiling division.

Low decimals also make one unit expensive. The Balancer V1 case above depended on a WBTC reserve that swaps had compressed to about 7 satoshis, at which point an 18-decimal formula rounded the required input to a single satoshi. A useful search in any audit is every occurrence of 1e12, 10 ** and decimals().

Inflate the unit, then round#

Consider a vault that rounds shares up on deposit and assets down on redemption, with a share price of 2.5 (2,500,000 assets backing 1,000,000 shares).

  • Deposit 1 wei. The exact result is 0.4 shares, and rounding up mints 1 share.
  • Redeem that share. The exact claim is 1 × 2,500,001 / 1,000,001 ≈ 2.4999985, which floors to 2 wei.

The round trip pays 2 wei for 1, a gain no one would spend gas on. The gain per trip is roughly the share price, though, so the attack consists of making the share price enormous first.

Raft lost about $3.2M this way in November 2023. Its collateral token minted with divUp against a stored index, and the index was recomputed on liquidation as the contract's collateral balance divided by the raw supply. The attacker donated about 6,000 cbETH, liquidated their own dust position so that the raw supply fell to 89 units, and thereby raised the index roughly 3,000 times. From then on each 1 wei deposit rounded up to one raw unit that the protocol valued at 67.45 cbETH, and about 150 such deposits created the collateral for a 6.6M R borrow.

The Compound v2 forks failed in the mirror direction. With two shares outstanding and a large donation in the market, redeeming almost the whole donation computes fewer than two shares and truncates to one, so the attacker gets the donation back and still holds a share that the protocol values at half of it, which is enough to cover the borrow taken against the inflated collateral. Sonne's own post-mortem calls it a known donation attack on Compound v2 forks and describes the usual defence, which is to list a market with a zero collateral factor, seed it, burn the seed shares and only then raise the factor. The attacker executed the queued listing transactions themselves before that seeding had happened.

ERC-4626 and virtual shares at the vault boundary#

A vault that follows the ERC-4626 directions still has the empty-vault problem, because rounding down on deposit is what lets a donation push a victim's deposit to zero shares. OpenZeppelin's implementation has addressed this since v4.9 with virtual shares and assets. In v5.7.0 the conversion is:

SOLIDITY
function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
    return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
}

_decimalsOffset() returns 0 unless the vault overrides it, so by default the formula adds one virtual share and one virtual asset. The table below works through one scenario under four configurations: the attacker deposits 1 wei of USDC, donates 10,000 USDC directly, and a victim then deposits 5,000 USDC.

ConfigurationVictim's sharesVictim's resultAttacker's result
No virtual shares0loses 5,000gains 5,000
OpenZeppelin, offset 00loses 5,000loses 2,500
OpenZeppelin, offset 3999loses about 3.33loses about 4,998
OpenZeppelin, offset 6999,999loses about 0.003loses about 5,000

The default offset makes the attack unprofitable, which is what the OpenZeppelin documentation claims, and the victim can still be griefed out of a deposit by someone willing to lose money. A larger offset removes the griefing as well. The contract's comments name the costs: the virtual shares capture a very small part of the vault's yield, and after a loss the first users to exit lose less than the last. Uniswap v2 solved the same problem differently, by minting the first 1,000 units of liquidity to the zero address.

Rounding around external calls#

Settlement is a second source of asymmetric conversions. If a contract computes an expected amount, calls a token or a DEX, and then credits the computed figure, any difference between computed and received is a gap the caller controls. Crediting the measured balance change closes it, and our ERC-20 integration checklist covers the token side.

A mulDiv with full precision and an explicit direction#

The product x * y can exceed 256 bits when the final quotient fits, and teams that work around the overflow by reordering the formula run into the problem from the fee example above. A full-precision mulDiv computes the 512-bit product and divides it with a stated direction.

The libraries differ here, so the name alone is not enough to go on. OpenZeppelin's Math.mulDiv, Uniswap's FullMath.mulDiv and PRBMath's mulDiv are full precision, and all three credit Remco Bloemen's original construction. Solady offers both, with the full-precision versions named fullMulDiv and fullMulDivUp. Solmate's mulDivDown and mulDivUp revert when x * y overflows, which is safe and can turn a large position into a failed transaction.

Making the policy explicit in code#

The helpers below wrap OpenZeppelin's Math.mulDiv so that the direction lives in one place and the call sites name the business operation.

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

/// Every share conversion in the protocol goes through this library.
library SharePolicy {
    /// Shares minted for a deposit. Rounds down, the depositor absorbs the dust.
    function sharesForDeposit(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
        return Math.mulDiv(assets, totalShares, totalAssets, Math.Rounding.Floor);
    }

    /// Shares burned to withdraw an exact asset amount. Rounds up.
    function sharesForWithdraw(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
        return Math.mulDiv(assets, totalShares, totalAssets, Math.Rounding.Ceil);
    }

    /// Assets paid out for redeemed shares. Rounds down.
    function assetsForRedeem(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
        return Math.mulDiv(shares, totalAssets, totalShares, Math.Rounding.Floor);
    }

    /// Assets required to mint an exact share amount. Rounds up.
    function assetsForMint(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
        return Math.mulDiv(shares, totalAssets, totalShares, Math.Rounding.Ceil);
    }
}

The sketch leaves out the empty-vault case, which needs virtual shares or a seeded minimum as discussed above. Aave took a similar step in its own codebase: WadRayMath rounded half up everywhere through v3.4, and v3.5 added rayMulFloor, rayMulCeil, rayDivFloor and rayDivCeil next to the half-up defaults.

Why the sign of the error matters more than its size#

The error of a single operation is usually bounded by one unit. If its sign is random from the attacker's point of view, repeated operations cancel out. If the sign consistently favours the caller, the total grows linearly with the number of operations.

CODE
profit
  ^
  |          *
  |        *
  |      *
  |    *
  |  *
  +------------------> iterations

More precision lowers the slope of that line and leaves its direction unchanged. The durable fixes are to flip the sign, so that each iteration costs the caller, and to keep the unit small with a floor on supply and reserves.

Properties that catch rounding bugs in tests#

Tests with hand-picked amounts rarely find these bugs, because the failing inputs are dust amounts and unusual share prices. Four properties cover most of the ground.

  1. No free value: a deposit followed by a full redemption never returns more than was deposited.
  2. Monotonicity: depositing more assets never yields fewer shares.
  3. Bounded error: each conversion differs from the exact rational result by less than one unit, in the documented direction.
  4. Path consistency: deposit and mint, and withdraw and redeem, agree to within one unit for equivalent inputs.

A Foundry fuzz test for the first property against any ERC-4626 vault looks like this.

SOLIDITY
import {Test} from "forge-std/Test.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

abstract contract RoundTripTest is Test {
    IERC4626 internal vault;
    IERC20 internal asset;

    function testFuzz_roundTripNeverProfits(uint256 assets, uint256 donation) public {
        assets = bound(assets, 1, 1e30);
        donation = bound(donation, 0, 1e30);

        // Put the vault at an arbitrary share price before the round trip.
        deal(address(asset), address(vault), asset.balanceOf(address(vault)) + donation);

        deal(address(asset), address(this), assets);
        asset.approve(address(vault), assets);
        uint256 shares = vault.deposit(assets, address(this));
        uint256 returned = vault.redeem(shares, address(this), address(this));

        assertLe(returned, assets, "round trip returned more than was deposited");
    }
}

The donation line is the important one, since a suite that only tests at a share price of 1.0 never sees the regime where one unit is valuable. a16z maintains a property test suite for ERC-4626 that covers the rounding requirements of the standard and can be pointed at any vault.

Rounding in Uniswap-style fixed point#

Uniswap v3 stores prices as Q64.96 square roots and fees as per-liquidity accumulators (feeGrowthGlobal0X128 and its per-tick and per-position snapshots), so nearly every line of a swap rounds. The codebase handles this by putting the direction in the function names and comments. SqrtPriceMath has getNextSqrtPriceFromAmount0RoundingUp and getNextSqrtPriceFromAmount1RoundingDown, the amount helpers take a roundUp flag that SwapMath sets to true for amounts owed to the pool and false for amounts paid out, and the next-price function carries the comment "round to make sure that we don't pass the target price".

KyberSwap Elastic lost exactly that property in November 2023, when a rounded price passed the tick it was supposed to stop at (the details are in the compositional post). Anyone writing swap logic, or a v4 hook that keeps its own accumulators, takes on the same obligation for every multiplication and division, at a call frequency the adversary controls.

Accumulators add one more requirement. A global accumulator, a per-position snapshot and a claim function each round, and the sum of all claims must never exceed what the global figure accrued, so claims round down.

Rounding edges are also copied quickly. KyberSwap's post-mortem attributes about $6.6M of that incident to front-running bots, and Balancer's reports that a whitehat front-ran the attacker on mainnet within the first minute of the November 2025 exploit.

The rounding pass in an audit#

The pass starts with the places where a rounded operation can be repeated or sized by the caller, which are deposits and mints, withdrawals and redemptions, reward claims, swaps and liquidations. For each of them, these are the checks we would run.

  • Compare the direction with the table above, and compare the two functions of each pair (deposit and mint, withdraw and redeem) with each other.
  • Find out whether any call sequence can shrink the denominator of a share price or index to a few units, and whether a donation can raise the numerator.
  • Trace every decimal conversion and check that scaling happens before division.
  • Look at formulas that were reordered, especially near comments about overflow.
  • Check that settlement credits what arrived, where an external call sits between two computations.

The same checks apply wherever units change, which means the vault boundary (convertToShares and convertToAssets), the oracle boundary where a feed's decimals meet internal units, the token boundary for 6 and 8 decimal assets, and the settlement boundary around external calls. When one site is wrong, search for copies of it, since rounding code tends to be pasted.

A talk on rounding errors as an exploit primitive#

A short talk that treats rounding as something an adversary repeats and composes, with worked exploit examples.

Sources#