[en] UniswapV2 forks and constant product AMMs

In the DeFi ecosystem, Automated Market Makers (AMMs) represent a fundamental innovation by removing intermediaries and traditional order books. Among them, Uniswap V2 has solidified its position as a leading protocol and has served as the basis for numerous forks. The key to Uniswap V2’s efficiency and robustness lies in the “Constant Product Market Maker” (CPMM) model, whose central premise is to keep the product of the reserves of two tokens, X and Y, constant.

This mathematical invariant is not a mere whim: it ensures that, after any swap, total liquidity is not reduced, thereby protecting liquidity providers (LPs) and maintaining the economic integrity of the system. In this article, we will explore Uniswap V2’s architecture, the math behind the K invariant, the implications of fees, the interactions with arbitrage, oracles, and MEV, and we will show—through the Uranium Finance case—how disastrous it can be to tinker irresponsibly with the protocol’s mathematical machinery.


Constant K: The Invariant That Shapes Price and Preserves Integrity

In a constant product AMM, each pool contains two tokens, for example Token X and Token Y. The fundamental formula is K = X * Y.

This product K must remain constant (or at least not decrease) before and after the swap. In practice, Uniswap V2 applies a 0.3% fee on the input amount, resulting in an adjustment factor (for example, a 1000 multiplier and a fee of 3, equivalent to 0.3%). Without a fee, we would have: (X + ΔX) * (Y - ΔY) = K.

With the fee, the effective amount of ΔX entering the pool after deduction is smaller, ensuring that K' (the new product after the swap) is at least equal to or greater than K. This benefits LPs since the pool’s total value increases with every trade.

This mechanism ensures internal balance: if the pair’s price diverges from the market price, arbitrageurs step in to restore equilibrium. Thus, the AMM acts as an autonomous price discovery system, without the need for limit orders typical of order books.


The Uniswap V2 Architecture: Simplicity at the Core, Flexibility at the Periphery

Uniswap V2 follows a “core/periphery” architectural pattern:

  • UniswapV2Factory: Creates new pairs (pools) for any combination of tokens.
  • UniswapV2Pair: Each pair is a separate contract that holds two tokens and allows swaps, as well as liquidity provision and removal. The pair itself is an ERC-20 token representing LP shares.
  • Router (Periphery): Facilitates complex interactions, such as executing trades across multiple pools in a single transaction.

This separation reduces the likelihood of bugs in the core, which retains only the essential logic. It’s a minimalist yet powerful design. Uniswap V2 also has relatively low gas costs compared to an on-chain order book, since the contract only holds two balances.


AMMs, Price Discovery, and Oracles

The marginal price of a token in an AMM is determined by the ratio between the pair’s token quantities. If X is abundant, its price relative to Y falls, encouraging trades that restore equilibrium. Thus, the AMM also acts as a price oracle. However, this oracle is susceptible to short-term manipulation, especially via flash loans. That’s why protocols using Uniswap V2 as an oracle often apply techniques like TWAP (Time-Weighted Average Price).


Slippage, MEV, and Sandwich Attacks

Unlike an order book, even small orders in an AMM shift the price, causing slippage. This behavior—where any trade alters the X/Y ratio—creates opportunities for MEV (Maximal Extractable Value) attacks.

  • Sandwich attacks: An attacker places a buy order before the victim’s order, pushing the price up. Right after the victim buys at the higher price, the attacker sells, profiting from the price difference. This is an inevitable side effect in AMMs, as any transaction moves the price.

Liquidity Providers: Impermanent Loss and Constraints

LPs provide liquidity by adding proportional amounts of X and Y. The invariant K = X * Y requires maintaining this proportion. It’s not possible to set specific buy or sell prices; the LP “follows the market.” This leads to impermanent loss (IL) when one token appreciates or depreciates. Even though K increases over time, the LP might have earned more by simply holding the assets separately, without providing liquidity.


The Uranium Finance Case: When Poorly Adjusted Parameters Break K

The original Uniswap V2 uses carefully chosen factors (e.g., 1000 and 3) to apply the 0.3% fee. In Uranium Finance, a Uniswap V2 fork on the BNB Chain, the multipliers were changed to 10000 and 16, but the final require for the K invariant remained using 1000^2.

This created a mismatch: the adjusted calculations were based on 10000, but the final check still used 1000. This error allowed the contract to accept impossible swaps, draining absurd amounts of one of the tokens without “technically” breaking the K invariant in code. The result? Over $50 million lost in one of the most devastating attacks of the time.


The Math Behind CFMMs

K = X * Y is a specific case of Constant Function Market Makers (CFMMs). Academic research shows that these functions underpin capital efficiency and economic robustness in AMMs. Small errors, like Uranium Finance’s, open the door to infinite arbitrage opportunities or value creation out of thin air, destroying the system’s equilibrium.


Best Practices: Audits, Testing, and Deep Understanding

How to avoid issues like Uranium Finance?

  • Deep Understanding: Know why 1000 and 3 were chosen and how the fee affects K.
  • Audits and Formal Verification: Specialized firms, tools like Certora or Echidna, and fuzz testing (Foundry) can detect flaws.
  • Extensive Testing: Simulate extreme scenarios, altering fees and testing minimum and maximum values.
  • Study Real Cases (Post-Mortems): Analyzing famous exploits helps prevent repeating past mistakes.

Conclusion:

Uniswap V2 and its forks show how the simple math of K = X * Y created a vibrant DeFi ecosystem. However, the Uranium Finance case warns that tinkering with these “magic numbers” without maintaining coherence throughout the code is like tampering with the gravitational force that keeps the AMM stable.

In the end, AMM security is not just about flawless code, but also solid economic reasoning. K is not a trivial detail; it’s the heartbeat that sustains AMM equilibrium. Altering it carelessly is lighting a fuse that could cost millions.

In short, the Constant K is not just a formula—it’s the AMM’s soul. Changing it recklessly means risking everything, in a market where math rules supreme.

Subscribe to HellHex

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe