Directional Rounding Bias / Roundtrip-Swap Non-Invariance

  • Name: directional rounding bias / roundtrip-swap non-invariance
  • Category: exploit pattern / arithmetic-solvency failure / invariant drift / precision-loss amplification / AMM math failure
  • Summary: This exploit family appears when a protocol applies the wrong rounding direction in one step of a multi-operation pricing path, usually in scaling, invariant, or share-value math. The individual error may look negligible or even invisible under ordinary liquidity. The danger appears when the protocol also exposes a way to push state into an edge case — low liquidity, unusual scaling boundaries, composable LP-token routing, estimator flips, or another precision-sensitive regime — and then lets the attacker iterate a near-roundtrip loop. The analytical trap is collapsing three promotions into one vague the math only lost a little precision: a biased helper publishes a new local liquidity / invariant / share-value state, some later path reverses or re-prices that distortion into a rebound, and downstream swaps, redemptions, borrows, or reserve withdrawals still spend against that rebound as if it were money-good truth. A path that should be non-profitable (swap there, swap back) instead leaks value on every cycle because the invariant or share value drifts a tiny amount in the attacker’s favor each time.
  • What it is:
    • A protocol has a local arithmetic step whose rounding direction should depend on economic context but is implemented one way for all callers or all paths.
    • That step feeds a broader invariant, share-price, or settlement calculation.
    • Under normal states the loss per operation looks too small to matter.
    • The attacker first pushes the system into a precision-sensitive state, then repeats a swap or swap-like roundtrip that should not create net value.
    • The repeated directional bias accumulates, slowly walking the invariant, BPT/share value, or required payment away from truth until the attacker can cash out.
  • Typical preconditions:
    • The protocol performs scaling or precision conversion before an invariant-sensitive calculation.
    • At least one arithmetic step rounds in a fixed direction even though the correct direction should vary by token in versus token out, exact-in versus exact-out, or mint versus burn context.
    • The protocol exposes an edge-state setup path such as low-liquidity operation, swappable LP tokens, internal accounting deficits, or another way to make precision error economically large.
    • The attacker can iterate the biased operation many times or combine it with a setup/reversal path in one transaction.
    • The protocol lacks invariant tests like roundtrip swap should not generate profit or share value should not decrease under valid user operations.
  • Common vulnerable surfaces:
    • stable-swap or hybrid-invariant AMMs with scaling helpers and exact-out paths
    • vault or pool systems that normalize tokens to common precision before local math
    • composable LP-token designs where the pool receipt token itself can be traded during setup and unwind
    • low-liquidity regimes where one-wei directional bias gets amplified by steep invariant curvature
    • protocols whose formal or audit coverage proves aggregate solvency but not local roundtrip safety
  • Failure sequence:
    1. A local arithmetic step rounds in the wrong direction for a specific economic path.
    2. The attacker identifies the state where that bias matters most, often by draining a balance near a rounding boundary or otherwise creating low-liquidity conditions.
    3. They execute a biased swap or pricing path that slightly undercharges, overcredits, or depresses the invariant/share value.
    4. They repeat the operation or combine it with a reversal path so the local error compounds.
    5. The protocol’s invariant, LP-share value, or settlement requirement drifts away from the economically correct value.
    6. The attacker exits through redemption, reverse swap, or another path that still honors the drifted state as real.
  • Variants:
    • Exact-out undercharge — the output leg is rounded down before invariant math, so the pool asks too little input for a desired output.
    • Share-value drift — directional bias does not instantly hand out assets but steadily depresses or inflates LP share value until mint/burn paths become extractable.
    • Low-liquidity amplification — a bias that is irrelevant in thick pools becomes profitable once balances are pushed to tiny values.
    • Estimator-switch rebound — one rounding-biased path first depresses the protocol’s chosen liquidity or invariant estimate, then a later state transition flips the protocol onto a different estimate source and monetizes the rebound.
    • Composable-receipt amplification — the protocol’s own LP token becomes the setup primitive that lets the attacker force edge-state liquidity and later unwind at the corrupted price.

Three rounding-authority promotions reviewers should not collapse

1. A biased arithmetic step published new local state

  • A rounding-biased helper may have only touched an intermediate amount, or it may already have rewritten liquidity, invariant, share value, cached rate, or another state object that later paths will honor.
  • Reviewers should name that first publication step plainly: the pool now believes this exact-out amount, the pool now believes active liquidity is this small, or the vault now believes one share is worth this much.
  • The first dangerous collapse is treating the helper rounded conservatively here as the same thing as the protocol only suffered a harmless local underestimate.
  • Balancer’s November 2025 postmortem preserves the sharp version: _upscale(... mulDown) did not merely shave precision off an exact-out amount; it published an invariant-relevant state that later StableMath steps and BPT accounting still honored.

2. A later path promoted that distortion into tradeable rebound or repriced truth

  • Many exploits do not cash out on the same arithmetic step that introduced the bias.
  • The real profit appears when a later swap, join/exit, estimator switch, share-price update, or reserve recomputation partially reverses the earlier distortion and turns local conservatism into a tradeable rebound.
  • Bunni preserves the clean reminder from its own postmortem: totalLiquidityEstimate0 being pushed artificially low was not yet the whole exploit; the decisive step was the later state change that flipped the pool onto totalLiquidityEstimate1 and let the attacker sandwich the resulting liquidity rebound.
  • This second promotion is stronger than the number changed again. The protocol is now treating the rebound or re-priced state as the economically relevant answer other paths may use.

3. Downstream rights still spent against that promoted rebound

  • Even after reviewers understand the local distortion and the later reversal path, they still need to ask what rights remain live once the rebound appears.
  • Swaps, redemptions, borrows, minting, collateral recognition, or reserve withdrawals may deserve different distrust windows once the protocol has just moved through a precision-sensitive state.
  • The final dangerous collapse is the number rebounded toward normal becoming the same event as that rebound deserved immediate full economic authority.
  • In Balancer the live right was continued exact-out routing plus later settlement against cheapened BPT; in Bunni it was the second swap that spent against the liquidity rebound before the protocol could narrow authority.

Detection heuristics

  • Test swap A -> B -> A and related roundtrips across dust states, low-liquidity states, and unusual scaling factors. The attacker should not gain value absent explicit fees or rewards.
  • Review every scaling helper and ask whether rounding direction should depend on path semantics rather than being globally fixed.
  • Differential-test exact-in versus exact-out code paths under the same state to ensure neither creates attacker-favorable drift.
  • Monitor LP share value / invariant monotonicity across valid user operations. A user action should not silently make one BPT share worth less unless the user actually withdrew value.
  • Fuzz repeated micro-swaps around rounding boundaries rather than only large realistic swaps.

Defenses

  • Make rounding direction explicit at every arithmetic step and tie it to economic context, not helper-library convenience.
  • Prove or fuzz roundtrip invariants such as swap there and back <= starting balance across extreme states.
  • Add share-value monotonicity invariants so valid operations cannot quietly bleed value out of LP tokens.
  • When the protocol selects among several candidate liquidity, invariant, or pricing estimates, prove that selector flips cannot turn an earlier conservative underestimate into a later tradeable rebound; see multi-estimator monotonicity and selector-switch discipline.
  • Avoid designs that let receipt tokens or internal deficits become attacker-controlled setup tools unless those paths are covered by the same arithmetic proofs.
  • Treat precision-sensitive low-liquidity states as first-class security cases, not merely pathological tails.
  • Re-audit mature math code when new composability features or rate-provider semantics make old rounding assumptions economically meaningful.

What sound design looks like

  • Every arithmetic step carries an explicit economic meaning, and rounding direction follows that meaning rather than helper-library habit. Exact-out demand, exact-in payout, mint, burn, estimate, and settlement are distinct policy surfaces, not one generic roundDown problem.
  • Reviews stay explicit about the whole promotion ladder: this local helper published this state, this later path promoted that distortion into a rebound or repriced truth, and these downstream rights are or are not allowed to spend against that promoted state.
  • Path-level non-profitability is enforced directly. A user who pushes the system into a weird but valid state still cannot extract value by cycling swap -> reverse, join -> exit, or mint -> redeem unless the protocol intentionally pays them for that behavior.
  • The protocol assumes adversarial edge-state preparation. Low-liquidity, dust-balance, near-empty, and nested-wrapper states are part of the main security envelope, not tolerable numerical tails outside normal review.
  • Estimator switching, wrapper composability, and receipt-token routing remain monotone across the whole lifecycle. A conservative underestimate in one phase cannot rebound into a spendable over-credit in the next.
  • If the protocol cannot prove monotonicity across that whole lifecycle, it narrows authority after precision-sensitive state changes instead of letting the rebound instantly drive swaps, borrows, redemptions, or reserve spending at full size.
  • Share value and invariant drift are treated as first-class production signals. If a valid user action can steadily make a pool share or receipt token richer or poorer than it should be, the system has already lost the plot even before a dramatic one-shot drain appears.
  • The design target is simple to state and hard to fake: repeated near-roundtrips should decay value through fees or leave it unchanged, never manufacture it from arithmetic path bias.

Failure-prevention checklist

  • Mark every arithmetic step with its economic role before choosing a rounding direction: token in versus token out, exact-in versus exact-out, mint versus burn, conservative estimate versus payable amount. Do not let helper-library defaults decide value flow.
  • Name the immediate publication boundary after every biased-looking step: what exact liquidity, invariant, share-value, or payable object did the protocol just make authoritative for later paths?
  • Enforce whole-path invariants, not just local algebra. Swap there and back, mint then burn, join then exit, and similar near-roundtrips should not print value across dust states, thin-liquidity states, or unusual scaling factors.
  • Treat low-liquidity and low-balance regimes as primary security targets. If one wei can move the slope sharply, the protocol must prove that repeated cycling still cannot accumulate profit.
  • Differential-test exact-in and exact-out paths against a high-precision model so one branch cannot quietly leak value while the other appears sound.
  • Review reversal paths explicitly. If a local underestimate, undercharge, or share-value drift can later be reversed by a swap, join/exit, estimator switch, harvest, or cache refresh, test that composed path rather than only the first step in isolation.
  • Keep selector logic monotone when the system chooses among candidate invariants, liquidity estimates, or pricing sources. A conservative underestimate in one step must not become a monetizable rebound in the next.
  • Narrow authority after precision-sensitive state changes when monotonicity cannot be proven. A rebound toward normal should not automatically restore full swaps, borrows, redemptions, or reserve spending in the same step.
  • Cover composability features with the same arithmetic proofs as the base pool: LP receipts, nested BPT, wrappers, internal deficit accounting, and rate-provider inputs all widen the setup space for iterative extraction.
  • Watch share price and invariant monotonicity directly in tests and monitoring. If a valid user action can make an LP share worth less without an explicit withdrawal or fee event, the system is already leaking value.
  • Re-review every old math routine when adding new routing, new token types, new wrappers, or new exact-out support. Mature arithmetic becomes unsafe when new paths make previously negligible bias economically reachable.
  • Prefer explicit saturation, bounds, and revert conditions over silently tolerating edge-state drift. Tiny repeated errors are exactly what this exploit family monetizes.

Audit prompts

  • For each division, scaling step, and invariant helper, what economic side is supposed to benefit from rounding, and is that direction still correct for every caller path that reaches it?
  • What exact state object becomes authoritative immediately after the biased-looking arithmetic step: payable amount, active liquidity, invariant, share value, cached rate, or some other downstream truth object?
  • Can an attacker force the protocol into a dust, low-liquidity, or near-empty state where a single-wei bias becomes large enough to monetize through iteration?
  • Do exact-in and exact-out paths satisfy the same economic invariants, or does one path systematically undercharge / overcredit compared with the other?
  • What later path can reverse or reprice the local distortion: a swap back, a join/exit, an estimator flip, a cache refresh, a share-price update, or a redemption path?
  • What tests prove that immediate roundtrips such as A -> B -> A, join -> swap -> exit, or mint -> redeem do not create profit outside explicit fee schedules?
  • Can the protocol’s own LP token, receipt token, or wrapper token be used as the staging tool that creates the precision-sensitive state and then later captures the drifted value?
  • If the system switches between multiple estimates, rates, or liquidity calculators, can a user intentionally push one estimator low and then monetize a later switch back to another estimator?
  • Once the distortion or rebound exists, which rights can already spend against it at full size: swaps, redemptions, borrows, minting, liquidation, or reserve withdrawals?
  • Are invariant, share-price, and solvency checks performed with enough precision to detect cumulative drift, or only large one-shot discrepancies?
  • Have fuzz tests targeted n repeated micro-operations near rounding boundaries, rather than just one representative swap at realistic size?
  • Could fees, rebates, or virtual-liquidity overlays hide a local undercharge long enough that the exploit only becomes visible after many cycles?
  • If a path is labeled conservative, conservative for whom and at which stage? Many exploits come from local conservatism that becomes global overpayment after composition.

Lessons that should already be standard

  • Arithmetic safety is not just no overflow and close enough. If a user can cycle the state and harvest the same bias repeatedly, the protocol has a solvency bug.

  • Rounding direction is part of economic policy. Hiding it inside generic helper code is how protocols forget which side of the trade they intended to protect.

  • This step rounded conservatively, the later path reversed that distortion, and the rebound was allowed to move money are different claims. Good reviews keep all three explicit.

  • Near-roundtrip non-profitability should be a default invariant for AMMs, vaults, and share systems. If the protocol cannot prove it, an attacker will test it onchain.

  • Tiny errors become catastrophic when the attacker controls state preparation. The dangerous question is not how big is the bias per step? but can the attacker make that step repeat in the steepest part of the curve?

  • Exact-out paths deserve special suspicion. Systems often reason carefully about what they output, then accidentally undercharge what they should demand in return.

  • Composability turns mature math into new attack surface. Once the protocol’s own receipt token or nested pool becomes tradable, old precision assumptions need to be re-proved under adversarial routing.

  • A conservative estimate in isolation may be unsafe in composition. Any system that switches estimators or reuses intermediate values needs monotonicity discipline across the whole lifecycle, not just per function.

  • Rebounded toward normal is not automatically a safety story. If the rebound itself is what later swaps, borrows, or redemptions are allowed to spend against, the protocol may simply have moved the exploit into a later step.

  • Share-price monotonicity and roundtrip invariance are better security guides than prose claims that the math is economically balanced.

  • If a reviewer cannot point to tests for dust states, one-wei boundaries, and repeated reversals, the review likely covered only the pleasant part of the state space.

  • High-signal incidents:

    • invariant-deflation exploit (2025-11-03) — the clean preserved exemplar: _swapGivenOut() rounded the exact-out amount the wrong way during upscaling, and composable BPT plus low-liquidity setup let attackers iterate the bias until invariant D and BPT value drifted far enough to drain real assets.
    • liquidity-rebound sandwich drain (2025-09-02) — a strong locally conservative rounding becomes globally unsafe cousin where dust-state withdrawals pushed one liquidity estimate artificially low, then a later swap flipped the AMM onto the other estimate and let the attacker sandwich the rebound.

Internal linkages

Control surface

  • The leverage sits in helper functions that normalize amounts before invariant math, the economic meaning attached to rounding direction, and every composability feature that lets attackers revisit that math in pathological states.
  • The practical lesson is harsher than round in favor of the protocol: protocols must prove that entire roundtrips preserve value even after scaling, rate conversion, share accounting, and edge-state setup.

Sources

Last reviewed

  • 2026-08-02 UTC