A DEX spot price is just a pool’s current reserve ratio, and anyone can move it inside one transaction. If a protocol turns that number into borrowing power with no second opinion, the attacker sets their own credit limit.
This is one of the oldest bugs in DeFi, and it still shows up every month. This guide covers how it works, a real incident, how to spot it in a codebase, and the lookalikes that are actually safe.
The bug in one sentence
A lending or margin protocol values collateral from a live AMM quote, so an attacker with a flash loan can push the price up, deposit, borrow against the inflated value, unwind the price, and keep the difference.
The key distinction is between an oracle and an execution venue:
- An oracle answers: what is this asset worth across the market?
- An AMM quoter answers: if someone traded N tokens against this one pool right now, what would they get?
When a protocol uses the second answer as if it were the first, it has turned a pool anyone can trade against into an authority.
A real case: Sharwa Margin Trading (Arbitrum, May 2026, about $32.85K)
Sharwa was a margin trading and lending platform on Arbitrum. Users could deposit collateral and borrow USDC, WETH and WBTC. Unusually, it also accepted Hegic options NFTs as collateral.
To value an options NFT, Sharwa called a pluggable pricing module. The team had written two versions:
UniswapModuleWithChainlink, which read a Uniswap price and cross-checked it against a Chainlink feed with a deviation bound.UniswapModuleWithoutChainlink, which read a Uniswap V3 Quoter directly, with no cross-check, no time-weighting and no cap.
In production, the options collateral was wired to the unguarded module. Its whole valuation logic was this:
// One Uniswap V3 pool hop, fixed at construction: USDC.e --(0.05%)--> USDC.
path = abi.encodePacked(tokenInContract, poolFee, tokenOutContract);
function getInputPositionValue(uint256 amountIn) external returns (uint amountOut) {
amountOut = quoter.quoteExactInput(path, amountIn); // spot only, no clamp
}
quoteExactInput simulates a swap against the pool’s current liquidity and returns the output. It reflects the instantaneous price, and Uniswap’s docs say the Quoter isn’t meant to be called on-chain. Because the path ran through a single, shallow USDC/USDC.e pool, whoever traded in that pool right before depositing controlled the collateral’s value.
Why a small trade moved the price so much
In a constant-product pool with reserves x and y:
invariant : x · y = k
spot price : P = y / x
price impact : ΔP / P ≈ Δx / x
The price shift scales with the trade size relative to the pool’s depth. Concentrated liquidity in V3 makes this worse when the liquidity around the current price is thin.
The attacker flash-borrowed 22,000 USDC and swapped it into the pool for USDC.e. USDC.e became scarce in that pool and USDC became cheap. When Sharwa then asked what USDC.e was worth in USDC, the Quoter reported a hugely inflated number.
In a pool with $50M of liquidity, a $22K trade barely moves the price. In a pool with tens of thousands of dollars, it breaks the peg. Depth decides how cheap the lie is.
The attack, step by step (one transaction)
- Stage. The attacker sends the options NFT to their attack contract. The NFT receive callback kicks off the rest.
- Borrow. Flash-borrow 22,000 USDC from Balancer at zero fee.
- Pump. Swap it through the thin pool, pushing USDC.e far above its 1:1 peg.
- Deposit. Open a margin account and deposit the NFT. Sharwa prices it through the unguarded module and records an inflated credit limit.
- Borrow out. Borrow the maximum USDC, WETH and WBTC. The attacker routes some borrowed USDC back into the pool to keep the price up while borrowing the rest. About $54.85K leaves the protocol.
- Unwind and repay. Sell everything back to USDC through deep pools, repay the 22,000 USDC, and keep about $32.85K. Sharwa is left holding a nearly worthless NFT and bad debt.
Why it worked: three facts
- The spot price is controllable. A reserve ratio has no memory and no idea of fair value. Flash loans let anyone rent enough capital to move a shallow pool for one transaction.
- The protocol trusts the quote blindly. There’s no TWAP, no Chainlink cross-check, no deviation bound and no borrow cap.
- Settlement is atomic. The lie is created, recorded, spent and unwound in one transaction, so no arbitrageur gets a chance to fix the price in between.
Every working defense breaks at least one of these.
The five ingredients (all must hold)
Before you report this bug, check that all five are present:
- Spot quote valuation. Collateral or borrow capacity comes from an instantaneous AMM read, such as
quoteExactInput,quoteExactOutput,slot0,getAmountsOutorgetReserves. - Manipulable path. The pool is shallow compared with the capital available through flash loans.
- Consumed in the attacker’s transaction. The inflated value sizes a borrow, mint or payout before the price can recover.
- Accessible collateral. The attacker can get and deposit the collateral with no whitelist in the way.
- No guardrail. There’s no cross-check against an independent feed, no deviation clamp and no absolute cap.
How to hunt for it
- Trace every pricing call that isn’t just for display.
bash grep -rnE "quoteExactInput|quoteExactOutput|getAmountsOut|slot0|getReserves" src/For each hit, follow the return value. Does it only feed a UI preview, or does it reach borrow power, collateral value, liquidation thresholds or minting? - Check what is actually wired up. A safe oracle module in the repo means nothing if deployment wires the unsafe one. Read the deployment scripts and the on-chain storage, not just the source. This is exactly how Sharwa was lost.
- Compare pool depth with flash-loan capital. Work out how much capital it takes to move the quote by 20%, 50% or 200%, and compare that with what Aave, Balancer and Uniswap can lend. If flash liquidity is far larger, treat the pool as trivially manipulable.
- Check the timing. Can
deposit()andborrow()happen in the same transaction? Is collateral re-priced at borrow time, or is a deposit-time snapshot reused? - Look for circuit breakers and caps.
bash grep -rnE "Chainlink|Aggregator|observe|TWAP|deviation|cap|bound" src/Is there a deviation clamp against an independent feed? Are there per-account and per-deposit caps?
Lookalikes that are safe, and why
- A real 30-minute Uniswap V3 TWAP.
observe()averages the price over many blocks. A one-block spike barely moves the average, and keeping the pool distorted for many blocks bleeds money to arbitrageurs. Check that it really callsobserve()over a meaningful window and doesn’t just readslot0while calling itself a TWAP. - A DEX price clamped to Chainlink. If the contract reverts whenever the DEX price strays more than a few percent from Chainlink, the lie never reaches the borrow logic. This only holds if the clamp is wired in for every collateral type and the Chainlink read checks staleness.
- Snapshot pricing. If borrows are capped against a price recorded in an earlier block or epoch, an in-transaction swap can’t rewrite history.
- Display-only quotes. A quote used only for UI previews or slippage estimates never moves funds.
- Deep pools with tight caps. This is an economic argument, not a structural one. If moving the price costs more than the cap lets anyone borrow, the attack loses money. Do the math rather than assume it.
Fixes that work
- Use a cumulative TWAP. Read
observe()over a real window. Avoid very short windows, single illiquid pools, and wrappers that claim to average but read the current price. - Cross-check with an independent feed. Revert if the DEX price is more than a small percentage away from Chainlink. Check
updatedAtfor staleness, wire the check on every collateral path, and keep the bound tighter than an attack’s profit margin. - Cap borrowing absolutely. Set per-account and per-block limits in a stable unit, independent of the oracle. Even a fully broken oracle then has a bounded blast radius.
- Break atomicity. Require a delay between deposit and borrow, and re-price at borrow time.
- Only accept deep collateral, at conservative loan-to-value. This raises the cost of attack, but it isn’t a guarantee. Measure it.
The same bug in other clothes
The pattern isn’t limited to lending. It appears wherever a live price sizes an entitlement:
- LpdFi (BNB Chain). A staking protocol priced deposits with its own
price()function, which was a raw PancakeSwap reserve ratio. A flash-funded dump crashed the price, a small deposit was credited as an enormous order, and the attacker claimed most of the protocol’s reward inventory. - ElevateFi (Polygon, about $16K). Fixed-USD staking packages converted USD to tokens at the spot price on entry, then paid rewards against the USD face value. The attacker pumped the token, bought packages for very few tokens, and claimed rewards an epoch later. Waiting an epoch didn’t help, because the entitlement was never re-priced.
- Whalebit (Polygon). The contract said it used an “average price”. The code read the pool’s current
sqrtPriceX96. Deposit high, push the price down, withdraw low, repeat. Labels lie. Code doesn’t.
Test yourself
- A protocol prices collateral with a 30-minute TWAP. Vulnerable to a flash-loan oracle attack? No, ingredient 1 fails. But confirm it really calls
observe()over that window and isn’t readingslot0under a TWAP name. - Spot quote, but a mandatory 24-hour wait between deposit and borrow. Vulnerable? Not to flash loans, as long as collateral is re-priced at borrow time. If the deposit-time value is stored and reused, it’s still exploitable, as ElevateFi showed.
- Spot quote with a 2% Chainlink deviation clamp. Valid finding? No, the clamp stops it. Still confirm the clamp is wired for every collateral type and the feed checks staleness.
- Your fork test works mechanically, but net profit is negative after fees. High severity? No. A working mechanism with negative economics is a near miss. Try other parameters first. If it stays unprofitable, report it as Low or Informational.
Recap
- An AMM spot price is an instantaneous balance ratio. Anyone with a flash loan can move it.
- The exploit needs a controllable quote, blind trust and atomic settlement. Each fix breaks one.
- Sharwa had the safe module in its codebase and wired the unsafe one. Audit what’s deployed, not just what’s written.
- The same shape appears in staking, packaged yields and anything else that sizes an entitlement from a live price.
- The rule: a number the protocol trusts must never be a number an attacker can move inside the same transaction.