AMM Vulnerabilities & Exploits: How DeFi Hacks Happen

AMM Vulnerabilities & Exploits: How DeFi Hacks Happen Oct, 8 2024

AMM Vulnerability Risk Calculator

Risk Assessment Results

Vulnerability Breakdown

Quick Take

  • Automated Market Makers (AMMs) are prone to flash‑loan, sandwich, and MEV attacks.
  • Smart‑contract bugs can let attackers drain liquidity pools in seconds.
  • Audits, time‑weighted pricing, and anti‑sandwich mechanisms reduce risk.
  • Real‑world exploits on Uniswap, SushiSwap, and Curve illustrate common failure points.
  • Follow the checklist at the end to spot red flags before deployment.

What is an AMM?

When you hear Automated Market Maker is a protocol that provides liquidity for token swaps without a traditional order book, think of a vending machine for crypto. Users deposit assets into a pool, the pool’s algorithm (usually a constant‑product formula) sets prices, and anyone can trade against that pool instantly. Because there’s no central market maker, the system is open, permissionless, and runs entirely on smart contracts.

Popular AMMs include Uniswap the first mainstream Ethereum AMM, SushiSwap a fork of Uniswap that added token incentives, and Curve Finance an AMM optimized for stable‑coin swaps. All share the same core risk surface: code that moves money automatically.

Common Vulnerability Categories

Below are the biggest buckets where attackers find openings. Each one can be traced back to a specific flaw in the contract logic or the economic design.

  • Flash‑Loan Attacks - Borrow large amounts of capital without collateral, manipulate the pool’s price, and return the loan in the same transaction.
  • Sandwich Attacks - Front‑run a victim’s trade, execute a back‑run after the price moves, and pocket the spread.
  • MEV (Maximal Extractable Value) Manipulation - Reorder, insert, or suppress transactions to extract profit, often using bots.
  • Liquidity‑Pool Draining - Exploit a rounding error, missing access control, or a faulty fee calculation to withdraw more than contributed.
  • Impermanent‑Loss Exploitation - Trigger sudden price divergences that make the pool’s token balance unfavorable to honest LPs.
  • Smart‑Contract Bugs - Integer overflow/underflow, re‑entrancy, uninitialized storage slots, or bad random number generation.
  • Arbitrage Exploits - Use price differentials across AMMs to profit, but when combined with other bugs it can become a drain.
Notable Real‑World Exploits

Notable Real‑World Exploits

Seeing the theory in action helps you recognize similar patterns in your own code.

  1. Uniswap V2 Flash‑Loan Drain (2022) - An attacker borrowed $10M via a flash loan, swapped a tiny amount of a newly‑listed token to artificially inflate its price, then used that inflated price to extract ETH from the pool. The underlying bug was an unchecked price oracle that relied on the pool’s own balance.
  2. SushiSwap Governance Attack (2023) - By exploiting a delayed execution window, the attacker front‑ran a governance proposal, injected malicious code that redirected a portion of swap fees to their address. The weakness was an insufficient timelock on contract upgrades.
  3. Curve Finance Stable‑Coin Pump‑And‑Dump (2024) - A flash‑loan attacker manipulated the stable‑coin curve to create a price gap, then performed arbitrage across Curve pools and a centralized exchange, earning $15M. The exploit hinged on a mis‑priced “virtual balance” parameter.

How Attackers Execute Each Exploit

Below is a step‑by‑step view of the most common attack vectors. Understanding the flow makes it easier to interrupt it.

Flash‑Loan Attack Flow

  1. Call a flash‑loan provider (e.g., Aave) to borrow assets.
  2. Swap the borrowed assets in the target AMM, changing its price curve.
  3. Execute a second trade (often an arbitrage) that benefits from the manipulated price.
  4. Repay the flash loan plus fees in the same transaction.
  5. If the AMM’s accounting is naive, the attacker walks away with a net profit.

Sandwich Attack Flow

  1. Monitor the mempool for a large pending swap (the victim).
  2. Submit a transaction that trades just before the victim, pushing the price up.
  3. The victim’s trade executes at the worse price.
  4. Immediately submit a back‑run that trades in the opposite direction, capturing the spread.

MEV Manipulation Flow

  1. Run a private relayer that orders transactions for maximum profit.
  2. Bundle a series of trades (e.g., front‑run, victim, back‑run) into a single block.
  3. The miner includes the bundle, and the attacker extracts value from all three steps.

Mitigation Strategies for Developers

Fixing the root cause is cheaper than patching after a breach. Here are proven defenses.

  • Use Time‑Weighted Average Price (TWAP) instead of spot price when calculating swaps. This blunts flash‑loan spikes.
  • Introduce Slippage Limits that reject trades moving price beyond a preset threshold.
  • Apply Re‑entrancy Guards (the nonReentrant modifier) to all external calls.
  • Audit Oracle Sources - never trust a single on‑chain pool as its own price oracle.
  • Delay Administrative Actions with a timelock (e.g., 48‑hour delay) to prevent instant malicious upgrades.
  • Enable Block‑Level Price Checks that compare pre‑ and post‑trade reserves to detect abnormal shifts.
  • Deploy Multi‑Sig Governance for critical parameter changes, reducing single‑key exposure.

Auditor’s Checklist

Before you push an AMM contract to mainnet, run through this list. Treat each item as a quick test you can automate.

  1. Confirm all external calls are protected by a nonReentrant guard.
  2. Validate that price calculations use a TWAP window of at least 30seconds.
  3. Check that swap functions enforce a maximum slippage of 0.5% (or lower for volatile pairs).
  4. Ensure any admin function has a minimum 72‑hour timelock and requires multi‑sig approval.
  5. Run a simulation of flash‑loan scenarios using a forked mainnet and verify no net profit can be extracted.
  6. Audit integer math for overflow/underflow; prefer SafeMath or Solidity0.8+ built‑in checks.
  7. Review the contract’s upgrade path: are storage slots aligned and versioned?
Attack Type vs. Primary Mitigation
Attack Typical Symptom Key Mitigation
Flash‑Loan Drain Large profit after a single‑block trade TWAP pricing & slippage caps
Sandwich Victim trade executed at worse price than expected Dynamic slippage limits & order‑book simulation
MEV Bot Bundle Unusual bundle of three trades in one block Randomized transaction ordering or commit‑reveal
Liquidity Drain Pool balance shrinks dramatically without external market move Fee recalculation checks & withdrawal caps
Smart‑Contract Bug Re‑entrancy or overflow errors observed in testnets Formal verification & use of Solidity0.8 safety features
Frequently Asked Questions

Frequently Asked Questions

What makes AMMs different from order‑book exchanges?

AMMs rely on a mathematical formula and a pool of assets to price trades, so there’s no need for a buyer‑seller match. This design is simple but also opens up price‑manipulation vectors that don’t exist on traditional order books.

Can I protect my liquidity from sandwich attacks?

Yes. Use slippage limits, enable time‑weighted average pricing, and consider adding a commit‑reveal step for large swaps. Some protocols also offer “protected swaps” that delay execution by a few seconds to break the attacker’s timing.

How do flash‑loan attacks differ from regular loans?

Flash loans must be repaid in the same transaction block, which means the attacker can’t walk away with the borrowed capital unless the rest of the transaction succeeds. This forces them to combine the loan with a price manipulation that instantly yields profit.

Are there any AMM designs that are inherently safer?

Protocols that use a hybrid model-pairing a modest constant‑product pool with an external oracle or a dynamic fee schedule-tend to resist flash‑loan spikes better. Curve’s stable‑coin pools, for example, incorporate amplification parameters that dampen price swings.

What role does MEV play in AMM exploits?

MEV (Maximal Extractable Value) is the extra profit miners or validators can capture by re‑ordering, inserting, or suppressing transactions. In AMMs, MEV bots often bundle front‑run and back‑run trades around a victim’s swap, turning a normal trade into a lucrative sandwich.

15 Comments

  • Image placeholder

    Jacob Anderson

    October 8, 2024 AT 23:40

    Oh great, another brilliant checklist that assumes developers actually read docs.

  • Image placeholder

    Ben Dwyer

    October 9, 2024 AT 00:21

    Nice rundown, really consolidates the main attack vectors. The checklist at the end is practical and something devs can actually run against their code. Remember, the best defense is layering these mitigations early, not patching after a breach.

  • Image placeholder

    Katrinka Scribner

    October 9, 2024 AT 01:03

    Wow, this post is super helpful! 😍 I love how it breaks down flash‑loan attacks step‑by‑step, made it so clear for newbies like me. Just wish there were more pictures, lol 😅

  • Image placeholder

    Billy Krzemien

    October 9, 2024 AT 01:45

    The guide does a solid job of highlighting the most common pitfalls in AMM contracts. I especially appreciate the emphasis on TWAP and slippage caps; those are often overlooked. Deploying a timelock is a low‑cost change that can save millions.

  • Image placeholder

    Clint Barnett

    October 9, 2024 AT 02:26

    When you dive into the rabbit hole of AMM design, the first thing that hits you is how elegantly simple the constant‑product formula appears. Yet underneath that simplicity lies a sprawling garden of edge cases waiting to bite the unwary. Take flash‑loan resilience: if you rely on a single‑block price snapshot, you hand a predator a perfectly sharpened spear. Introducing a TWAP window-say thirty seconds-turns that spear into a blunt rod that merely nudges the pool. Similarly, slippage caps are not just UI niceties; they act as a friction brake for sandwich bots that sprint ahead of a victim’s trade. A well‑tuned cap of half a percent can deflate many front‑running attempts without inconveniencing casual users. Re‑entrancy guards, the nonReentrant modifier, are the equivalent of a dead‑bolt on a front door; forget them and anyone can walk in and out with the loot. Timelocks on governance actions are the temporal equivalent of a safe‑deposit box: they give the community a chance to spot malicious code before it’s pressed. Beyond code, the economic parameters-fee structures, amplification factors, virtual balances-must be stress‑tested against extreme market swings. A curve‑style stable‑coin pool, for instance, uses an amplification coefficient that cushions price drift, but if that coefficient is mis‑configured, the pool can become a vacuum that sucks in liquidity. Auditors should also simulate multi‑hop flash‑loan attacks on a forked mainnet to see whether any arbitrage loop leaves a net profit. Don’t forget the human factor: multi‑sig governance adds a social layer of defense that a single rogue key cannot bypass. Finally, continuous monitoring-on‑chain analytics that flag sudden reserve imbalances-acts as an early warning system. In short, layering TWAP, slippage limits, re‑entrancy guards, timelocks, and vigilant governance creates a defense‑in‑depth strategy that is far tougher to breach. Neglect any of these, and you’re essentially leaving the back door wide open for the next flash‑loan marauder.

  • Image placeholder

    Rajini N

    October 9, 2024 AT 03:08

    Great summary of the attack flows. For developers, I recommend integrating a TWAP oracle right from testnet to catch price spikes early. Also, keep your admin functions behind a 48‑hour timelock to deter rushed upgrades.

  • Image placeholder

    Oreoluwa Towoju

    October 9, 2024 AT 03:50

    Clear and concise, thanks for the cheat sheet. The bullet points make it easy to scan.

  • Image placeholder

    Amie Wilensky

    October 9, 2024 AT 04:31

    Indeed, the list is exhaustive; however, one could argue that not every point is equally critical, especially in low‑volume pools, which perhaps deserve a more nuanced approach; still, the depth is impressive.

  • Image placeholder

    Naomi Snelling

    October 9, 2024 AT 05:13

    Did you know the big players might be hiding behind these so‑called 'transparent' protocols? I suspect there's a coordinated effort to keep the public in the dark.

  • Image placeholder

    Michael Wilkinson

    October 9, 2024 AT 05:55

    If you think adding a single guard will stop all attacks, you’re dreaming.

  • Image placeholder

    Kate Nicholls

    October 9, 2024 AT 06:36

    The post is thorough, but it glosses over the risk of oracle manipulation in cross‑chain setups. A more detailed look at hybrid price feeds would strengthen the advice.

  • Image placeholder

    Carl Robertson

    October 9, 2024 AT 07:18

    Wow, this reads like a thriller novel about code! The drama of flash‑loan exploits is real, and the stakes couldn't be higher.

  • Image placeholder

    MD Razu

    October 9, 2024 AT 08:00

    The architecture of AMMs, when examined through a philosophical lens, reveals a paradox of decentralization and centralization. On one hand, the code is immutable and trustless; on the other, the economic parameters are often governed by a handful of entities. This duality creates a fertile ground for both innovation and exploitation. Understanding the incentives that drive attackers is as crucial as fixing the technical bugs. A robust design must therefore embed not only mechanical safeguards like re‑entrancy guards but also governance safeguards that distribute power. Only then can the ecosystem hope to achieve a sustainable equilibrium.

  • Image placeholder

    Charles Banks Jr.

    October 9, 2024 AT 08:41

    Oh sure, just sprinkle a few governance tokens and the problem disappears, right? It’s not like attackers will just wait for a chance to profit.

  • Image placeholder

    Lindsay Miller

    October 9, 2024 AT 09:23

    I get that it can feel overwhelming when every fix seems to open another gap. Remember, each incremental improvement builds a stronger barrier. Keep focusing on the basics, and the system will become more resilient over time.

Write a comment