You deposit your hard-earned assets into a decentralized exchange, expecting steady yield. Instead, you wake up to find the price of your token has crashed by 90%, or worse, the entire liquidity pool has been drained. This isn't just bad luck; it is often the result of sophisticated AMM vulnerabilities being exploited by attackers who know exactly how to manipulate the math behind automated market makers.
Automated Market Makers (AMMs) revolutionized finance by removing order books and allowing anyone to trade against a pool of liquidity. But this convenience comes with a massive attack surface. Unlike traditional exchanges where humans manage risk, AMMs rely on immutable code. If that code has a flaw, or if the mathematical model can be gamed, millions of dollars can vanish in seconds. Understanding these exploits is not just for developers; it is essential for anyone holding assets in DeFi.
The Mechanics of Flash Loan Attacks
To understand how AMMs get hacked, you first need to grasp the weapon of choice: the flash loan. A flash loan allows a user to borrow millions of dollars without collateral, provided they return the money within the same blockchain transaction. It sounds like magic, but it is actually just clever coding. The problem arises when an attacker uses this borrowed capital to manipulate the price of an asset in a vulnerable pool.
| Attack Type | How It Works | Who Gets Hurt? |
|---|---|---|
| Flash Loan Manipulation | Attacker borrows huge amounts, trades to skew price, then exploits another protocol using the fake price. | Liquidity Providers & Other Protocols |
| Sandwich Attack | Bot detects your pending buy order, buys before you to raise price, sells after you to profit from your loss. | Regular Traders |
| Oracle Manipulation | Attacker manipulates the spot price which serves as the oracle for lending protocols. | Lending Platforms |
| Reentrancy | Contract calls back into itself before updating balances, draining funds repeatedly. | The Protocol Treasury |
Here is how a typical flash loan exploit unfolds. Imagine a small token, let's call it "MoonCoin," is paired with Ethereum in a liquidity pool. There is also a lending platform that uses the price of MoonCoin from that pool to decide if borrowers are solvent. An attacker borrows $10 million worth of ETH via a flash loan. They dump all that ETH into the MoonCoin pool. Because the pool is small, the price of MoonCoin skyrockets artificially. The lending platform sees this high price and thinks MoonCoin is valuable. The attacker then deposits their inflated MoonCoin into the lending platform as collateral and borrows out stablecoins. Finally, they repay the flash loan, leaving the lending platform with worthless MoonCoin and empty pockets. This happened famously with dYdX and Cream Finance in earlier years, resulting in losses exceeding $13 million each.
Sandwich Attacks: The Tax on Your Trades
If flash loans are the heavy artillery, sandwich attacks are the everyday harassment. You might have experienced this yourself. You try to swap a large amount of tokens on a decentralized exchange, and suddenly the slippage is higher than expected, or you receive fewer tokens than the quote showed. That is likely because a bot "sandwiched" your transaction.
These bots monitor the mempool-the waiting area for unconfirmed transactions. When they see a large buy order coming in, they use their own funds to buy the token *before* your transaction executes. This drives up the price. Your transaction then goes through at this higher price. Immediately after, the bot sells their tokens to you at the peak. You end up buying high, and the bot profits from the spread. This is a form of Maximal Extractable Value (MEV), where validators and searchers extract value from the ordering of transactions. While not technically a "bug" in the code, it is a vulnerability in the design of public mempools. Projects like Uniswap face constant sandwich attacks, costing users millions annually in hidden fees.
Smart Contract Bugs: Reentrancy and Logic Errors
Beyond economic manipulation, there are plain old coding errors. The most notorious is reentrancy. In a simple scenario, a contract sends funds to a user and then updates their balance. A malicious contract can intercept that fund transfer and call the withdrawal function again *before* the balance is updated. It keeps calling itself until the pool is dry. This was the method used in the infamous DAO hack in 2016, though modern AMMs have largely patched this specific issue. However, new logic errors emerge constantly.
Consider the case of incorrect fee calculations or rounding errors. If an AMM rounds down fees incorrectly over thousands of transactions, an attacker can exploit the discrepancy to drain small amounts continuously. Another common issue is improper access control. If a developer forgets to restrict a "withdraw" function to only the owner, any random user can trigger it and empty the treasury. These are preventable, yet they happen regularly because many DeFi projects rush to launch without rigorous audits.
Oracle Manipulation and Price Feeds
Many AMMs do not just sit there; they interact with other protocols. To do this safely, they need accurate price data. Often, they use the current spot price of the pair as the oracle. This creates a critical weakness. As seen in the flash loan example, if the price feed relies on a single, manipulatable pool, the whole system is fragile.
Robust systems use Time-Weighted Average Prices (TWAP). Instead of looking at the price right now, TWAP looks at the average price over the last hour or day. This makes it much harder for an attacker to skew the price instantly. However, implementing TWAP correctly is tricky. If the window is too short, it can still be manipulated. If it is too long, it becomes stale. Projects like Chainlink provide decentralized oracle networks to solve this, but integrating them adds complexity and cost. Many smaller AMMs skip this step, leaving them wide open to oracle manipulation attacks.
Impermanent Loss vs. Exploitation
It is crucial to distinguish between impermanent loss and an actual exploit. Impermanent loss is a mathematical certainty when providing liquidity to volatile pairs. If one token pumps while the other stays flat, the AMM rebalances by selling the winner and buying the loser. You end up with less value than if you had just held the tokens. This is not a hack; it is the cost of doing business in an AMM. However, sophisticated actors can engineer scenarios that accelerate this loss for providers while profiting themselves, blurring the line between market dynamics and exploitation.
How to Protect Yourself and Your Protocols
For developers, the defense starts with auditing. Never deploy code that hasn't been reviewed by multiple independent firms. Use established libraries rather than writing custom math functions. Implement circuit breakers-mechanisms that pause trading if prices move too drastically in a short time. For users, the advice is simpler but harder to follow: stick to deep, liquid pools on reputable platforms. Avoid providing liquidity to new, low-cap tokens unless you are prepared to lose everything. Always check if the project uses secure oracles like Chainlink instead of relying on internal spot prices.
DeFi is permissionless, which means it is open to innovation but also open to abuse. As the ecosystem matures, we see more sophisticated defenses, such as intent-based architectures that hide transaction details until execution. Until then, understanding these vulnerabilities is your best shield. The code doesn't lie, but it can be tricked. Stay vigilant, audit your interactions, and never trust a yield that seems too good to be true-it probably is.
What is the most common AMM exploit?
The most common exploits involve flash loan attacks combined with oracle manipulation. Attackers use uncollateralized loans to skew token prices in liquidity pools, tricking other protocols into accepting undervalued collateral or paying out excessive rewards.
Can I recover funds lost to a sandwich attack?
Generally, no. Once a transaction is confirmed on the blockchain, it is irreversible. Sandwich attacks are considered legal (though unethical) market behavior by most standards. Prevention involves using private RPC nodes or services that protect your transaction from being visible in the public mempool.
Are Uniswap and SushiSwap vulnerable to hacks?
While their core contracts are heavily audited and secure, they are frequently targeted by MEV bots for sandwich attacks. Direct hacks of the core protocol are rare due to robust security, but peripheral integrations or new versions may introduce temporary risks.
What is a reentrancy attack in DeFi?
A reentrancy attack occurs when a smart contract calls an external contract, which then calls back into the original contract before the first operation is complete. This can allow an attacker to withdraw funds multiple times before the balance is updated, draining the pool.
How do Time-Weighted Average Prices (TWAP) help security?
TWAP calculates the average price over a period (e.g., 10 minutes) rather than the current spot price. This makes it difficult for attackers to manipulate the price instantly with flash loans, providing a more accurate and secure reference for lending and borrowing protocols.
More Articles
How to Avoid Crypto Restrictions in China
China's 2025 crypto ban makes holding or trading cryptocurrency illegal for all citizens-even overseas. This article explains why there are no safe workarounds and what happens if you get caught.