diff --git a/amm-v2-docs/formula.md b/amm-v2-docs/formula.md index 31db604..b8d9dcd 100644 --- a/amm-v2-docs/formula.md +++ b/amm-v2-docs/formula.md @@ -70,5 +70,40 @@ $$\Delta y = \frac{\Delta L}{L} * y_{0}$$ In case users want to zap out to Asset B, $\Delta x$ will be swapped, then total amount users receive is $$Out = \Delta y + \frac{(f_{d} - f_{n}) * \Delta x * y_{0}}{x_{0} * f_{d} + (f_{d} - f_{n}) * \Delta x}$$ -### 5. Withdraw Imbalance -TODO \ No newline at end of file +### 6. Withdraw Imbalance + +Users want to withdraw with a ratio $A/B$. + +We have the basic withdrawal formulas: + +$$\Delta x = \frac{\Delta L}{L} * x_{0}$$ +$$\Delta y = \frac{\Delta L}{L} * y_{0}$$ + +Suppose we need to swap some in $\Delta x$ to get $\frac{\Delta x'}{\Delta y'} = \frac{A}{B}$. + +So we have the formula: +$$\frac{\Delta x - swap_{x}}{\Delta y + receive_{y}} =\frac{A}{B} (1)$$ + + +$$ receive_{y} = \frac{(f_{d} - f_{n}) * swap_{x} * y_{0}}{x_{0} * f_{d} + (f_{d} - f_{n}) * swap_{x}}(2)$$ + +(With $x_{0}$ and $y_{0}$ being $x$ and $y$ after withdrawal, $swap_{x}$ is the amount need to be swapped to adapt the ratio $A/B$ that users expect). + +Combination of formula (1) and (2), we have: + +$$a * swap_{x} ^ 2 + b * swap_{x} + c = 0$$ +where +$$a = (f_{d} - f_{n}) * B$$ +$$b = A*(f_{d} - f_{n})*(y_{0}+\Delta y) + B *(f_{d} * x_{0} - (f_{d} - f_{n})*\Delta x)$$ +$$ c =f_{d} * x_{0} *(A * \Delta y - B * \Delta x) $$ + +### 7. Partial Swap +Allow users swap only if price is exactly matched. + +In case users want to swap with price $A/B$ +We have 2 formulas: +$$\frac{\Delta x}{\Delta y} = \frac{A}{B} (1)$$ +$$ \Delta y = \frac{(f_{d} - f_{n}) * \Delta x * y_{0}}{x_{0} * f_{d} + (f_{d} - f_{n}) * \Delta x} (2)$$ +We can calculate $\Delta x$: +$$\Delta x = \frac{A * (f_{d} - f_{n}) * y_{0} - B * f_{d} * x_{0}}{(f_{d} - f_{n}) * B}$$ +where $\Delta x$ is the maximum amount can be swapped to adapt $A/B$ ratio \ No newline at end of file diff --git a/lib/amm_dex_v2/math.ak b/lib/amm_dex_v2/math.ak index b258ef7..2ea4748 100644 --- a/lib/amm_dex_v2/math.ak +++ b/lib/amm_dex_v2/math.ak @@ -358,8 +358,8 @@ pub fn calculate_zap_out( // a * swap_amount_in ^ 2 + b * swap_amount_in + c = 0 // Where: // - a = fee_diff * expect_io_ratio_denominator -// - b = expect_io_ratio_numerator * fee_diff ( reserve_out + amount_out ) * expect_io_ratio_denominator * (fee_denominator * reserve_in - fee_diff * amount_in) -// - c = fee_denominator * (expect_io_ratio_numerator * amount_out - expect_io_ratio_denominator * amount_in) +// - b = expect_io_ratio_numerator * fee_diff ( reserve_out + amount_out ) + expect_io_ratio_denominator * (fee_denominator * reserve_in - fee_diff * amount_in) +// - c = fee_denominator * reserve_in* (expect_io_ratio_numerator * amount_out - expect_io_ratio_denominator * amount_in) fn calculate_withdraw_swap_amount( amount_in: Int, amount_out: Int,