# Lowest slippage swap

Our protocol implements an algorithm that can reach the lowest slippage during token swap in Uniswap V2 like DEX. Just like 1inch, our algorithm supports all major protocols in Polygon, including QuickSwap, SushiSwap, Dfyn, Kyber DMM, WaultSwap, JetSwap, and more.

### Swap Exact Tokens for Tokens in lowest slippage

Suppose that you want to swap exact $$s$$USDC to WETH through several Uniswap V2 like DEX using only USDC-WETH LP. In 1inch, they will split the swap across all supported DEX. Our algorithm does a similar thing.

For Uniswap V2 like DEX, the swap can be described as the following function

$$
g_i(x)=\frac{x_i\cdot f_i \cdot a_i}{b_i+x\cdot f_i}
$$

where

* &#x20;$$x_i$$is the input USDC amount to the $$i$$-th DEX
* $$f_i$$is the swap fee for the $$i$$-th DEX
* $$a_i$$is the WETH reserve in the $$i$$-th DEX
* $$b_i$$is the USDC reserve in the $$i$$-th DEX
* $$g_i(x_i)$$is the output WETH amount

We need to optimize the following function

$$
\begin{array}{c}
\text{maximize} \sum_i g_i(x_i)   \\
\text{subject to:} \sum_i x_i = s
\end{array}
$$

Using the [**method of Lagrange multipliers**](https://en.wikipedia.org/wiki/Lagrange_multiplier)**,** we can find the optimal solution for $$x_i$$

$$
\begin{eqnarray}
\lambda &=& \frac{s+\sum_i \frac{b_i}{f_i}}{\sum_i \sqrt{\frac{a_i \cdot b_i}{f_i}}} \\
x_i &=& \sqrt{\frac{a_i\cdot b_i}{f_i}}\cdot \lambda-\frac{b_i}{f_i}
\end{eqnarray}
$$

### Swap Tokens for Exact Tokens in lowest slippage

Suppose that you want to swap some USDC to get exact $$s$$WETH through several Uniswap V2 like DEX using only USDC-WETH LP.

For Uniswap V2 like DEX, the swap can be described as the following function

$$
g_i(y_i)=\frac{b_i\cdot y_i}{(a_i-y_i)\cdot f_i}+1
$$

where‌

* &#x20;​$$y_i$$ is the output WETH amount to get from the ​$$i$$-th DEX
* ​​$$f_i$$ ​is the swap fee for the ​$$i$$-th DEX
* ​​$$a_i$$ ​is the WETH reserve in the ​$$i$$-th DEX
* ​​$$b_i$$ is the USDC reserve in the ​$$i$$-th DEX
* $$g_i(y_i)$$is the minimum input USDC amount needed

We need to optimize the following function

$$
\begin{array}{c}
\text{minimize} \sum_i f_i(y_i)   \\
\text{subject to:} \sum_i y_i = s
\end{array}
$$

Again, using the [**method of Lagrange multipliers**](https://en.wikipedia.org/wiki/Lagrange_multiplier)**,** we can find the optimal solution for $$y_i$$

$$
\begin{eqnarray}
\lambda &=& \frac{\sum_i a_i-s}{\sum_i \sqrt{\frac{a_i \cdot b_i}{f_i}}} \\
y_i &=& a_i - \sqrt{\frac{a_i \cdot b_i}{f_i}} \cdot \lambda
\end{eqnarray}
$$

