We manage your security to weather the AI storm →

← Resource Hub

AMM Vulnerabilities: Constant Product, StableSwap and CLMM

By Daniel GelfandPublished 7 min read

Part of our guide to smart contract vulnerabilities

AMM Vulnerabilities: Constant Product, StableSwap and CLMM

Quick answer. The AMM vulnerabilities that recur across pool designs are invariant math and rounding errors, liquidity and LP share accounting bugs, manipulable prices and missing slippage bounds, fee misallocation, and unauthenticated callbacks or reentrancy. Which bites first depends on the pool design.

Watch: AMM Vulnerabilities: Constant Product, StableSwap and CLMM 1:51
Video transcript

Anyone can call an AMM's pricing math, with any amount, in any order. A tiny repeating error can be farmed until the pool is empty.

Five bug classes recur: rounding errors, LP share accounting, missing slippage bounds, fee misallocation and unsafe callbacks. No public dataset ranks them.

Design decides what bites first. Constant product: settlement and share math. StableSwap: scaling and solver convergence. Concentrated liquidity: tick crossing and fee growth.

Rounding direction must match each operation. Reporting citing Balancer's preliminary disclosure tied its November 2025 incident to rounding in exact-output swaps.

Quotes can be right and settlement wrong. In Guardian's Baseline AMM review, a six decimal conversion rounded down, so dust buys paid far less than quoted. That Critical finding was resolved.

Guardian's Poolshark reviews show accounting failures. Tick liquidity counted twice. Fees were valued at the range boundary. A router callback never checked its caller. All were resolved.

Caller authentication does not stop reentrancy, so contracts need both. In Uniswap version 4, clearing every delta proves settlement, not that a hook allocated fees correctly.

Test each operation with named exceptions, since k falls on every withdrawal. Reconcile assets, block unfunded claims, check fee eligibility and roundtrips, then push dust trades.

Read the full guide for every property. Guardian's AMM audit tests swap math, ticks, LP shares, fees and callbacks with two independent teams. Start at guardian.security.

Why Pool Code Fails

An AMM lets anyone call its pricing math with any amount, in any order. A tiny error that repeats can be farmed until the pool is empty.

Our DeFi security guide compares risks across protocol types. This guide stays inside the pool: what breaks in each AMM design, and the properties that catch it.

No public dataset ranks these bug classes by frequency. So they are grouped here by design and by operation, not ranked.

AMM Designs and Their Invariants

Each design protects a different quantity. A bug is any path that lets that quantity move without matching payment.

Constant product pools trade on x × y = k, worked by hand in our constant product AMM guide. Uniswap v2 enforces a fee-adjusted inequality after each swap, not an unchanged product.[1, 2]

The v2 pair measures its token balances after transfers and callbacks, then checks settlement. Trade pricing lives separately, in the periphery.

StableSwap behaves close to constant sum near balance and like constant product away from it. The amplification parameter A sets how concentrated that middle is.[3, 4]

Curve's StableSwap NG math solves the invariant D iteratively on normalized balances. It caps the iterations and reverts when the solver does not converge.

Concentrated liquidity pools give each position its own range on a translated curve. Outside that range, a position adds no active liquidity and earns no fees.[5]

Ticks record gross liquidity referencing them and net liquidity added or removed on crossing. Our Uniswap v3 concentrated liquidity explainer covers how swaps cross them.[6]

DesignWhat must holdReview first
Constant productFee-adjusted reserve product never falls on a swap; LP claims stay proportionalBalance-based settlement, LP mint and burn math, spot price reads
StableSwapInvariant D over normalized balances, shaped by ADecimal and rate scaling, solver convergence, rounding across chained steps
CLMMActive liquidity matches in-range positions; fees follow active liquidityTick crossing, missing or duplicated liquidity, tick rounding, fee growth
All designsEvery swap settles; only genuine pools trigger callbacksCallback authentication, slippage bounds, unsettled deltas, shared accounting

Math and Rounding Bugs

Rounding direction is chosen per operation, not per codebase. Uniswap v3 rounds its next-price calculations in opposite directions, so exact-input swaps never send too much output and exact-output swaps always move the price far enough.[7]

Balancer v2's public scaling helper rounds every upscaled amount down. Downscaling has separate helpers for each direction.[8]

Cryptonews, citing Balancer's preliminary disclosure, tied the November 3, 2025 incident to rounding with non-integer scaling factors in exact-output swaps on Composable Stable Pools.[9, 10]

It reported Balancer v3 unaffected by that incident. Our Balancer exploit post-mortem traces how the small errors compounded.

A correct quote can still be undone at settlement. In Guardian's Baseline AMM Round 2 review, quotes rounded against the trader, but converting to a 6-decimal reserve token rounded down.[11]

A dust buy therefore paid far less than its quote, and that price fed the pool's later pricing (C-02, Critical, resolved).

Cetus merged a fix to the checked_shlw boundary comparison in its integer-mate library on May 22, 2025.[12, 13]

Crypto.news, citing Cetus, traces that day's incident to the faulty left-shift overflow check; SecurityWeek reports the same date and an open-source library flaw. Our Cetus hack breakdown follows the deposit that exploited it.[14, 15]

Price Manipulation and Slippage

A pool's current reserves are a price anyone can move within one transaction. Uniswap warns against reading them and accepting that quote without an external price reference.[1]

That applies to your router and to every protocol that reads your pool. Our price oracle manipulation guide covers spot reads and TWAPs.

Execution bounds are the trader's defense. Exact-input swaps need a minimum output, and exact-output swaps need a maximum input.

A router that hardcodes or skips either bound gives the difference to whoever trades first. Bounds cap sandwich losses; they do not remove every ordering opportunity.

Protective limits need review. In Poolshark Cover, a TWAP rate limit fell off the tick grid when elapsed blocks were not whole auctions, so swaps could take more than the auction held (EP-4, Critical, resolved).[16]

Fee and Liquidity Accounting

Fees belong only to liquidity that was active when they accrued. In Uniswap v3, a position's fee growth is derived from global growth and the growth recorded outside its two ticks.[6]

Any error in that bookkeeping moves yield between LPs. A mint followed by a burn is one way an attacker collects it.

In Guardian's Poolshark Limit review, accrued fees were valued at a position's range boundary instead of the current price (POS-1, High, resolved).[17]

An attacker could mint while fees were undervalued, then burn for their full value, taking yield from other LPs.

In the same review, liquidity stashed on a tick was sometimes not zeroed, so it counted twice. Swaps drew on positions far from the price, and LPs could not burn (TK-1, Critical, resolved).

Protocol fee switches, dynamic fees and reward streams each add another ledger. Ask the same question of each: who was eligible when this value accrued?

Reentrancy and Callback Risks

Callbacks hand control to the caller mid-swap. Uniswap v3's swap callback interface requires implementers to verify that the caller is a pool deployed by the canonical factory.[18]

That check authenticates the caller. It does not stop reentrancy, so a contract needs both.

In Poolshark Limit, the router's swap callback never checked that its caller was a real Poolshark pool. Anyone could call it and pull tokens from users who had approved the router (PROU-1, Critical, resolved).[17]

Separate locks fail when contracts share accounting. Balancer's February 2023 advisory described pool supply and Vault balances disagreeing mid-operation, skewing rates, fees and later prices.[19]

Protocols that price LP tokens from that state face read-only reentrancy, an integrator problem with its own checks.

In Baseline's AMM, a native-token refund ran before swap reserves reached the vault (H-09, High, resolved).[11]

A buyer could re-enter, stake while harvestable yield read as zero, and share yield owed to existing stakers.

Uniswap v4 moves this risk into hooks. Its PoolManager calls hooks, tracks caller and hook deltas separately, and rejects unsettled deltas when the unlock completes.[20]

Clearing every delta proves settlement at that boundary. It does not prove a custom hook allocated fees, rewards or permissions as intended.

How to Test AMM Invariants

Write each property for one operation and state its exceptions. A blanket rule such as k never decreases is false for every withdrawal.

Share value can also fall legitimately, through external losses or rate changes. Name donations, rebases, fees and hooks as explicit exceptions.

Foundry runs stateful invariant campaigns with handlers, multiple actors and ghost accounting. Our Foundry invariant testing guide shows the setup.[21]

Its docs warn that checking less often can miss a violation restored before the next check. Callback-time state needs its own assertions.

Guardian's AMM audit fuzzes these properties as executable invariants, testing rounding on low-decimal tokens, dust trades and near-empty pools.

  • Reconcile assets: ghost-tracked deposits, swaps and withdrawals match the pool's token balances after every call.
  • No unfunded claims: no mint, in any range, creates liquidity or shares worth more than the tokens paid in.
  • Swap invariant: the fee-adjusted invariant never falls across exact-input and exact-output swaps, in both directions.
  • Active liquidity: after every tick crossing, it equals the sum of in-range positions under your boundary convention.
  • Fee eligibility: fees reach only positions active when they accrued, and a mint then burn captures nothing extra.
  • Roundtrip: swapping out and back never returns more than went in, given fixed rates, no subsidy and no intervening trades.
  • Callbacks: calls from unauthenticated callers revert, and re-entering handlers never read unfinished accounting.
  • Edge states: dust, near-empty pools, 6 and 8 decimal tokens, positions bounded exactly at the current price, and time jumps.
  • Live paths: check revert counts per handler, so the campaign exercises successful swaps rather than piles of failed calls.

Test Your Pool Math Before It Holds Liquidity

Guardian's AMM audit tests swap math, ticks, LP shares, fees and callbacks with two independent teams and an invariant suite that stays with your code.

Frequently Asked Questions

Is impermanent loss an AMM vulnerability?

No. It is the value LPs give up versus simply holding when the pool price moves, and it follows from the curve itself. It becomes a security issue when a bug takes value beyond that design, such as mispriced fee claims or double-counted liquidity.

Does a forked AMM need its own review?

Yes, wherever it changes tokens, decimals, fees, parameters or integrations. Check every upstream advisory against the fork, and put imported math libraries in scope: the Cetus flaw sat in a dependency, not the exchange logic.[14, 15]

Do Uniswap v4 hooks need different checks?

They add their own: hook permissions, callbacks, delta settlement and hook-owned liquidity. Guardian scopes them in a separate Uniswap v4 Hook Audit, while the pool math classes above still apply wherever a hook changes swaps, fees or liquidity.

Sources

  1. Uniswap: Uniswap v2 Pricing
  2. Uniswap: UniswapV2Pair.sol
  3. Curve Finance: How Curve Compares to Other AMMs
  4. Curve Finance: CurveStableSwapNGMath.vy
  5. Uniswap: Uniswap v3 Core
  6. Uniswap: Tick.sol
  7. Uniswap: SqrtPriceMath.sol
  8. Balancer: ScalingHelpers.sol
  9. Balancer: BIP-892: Distribution of Rescued Funds from Balancer v2 November 3rd 2025 Attacks
  10. Cryptonews: How a Tiny Rounding Error Ignited Balancer’s $128M Multi-Chain DeFi Exploit
  11. Guardian: Baseline Markets AMM Audit Report, Round 2
  12. Cetus Protocol: Fix checked_shlw, pull request 7
  13. Cetus Protocol: Fix checked_shlw
  14. Crypto.news: Cetus DEX releases post-mortem, outlines recovery plan following $223M exploit
  15. SecurityWeek: $223 Million Stolen in Cetus Protocol Hack
  16. Guardian: Poolshark Cover Audit Report
  17. Guardian: Poolshark Limit Audit Report
  18. Uniswap: IUniswapV3SwapCallback.sol
  19. Balancer: Reentrancy Vulnerability Scope Expanded
  20. Uniswap: PoolManager.sol
  21. Foundry: Invariant Testing