Understanding the Constant Product Formula in AMMs (Without Getting Tricked by k)
Source: Dev.to
The Core Idea: What Does x * y = k Actually Mean?
In a constant‑product AMM:
x * y = k
- x = reserve of token A
- y = reserve of token B
- k = a constant
During a swap, k must remain constant. The reserves change, but the product of the reserves stays the same—that’s the entire pricing mechanism.
Initial State
uint256 reserveA = 1000;
uint256 reserveB = 1000;
Compute k:
uint256 k = reserveA * reserveB; // 1_000_000
This k defines the curve the pool must stay on.
A User Swaps Token A for Token B
The user swaps:
uint256 amountAIn = 100;
Step 1: Use the Current Invariant
uint256 k = reserveA * reserveB; // 1,000,000
This is the only valid k for this swap.
Step 2: Add the Incoming Tokens
uint256 newReserveA = reserveA + amountAIn; // 1,100
We now know the new A reserve but not the new B reserve.
Step 3: Solve for the New B Reserve
To preserve the invariant:
uint256 newReserveB = k / newReserveA; // ≈ 909.09
Step 4: Calculate What the User Receives
uint256 amountBOut = reserveB - newReserveB; // ≈ 90.91
The user receives ~90.91 token B, and the pool stays on the same curve.
Verifying the invariant
1100 * 909.09 ≈ 1,000,000
The invariant holds.
The Common Mistake: Recomputing k
A lot of people instinctively try this instead:
uint256 newK = newReserveA * reserveB; // 1,100 * 1,000 = 1,100,000
uint256 newReserveB = newK / newReserveA; // = 1,000
uint256 amountBOut = reserveB - newReserveB; // = 0
The user gets nothing because this logic moves the pool to a new curve, violating the fundamental invariant.
The Real Swap Equation
The actual AMM equation during a swap is:
(reserveA + amountIn) * (reserveB - amountOut) = reserveA * reserveB
Solving for amountOut:
uint256 amountOut = reserveB - (reserveA * reserveB) / (reserveA + amountIn);
That is exactly what Uniswap‑style contracts implement—no magic, just algebra.
Why the Old k Must Be Used
- k represents the curve.
- A swap moves the pool along the same curve.
- Adding liquidity creates a new curve.
- Swaps do not create a new curve.
If you recalculate k during a swap, you’re jumping to a different curve, and pricing instantly breaks.
Mental Model That Helps
- Think of k as a rail track.
- Liquidity providers lay down new tracks (new k).
- Traders move along the existing track.
- You never redraw the track mid‑swap.
Takeaway
- k is not recomputed during swaps.
- The invariant defines the pricing curve.
- Swaps must start and end on the same curve.
- Using a “new k” destroys the AMM logic.
If this ever feels counterintuitive again, just remember:
Swaps move the pool along the curve — they don’t redraw it.
