The AMM Security Deep Dive - Part 1: The foundations of decentralized trading
AMMDeFi

The AMM Security Deep Dive - Part 1: The foundations of decentralized trading

September 22, 2025
M3D
M3D

1. Introduction: A new paradigm for liquidity

For decades, the engine of financial markets has been the central limit order book (CLOB). Buyers and sellers declare their intent—their orders—and a central matching engine pairs them up. This model works exceptionally well in high-throughput, low-latency environments. But when we try to transpose it directly onto a blockchain like Ethereum, the model breaks down. The very act of placing, canceling, or modifying an order becomes a gas-consuming transaction. On a congested network, the cost and latency of maintaining an active order book are simply prohibitive. The architecture of the blockchain is fundamentally at odds with the architecture of the order book.
This friction gave rise to one of Decentralized Finance's foundational pillars: the Automated Market Maker (AMM). An AMM is an elegant, blockchain-native solution to the problem of on-chain liquidity. Instead of matching individual buyers and sellers, an AMM creates a peer-to-pool system where users trade against a reserve of assets held in a smart contract. Liquidity is available 24/7, managed not by a central party, but by a deterministic algorithm.
The goal of this first article is to deconstruct the simple but powerful mathematical principle that powers the first generation of AMMs. We will translate this principle into its core smart contract primitives, establishing the first-principles understanding required to properly analyze its security implications.

2. The core engine: The constant product formula

The magic behind the original AMM model, popularized by Uniswap, is a single, disarmingly simple formula:
xy=kx * y = k
This is the Constant Product Formula, and it's the heart of the entire system. Let’s break down its components from first principles:
  • x: Represents the total reserve of one asset in the liquidity pool (e.g., the amount of ETH).
  • y: Represents the total reserve of the other asset in the liquidity pool (e.g., the amount of USDC).
  • k: The constant product, often called the "invariant." This value is the cornerstone of the model. The protocol's primary directive is to ensure that, for any trade, the product of the reserves after the trade is equal to the product of the reserves before the trade.
So, why does this work? The formula creates an inverse relationship between the two assets. To withdraw some amount of asset y from the pool, you must deposit a proportional amount of asset x to keep the product k constant (ignoring fees for a moment). The price of an asset is not set by an external oracle or an order book; it is discovered organically as a function of the ratio between x and y at any given moment.
Let's walk through a concrete example.
Imagine a liquidity pool for ETH/USDC with the following state:
  • x (ETH reserve) = 10
  • y (USDC reserve) = 50,000
First, we calculate our invariant, k:
  • k = 10 * 50,000 = 500,000
The spot price of ETH in this pool is y / x, or 50,000 / 10 = 5,000 USDC per ETH.
Now, a trader wants to sell 1 ETH into the pool. They will send 1 ETH to the contract, increasing the ETH reserve.
  • The new ETH reserve, x', is 10 + 1 = 11 ETH.
To find out how much USDC the trader receives, the contract must solve for the new USDC reserve, y', that maintains the invariant k:
  • x' * y' = k
  • 11 * y' = 500,000
  • y' = 500,000 / 11 ≈ 45,454.55 USDC
This y' is the amount of USDC that must remain in the pool. The amount sent to the trader is the difference:
  • USDC out = y - y' = 50,000 - 45,454.55 = 4,545.45 USDC
The trader sent 1 ETH and received 4,545.45 USDC. The act of trading changed the reserve ratio, and therefore, the price. The new spot price is now 45,454.55 / 11 ≈ 4,132.23 USDC per ETH. This price movement is a fundamental property we'll revisit.

3. From math to code: The three core primitives of a pool

The constant product formula is the theoretical engine. In a DEX pair contract, this theory is implemented through three core state-changing functions, or primitives, that users can call.
1. Providing Liquidity (addLiquidity) Before any trades can happen, the pool needs assets. This is the role of Liquidity Providers (LPs). A user provides liquidity by depositing a proportional amount of both token0 and token1 into the pool contract. For example, if the pool holds 10 ETH and 50,000 USDC (a 1:5000 ratio), a new LP must deposit assets in that same ratio.
In exchange for their deposit, the contract mints and sends them a special token known as an LP token. This token is a critical accounting mechanism; it represents the provider's proportional claim on the pool's total assets. If an LP's tokens represent 10% of the total LP token supply, they are entitled to withdraw 10% of the pool's ETH and USDC reserves.
2. Swapping Tokens (swap) This is the core trading function we demonstrated in our numerical example. A user initiates a swap by sending a certain amountIn of one token to the contract. The contract receives these tokens, updates its internal reserve balance, and then uses the constant product formula to calculate the amountOut of the other token. Finally, it transfers the amountOut to the user. This entire operation—receive token, calculate output, send token—occurs atomically within a single transaction.
3. Removing Liquidity (removeLiquidity) At any time, a liquidity provider can decide to exit their position. To do this, they send their LP tokens back to the pair contract. The contract "burns" (destroys) these LP tokens and, in return, calculates the user's proportional share of the current token0 and token1 reserves. It then transfers these assets back to the user. The ratio of assets the LP receives upon withdrawal may be different from the ratio they initially deposited, a phenomenon we will explore next.

4. Inherent risks and economic assumptions (The Security Angle)

The first step in a robust security analysis is to understand the system's inherent properties and assumptions. These are not "bugs" or implementation flaws; they are fundamental characteristics of the model itself. For a constant product AMM, three stand out.
Impermanent Loss This is the most critical risk for liquidity providers. Impermanent Loss (IL) is the difference in value between holding two assets in a liquidity pool versus simply holding them in a wallet. If the market price of the assets in the pool diverges—in either direction—from the price at the time of deposit, LPs will suffer a loss relative to just holding the assets. This happens because arbitrageurs constantly rebalance the pool to match external market prices, buying the asset that has become cheaper in the pool and selling the one that has become more expensive. In doing so, they change the ratio of assets held by the LPs. An LP is only profitable if the trading fees they earn are greater than the value lost to IL. It is the fundamental economic cost of providing passive liquidity.
Price Slippage As we saw in our numerical example, the marginal price of a token changes as you trade against the pool. The x*y=k formula creates a hyperbolic curve. For small trades relative to the pool's size, the price impact is minimal. But for large trades, the trader is pushed further along the curve, resulting in a progressively worse execution price. This is slippage. It is a necessary feature, as it acts as a braking mechanism that makes it exponentially more expensive to drain a pool of one asset. However, it can be a vector for value extraction (e.g., sandwich attacks) and results in poor execution for large traders if liquidity is thin.
The insecure Oracle problem (A Teaser) The spot price of an AMM pool (reserveY / reserveX) is trivial to manipulate. An attacker can use a flash loan to execute a massive trade, momentarily shift the reserve ratio to a desired value, perform an action on another protocol that relies on this manipulated price, and then trade back to restore the original price, all within a single atomic transaction. This makes the instantaneous spot price of a simple AMM a fundamentally insecure price oracle. Using it as a source of truth for critical operations like issuing loans is one of the most common and devastating vulnerabilities in DeFi. This will be a central topic in Part 3 of this series.

5. Conclusion: A foundation to build on

The constant product AMM is a revolutionary piece of financial engineering. It elegantly solves the on-chain liquidity problem by replacing the complex, high-touch order book with a simple, passive liquidity pool governed by the x * y = k invariant. Its operation is defined by three core primitives: adding liquidity, swapping tokens, and removing liquidity.
However, its revolutionary simplicity is also its limitation. The capital spread across the entire price curve from zero to infinity is inefficient, and the risk of impermanent loss is a significant deterrent for liquidity providers. This foundation, while powerful, left clear room for improvement.
In our next post, we will explore how protocols like Uniswap V3, Curve, and Balancer have iterated on this foundational model. They introduced new mathematical invariants and architectural patterns to create more complex, specialized, and capital-efficient systems, each bringing its own unique set of security challenges.

Get in touch

At Zealynx, we specialize in uncovering and mitigating the kinds of risks described above. If you’re building in DeFi, let’s talk security — reach out.
Want more articles like this? Subscribe to our newsletter so you don’t miss the next parts of this series.

FAQ: Key concepts used in AMM security - Part 1

1. What is a central limit order book (CLOB)?
A central limit order book is a traditional system used in financial markets where buyers and sellers submit orders, and a central engine matches them based on price and time. It’s efficient in centralized, high-speed environments but difficult to implement on slow, expensive blockchains.
2. What are liquidity providers (LPs) and LP tokens?
Liquidity providers are users who deposit assets into an AMM pool, enabling others to trade. In return, they receive LP tokens, which represent their proportional share of the pool and can be redeemed for the underlying assets.
3. What is arbitrage in the context of AMMs?
Arbitrage is the practice of exploiting price differences between markets. In AMMs, arbitrageurs rebalance pools by trading when the AMM price diverges from the market price, helping to keep prices accurate but also causing impermanent loss for LPs.
4. What is a flash loan?
A flash loan is a type of uncollateralized loan in DeFi that must be borrowed and repaid within a single blockchain transaction. Flash loans are often used for arbitrage, liquidations, or, in some cases, for manipulating on-chain prices.
5. What does “atomic transaction” mean in smart contracts?
An atomic transaction is a blockchain operation where all steps must succeed or none do. This ensures that complex operations (like swaps or flash loans) either complete fully or revert, preventing partial execution.
6. What is slippage tolerance, and why does it matter?
Slippage tolerance is a user-defined limit on how much the execution price of a trade can differ from the expected price. Setting this helps protect traders from large, unexpected losses due to price movements during their transaction.

oog
zealynx

Subscribe to Our Newsletter

Stay updated with our latest security insights and blog posts

© 2024 Zealynx