Skip to content

Instantly share code, notes, and snippets.

@npodonnell
Last active February 7, 2023 16:02
Show Gist options
  • Save npodonnell/f68dabf010ac9e60b399b465e5da530f to your computer and use it in GitHub Desktop.
Save npodonnell/f68dabf010ac9e60b399b465e5da530f to your computer and use it in GitHub Desktop.
Uniswap v3 Formulae

Uniswap Formulae

Notes:

  • Lower-case x and y denote virtual or v1 reserves, upper-case X and Y denote v3 real reserves.
  • The v3 formulae have been adapted from those in the whitepaper to be in terms of price, not square-root-price.

v1/v2 Formulae

Constant Product Formula

$$ xy = k $$

Liquidity Formula

$$ L = \sqrt{k} $$

Price Formula

$$ P = \frac{y}{x} $$

Reserves

$$ x = \frac{L}{\sqrt{P}} \qquad y = L \sqrt{P} $$

v3 Formulae

Opening/Closing Positions

Used to compute the amount of asset0 (X) and asset1 (Y) to add (remove) when opening (closing) a position.

NOTE: Github is not correctly rendering this.

∆X =

$$ \Delta X = left{ \begin{array}{l l} \Delta L \cdot ( \frac{1}{\sqrt{p_l}} - \frac{1}{\sqrt{p_u}} ) & \quad P \le p_l \\ \Delta L \cdot ( \frac{1}{\sqrt{P}} - \frac{1}{\sqrt{p_u}} ) & \quad p_l \le P \le p_u \\ 0 & \quad p_u \le P \\ \end{array} \right. $$

∆Y =

$$ \Delta Y = \left{ \begin{array}{l l} 0 & \quad P \le p_l \\ \Delta L \cdot ( \sqrt{P} - \sqrt{p_l} ) & \quad p_l \le P \le p_u \\ \Delta L \cdot ( \sqrt{p_u} - \sqrt{P_l} ) & \quad p_u \le P \\ \end{array} \right. $$

Swapping

Mathematically, there exist two types of swap:

  1. Volume-based
  2. Price-based

In a volume-based swap the user specifies a volume of asset0 or asset1 they want to put in (take out) of the pool, then the pool calculates the new price and the amount of the other asset they'll need to take out (put in). In a price-based swap, the user specifies a destination price they want the current price to move to, then the pool calculates the amounts of asset0 and asset1 they need to put in/take out of the pool.

In practice nearly all swaps are volume-based, or a combination of the two.

Swapping

(i) Next price given liquidity, current price, and ∆X:

$$ P_n = \frac{L^2 P_c}{(\Delta X \sqrt{P_c} + L)^2} $$

(ii) Next price given liquidity, current price, and ∆Y:

$$ P_n = (\frac{\Delta Y}{L} + \sqrt{P_c})^2 $$

(iii) Asset0 delta given liquidity, current, and next prices:

$$ \Delta X = \frac{L}{\sqrt{P_n}} - \frac{L}{\sqrt{P_c}} $$

(iv) Asset1 delta given liquidity, current, and next prices:

$$ \Delta Y = L \cdot (\sqrt{P_n} - \sqrt{P_c}) $$

Note: formulae (i) and (iii) are re-arrangements of each other as are (ii) and (iv)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment