# OVERVIEW $$L = \sqrt{xy}$$ $$\sqrt{P} = \sqrt{\frac{y}{x}}$$ $L$ is the current amount of liquidity. $xy$ is actually the $k$-constant. $y / x$ is price of token $0$ in terms of token $1$. ## Reason of using $\sqrt{P}$ instead of $P$ - Square root precision calculation. Instead of having to calculate it everytime, it's easier to only store it. - $\sqrt{P}$ has a connection to $L$. $$L = \frac{\Delta{y}}{\Delta{\sqrt{P}}}$$ ### Proof $$L = \frac{\Delta{y}}{\Delta{\sqrt{P}}}$$ $$\sqrt{xy} = \frac{\Delta{y}}{\Delta{\sqrt{P}}}$$ $$\sqrt{xy} = \frac{y_1 - y_0}{\sqrt{P_1} - \sqrt{P_0}}$$ $$\sqrt{xy}(\sqrt{P_1} - \sqrt{P_0})=y_1 - y_0$$ $$\sqrt{x_1y_1P_1} - \sqrt{x_0y_0P_0}=y_1-y_0$$ $$y_1 - y_0 = y_1 - y_0$$ **Conclusion**: Liquidity is the relation between the change of output amount and the change in $P$ ## Pricing From above, we can calculate the output amount right away without finding the actual prices. $$\Delta{y}=L\Delta{\sqrt{P}}$$ $$\Delta{x}=\Delta{\frac{1}{\sqrt{P}}}L$$ ## Ticks $p(i)=1.0001^i$ is the price at tick $i$. ### Warning - Uniswap V3 stores $\sqrt{P}$ instead of $P$. So $\sqrt{P}=1.0001^{i/2}$. Ticks in Uniswap can be negative and not infinite. $\sqrt{P}$ is stored as a fixed point Q64.96 number, so the price of $P$ is in the range $[-2^{128}\ldots2^{128}]$. From that, ticks is in the range of $[log_{1.0001}{-2^{128}} \ldots log_{1.0001}{2^{128}}]$ = $[-887272 \ldots 887272]$. # Add liquidity ## Liquidity Amount Calculation **Warning**: This only allows add within the price range include the current price. - We need to calculate $L$ base on the amount and the range prices we deposit. - What we have now? - $\Delta{X}$ and $\Delta{Y}$. - $p_a$ and $p_b$, which is the lower and upper price ranges. - Calculate $L$ on two separate segments as the left segment contains only $x$ and right segment contains only $y$. $$L_{left} = \Delta{x}\frac{\sqrt{P_b}\sqrt{P_c}}{\sqrt{P_b} - \sqrt{P_c}}$$ $$L_{right}= \frac{\Delta{y}}{\sqrt{P_c} - \sqrt{P_a}}$$ $$L=min(L_{left}, L_{right})$$ ## Verify the token amount have to add into pool - Now that we have calculated $L$, we can verify how much we have to deposit to gain that liquidity amount. $$\Delta{x}=L\frac{\sqrt{P_b} - \sqrt{P_c}}{\sqrt{P_b}\sqrt{P_c}}$$ $$\Delta{y}=L(\sqrt{P_c}-\sqrt{P_a})$$ # First swap **Warning**: This only allows swap in the current price ranges. ## Buy $x$ from $y$. We know the formula: $$\Delta{Y}=L\Delta{\sqrt{P}}$$ In a swapping of a price range, $L$ remains unchanged, only price change. So that we can easily calculate the new price. $$\sqrt{P_{target}} = \sqrt{P_{current}} + \Delta{\sqrt{P}}$$ After finding the price target, we can find the amount $$x=L\frac{\sqrt{P_b}\sqrt{P_a}}{\sqrt{P_b} - \sqrt{P_a}}$$ $$y=L(\sqrt{P_b}-\sqrt{P_a})$$ ## Buy $y$ from $x$ We know the formula $$\Delta{X}=\Delta{\frac{1}{\sqrt{P}}}L$$ $$\Delta{X}=(\frac{1}{\sqrt{P_{target}}} - \frac{1}{\sqrt{P_{current}}})L $$ $$...$$ $$\sqrt{P_{target}}=\frac{\sqrt{P}L}{\Delta{X}\sqrt{P}+L}$$