---
# System prepended metadata

title: Uniswap v2 - Arbitrage
tags: [uniswap2, arbitrage, crypto]

---

# Uniswap V2 - Arbitrage

###### tags: `crypto`, `uniswap2`, `arbitrage`

> This document is a product of reaserch of Uniswap V2 crypto exchange protocol. The goal of the research is to provide ready to use formulas to be used in a crypto arbitrage application.

Arbitrage is a practice of taking advantage of the dfference between buy and sell prices of some asset, in paricular a crypto token.

The following terms are used in the document:

**Liquidity pair** (**LP**) - is a smart contract (a protocol) that allows to exchange some amount of asset `X` for some amount of asset `Y`. In scope of the document only Uniswap V2 protocol is taken into consideration.

**Swap** - is a procedure of singular exchange.

**Reserve** - is an amount of asset `X` secured in a protocol. Each protocl of Uniswap V2 has two reserves, one for each asset used in exchage. Exchange in scope of Uniswap V2 allowed in both directions.

<br>

## Definition of exchange

According to [source code of Uniswap V2](https://github.com/Uniswap/v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol#L43-L50), the dependency between an amount $x$ of token bought (by the protocol) and an amount $y$ of tokens sold during a swap is the following:

$$
y = \frac{997 r_y x}{1000r_x + 997x}
$$

Where $r_x$ and $r_y$ are reserves of token $X$ and $Y$ before the exchange. The coefficient `997` shows the protocol fee, which in case of Uniswap V2 is fixed (0.3%). In general, exchange equation is:

$$
y = \frac{qr_yx}{r_x + qx} \quad q = 1 - fee
$$

Where $fee$ is a fee in percents and $q$ is a value introduced for simplicity. The [graph](https://www.desmos.com/calculator/intgs5ozza) of this equation shows that function is a hyperbola asymptotically approaching $r_y$ as $x$ tends to infinity.

![](https://hackmd.io/_uploads/B178Xc0T3.png)

This dependency is a consequence of the protocol architecture, where an asset price is a product of reserves ratio. In general case, the ratio is the following:

$$
r_xr_y = k \quad\quad k - const
$$

Where $k$ is a constant value, set up by the owner of the protocol during it's initialization. In other words, the reference exchange ration is set acts as an equilibrium point with protocol raising the asset price after it's being sold.

<br>

Since the reserve ratio is a constant, the following shows the functional dependency between the amount of tokens being received by the protocol and the amount of tokens being released:

$$
(r_x + qx)(r_y - y) = r_xr_y
$$

The amount of tokens in general is a natural number, that so the signs of $+x$ and $-y$ shows the direction of the exchange, meaning that asset `X` was retreived and asset `Y` was released. It is worth mentioning that $q$ multiplier is applied to the amount of tokens received by the protocol, since the fee is held before the amount reaches the reserve.

<br>

## Margin

Based on arbitrage definition, the interest is based on the difference between buy and sell prices. Let's define the margin as a difference between the amount of token received $x'$ and the amount of token $x$ used to perform the exchange operations:

$$
\delta = x' - x
$$

According to the protocol principle, the positive margin is not possible if both operations are performed within the single protocol without third parties involved in the proccess (socalled "Sandwich attack"), which is out of scope of the current document. Herein it is assumed that the exchange operations are performed with two different protocols, where the second protocol with reserves $s_x$ and $s_y$ and exchange equation as:

$$
(s_x - x')(s_y + qy) = s_xs_y
$$

$y$ is the amount of assets received as the result of the exchange performed with the first protocol. Then the final amount of tokens `X` received is:

$$
x' = s_x - \frac{s_xs_y}{s_y + qy} = \frac{qs_xy}{s_y + qy}
$$

Using the exchange equation of the first protocol:

$$
y(x)=\frac{qr_yx}{r_x + qx} \quad
x'(y)=\frac{q^2s_xr_yx/(r_x + qx)}{s_y + q^2r_yx/(r_x + qx)}
$$

$$
x'(x)=\frac{q^2s_xr_yx}{s_yr_x + qs_yx + q^2r_yx}
$$

Turns the margin expression as the function of $x$:

$$
\delta(x)=x'-x=\frac{q^2s_xr_yx}{s_yr_x + qs_yx + q^2r_yx}-x
$$

Данная функция ([визуализация доступна здесь](https://www.desmos.com/calculator/jhriefsi1s)) является гиперболой асимптотически стремящейся к прямой $y=-x$. Функция принимает положительные значения на промежутке значений $x$ около начала координат, границы промежутка выражаются как:

The function ([visualization is available here](https://www.desmos.com/calculator/jhriefsi1s)) is a hyperbola that asymptotically approaching the line $y = -x$. The function has possitive values only in range of $x$ in the beggining of the axis with the following borders:

$$
x_1=0 \quad x_2=\frac{q^2s_xr_y-s_yr_x}{qs_y+q^2r_y}
$$

Those are solutions of the following equation:

$$
\delta(x)=\frac{q^2s_xr_yx}{s_yr_x + qs_yx + q^2r_yx}-x=0\\
q^2s_xr_yx-s_yr_xx-qs_yx^2-q^2r_yx^2=0\\
x(q^2s_xr_y-s_yr_x-qs_yx-q^2r_yx)=0\\
q^2s_xr_y-s_yr_x-qs_yx_2-q^2r_yx_2=0\quad
x_1=0\\
(qs_y+q^2r_y)x_2=q^2s_xr_y-s_yr_x\quad
x_1=0\\
x_2=\frac{q^2s_xr_y-s_yr_x}{qs_y+q^2r_y}\quad
x_1=0
$$

<br>
<br>

## Margin maximization

The margin curve at the range $[x_1, x_2]$ has a maximum at some value $x_{opt}$, which corresponds to the largest possible value of the margin when sequentially conducting buy transaction using the protocol with $r_x$ and $r_y$, and selling using the protocol with $s_x$ and $s_y$.

The coordinate $x_{opt}$ corresponds the the optimal amount of asset $X$ to be used to achieve the maximum marging and can be found as a point where the first derivative of margin function turns zero:

$$
\delta(x)=\frac{q^2s_xr_yx}{s_yr_x + qs_yx + q^2r_yx}-x
$$

Using the rule of differentiation of a division of functions:

$$
(f/g)'=(f'g-fg')/g^2
$$

And the derivative of the margin function is the following:

$$
\delta'(x)=\frac{q^2s_xr_y(s_yr_x + qs_yx + q^2r_yx)-q^2s_xr_yx(qs_y+q^2r_y)}{(s_yr_x + qs_yx + q^2r_yx)^2}-1\\
\delta'(x)=\frac{q^2s_xs_yr_xr_y + q^3s_xs_yr_yx + q^4s_xr_y^2x-q^3s_xs_yr_yx-q^4s_xr_y^2x}{(s_yr_x + qs_yx + q^2r_yx)^2}-1\\
\delta'(x)=\frac{q^2s_xs_yr_xr_y}{(s_yr_x + qs_yx + q^2r_yx)^2}-1
$$

The function $\delta(x)$ has a maximum value $\delta(x_{opt})$ in the point $x_{opt}$, where it's derivative turn zero:

$$
\delta'(x_{opt})=\frac{q^2s_xs_yr_xr_y}{(s_yr_x + qs_yx_{opt} + q^2r_yx_{opt})^2}-1=0\\
\frac{q^2s_xs_yr_xr_y-(s_yr_x + qs_yx_{opt} + q^2r_yx_{opt})^2}{(s_yr_x + qs_yx_{opt} + q^2r_yx_{opt})^2}=0\\
\frac{(qs_y+q^2r_y)^2x_{opt}^2+2s_yr_x(qs_y+q^2r_y)x_{opt}+s_y^2r_x^2-q^2s_xs_yr_xr_y}{(s_yr_x + qs_yx_{opt} + q^2r_yx_{opt})^2}=0\\
(qs_y+q^2r_y)^2x_{opt}^2+2s_yr_x(qs_y+q^2r_y)x_{opt}+s_y^2r_x^2-q^2s_xs_yr_xr_y=0\\
$$

Let's find solutions of the square equation:

$$
x_{1,2}=\frac{-b\pm\sqrt{b^2-4ac}}{2a}
$$

Where the coeffinients $a$,$b$ и $c$ are:

$$
a=(qs_y+q^2r_y)^2 \quad
b=2s_yr_x(qs_y+q^2r_y) \quad
c=s_y^2r_x^2-q^2s_xs_yr_xr_y
$$

$$
x_{1,2}=\frac{-2s_yr_x(qs_y+q^2r_y) \pm \sqrt{4s_y^2r_x^2(qs_y+q^2r_y)^2 - 4(qs_y+q^2r_y)^2(s_y^2r_x^2-q^2s_xs_yr_xr_y)}}{2(qs_y+q^2r_y)^2}\\
x_{1,2}=\frac{-s_yr_x \pm \sqrt{s_y^2r_x^2 - (s_y^2r_x^2-q^2s_xs_yr_xr_y)}}{qs_y+q^2r_y}\\
x_{1,2}=\frac{-s_yr_x \pm \sqrt{q^2s_xs_yr_xr_y}}{qs_y+q^2r_y}
$$

Considering that $x \in N$, the single solution is the following:

$$
x_{opt} = \frac{\sqrt{q^2s_xs_yr_xr_y}-s_yr_x}{qs_y+q^2r_y}
$$

Let's find the maximum value of margin:

$$
\delta(x_{opt})=\frac{q^2s_xr_yx_{opt}}{s_yr_x + q(s_y + qr_y)x_{opt}}-x_{opt}=\delta_{max}
$$

By substitutting $x_{opt}$ and simplifying:

$$
\frac{q^2s_xr_y(\sqrt{q^2s_xs_yr_xr_y}-s_yr_x)/(qs_y+q^2r_y)}{s_yr_x + q(s_y + qr_y)(\sqrt{q^2s_xs_yr_xr_y}-s_yr_x)/(qs_y+q^2r_y)}-\frac{\sqrt{q^2s_xs_yr_xr_y}-s_yr_x}{qs_y+q^2r_y}=\\
=\frac{q^2s_xr_y(\sqrt{q^2s_xs_yr_xr_y}-s_yr_x)/(qs_y+q^2r_y)}{s_yr_x+\sqrt{q^2s_xs_yr_xr_y}-s_yr_x}-\frac{\sqrt{q^2s_xs_yr_xr_y}-s_yr_x}{qs_y+q^2r_y}=\\
=\frac{q^2s_xr_y(\sqrt{q^2s_xs_yr_xr_y}-s_yr_x)}{(qs_y+q^2r_y)\sqrt{q^2s_xs_yr_xr_y}}-\frac{\sqrt{q^2s_xs_yr_xr_y}-s_yr_x}{qs_y+q^2r_y}=\\
=\frac{q^2s_xr_y(\sqrt{q^2s_xs_yr_xr_y}-s_yr_x)-(\sqrt{q^2s_xs_yr_xr_y}-s_yr_x)\sqrt{q^2s_xs_yr_xr_y}}{(qs_y+q^2r_y)\sqrt{q^2s_xs_yr_xr_y}}=\\
=\frac{
q^2s_xr_y\sqrt{q^2s_xs_yr_xr_y}
-q^2s_xs_yr_xr_y
-q^2s_xs_yr_xr_y
+s_yr_x\sqrt{q^2s_xs_yr_xr_y}
}{(qs_y+q^2r_y)\sqrt{q^2s_xs_yr_xr_y}}=\\
=\frac{
q^2s_xr_y\sqrt{q^2s_xs_yr_xr_y}
-2q^2s_xs_yr_xr_y
+s_yr_x\sqrt{q^2s_xs_yr_xr_y}
}{(qs_y+q^2r_y)\sqrt{q^2s_xs_yr_xr_y}}=\\
=\frac{q^2s_xr_y-2\sqrt{q^2s_xs_yr_xr_y}+s_yr_x}{qs_y+q^2r_y}
=\frac{(q\sqrt{s_xr_y}-\sqrt{s_yr_x})^2}{qs_y+q^2r_y}
$$

It becomes clear that the maximum value of margin in the range $[0,\frac{q^2s_xr_y-s_yr_x}{qs_y+q^2r_y}]$ is:

$$
\delta_{max}=\frac{(q\sqrt{s_xr_y}-\sqrt{s_yr_x})^2}{qs_y+q^2r_y}\quad
x_{opt}=\frac{\sqrt{s_yr_x}(q\sqrt{s_xr_y}-\sqrt{s_yr_x})}{qs_y+q^2r_y}
$$

The visualization is available [here](https://www.desmos.com/calculator/wqv4zulbui). It is obvious that the positive value of margin is only possible if the following inequality is true:

$$
\delta_{max} > 0 \quad \Longrightarrow \quad q^2s_xr_y > s_yr_x
$$

Up until this point only the single direction of operations were onsidered, which is $X \rightarrow Y \rightarrow X$. However, if the inequality from above is not true, it is worth checking other variants described below.

The amount of tokens $Y$ with amount of tokens $X$ being $x_{opt}$ is:

$$
y(x_{opt})=\frac{qr_yx_{opt}}{r_x + qx_{opt}}
=\frac{qr_y\sqrt{s_yr_x}(q\sqrt{s_xr_y}-\sqrt{s_yr_x})}{r_x(qs_y+q^2r_y)+q\sqrt{s_yr_x}(q\sqrt{s_xr_y}-\sqrt{s_yr_x})}
$$

<br>
<br>

### Variaty of operations

While performing the calculation from above, it might be usefull to also calculate the margin for the **backward** ($Y \rightarrow X \rightarrow Y$), **reverse** (the reverse order of calling protocols) and the **brackward-reverse** (both from above) operations.

First, let's consider the **backward** operation, where tokens are exhcaged in a way $Y \rightarrow X \rightarrow Y$. In this case, the reserve changes of the protocols are:

$$
(r_x - \bar{x})(r_y + q\bar{y}) = r_xr_y \\
(s_x + q\bar{x})(s_y - \bar{y'}) = r_xr_y
$$

From where:

$$
\bar{x}(y) = \frac{qr_x\bar{y}}{r_y + q\bar{y}} \\
\bar{y'}(y) = \frac{qs_y\bar{x}}{s_x+q\bar{x}} =
\frac{qs_y\frac{qr_x\bar{y}}{r_y + q\bar{y}}}{s_x+q\frac{qr_x\bar{y}}{r_y + q\bar{y}}}
=\frac{q^2s_yr_x\bar{y}}{s_xr_y+qs_x\bar{y}+q^2r_x\bar{y}}\\
\bar{\delta}(\bar{y}) = \frac{q^2s_yr_x\bar{y}}{s_xr_y+qs_x\bar{y}+q^2r_x\bar{y}} - \bar{y}
$$

Note that the expressions from above can be obtained by the simple variable substitution $x \Rightarrow \bar{y}$ и $y \Rightarrow \bar{x}$ for the according expressions for the direct operation:

$$
y(x)=\frac{qr_yx}{r_x + qx} \\
x'(x)=\frac{q^2s_xr_yx}{s_yr_x + qs_yx + q^2r_yx} \\
\delta(x)=\frac{q^2s_xr_yx}{s_yr_x + qs_yx + q^2r_yx}-x
$$

Then, this is how margin maximum value is expressed:

$$
\delta_{max}=\frac{(q\sqrt{s_xr_y}-\sqrt{s_yr_x})^2}{qs_y+q^2r_y} \quad \Rightarrow \quad
\bar{\delta}_{max} = \frac{(q\sqrt{s_yr_x}-\sqrt{s_xr_y})^2}{qs_x+q^2r_x}
\\
x_{opt}=\frac{\sqrt{s_yr_x}(q\sqrt{s_xr_y}-\sqrt{s_yr_x})}{qs_y+q^2r_y}
\quad \Rightarrow \quad
\bar{y}_{opt} = \frac{\sqrt{s_xr_y}(q\sqrt{s_yr_x} - \sqrt{s_xr_y})}{qs_x + q^2r_x}
$$

This margin can be positive only if:

$$
\bar{\delta}_{max} > 0 \quad q^2s_yr_x > s_xr_y
$$

Let's compare it with the direct operation:

$$
\delta_{max} > 0 \quad q^2s_xr_y > s_yr_x
$$

Since $r_x,r_y,s_x,x_y > 0$:

$$
q^2(s_yr_x + s_xr_y) > s_xr_y + s_yr_x \\
q^2 > \frac{s_xr_y + s_yr_x}{s_yr_x + s_xr_y} \quad q > 1
$$

This inequality shows that the positive margin is impossible after performing both direct and reverse operations.

Let's express inequalities using reserves relationships of the protocols:

$$
\delta_{max} > 0
\quad q^2s_xr_y > s_yr_x
\quad q^2s_x/r_x > s_y/r_y
\quad s_y/r_y < q^2s_x/r_x \\
\bar{\delta}_{max} > 0
\quad q^2s_yr_x > s_xr_y
\quad q^2s_y/r_y > s_x/r_x
\quad s_y/r_y > s_x/q^2r_x
$$

The inequalities from above can allow to make a decision regarding the direction of the operation based on only the knowledge of initial reserves of the both protocols.

<br>
<br>

Now, let's consider the operation, where the direction is direct, but the order of protocols is changed. In this case:

$$
(s_x + qx)(s_y - \tilde{y}) = s_xs_y \\
(r_x - q\tilde{x'})(r_y + q\tilde{y}) = r_xr_y \\
$$

Respectively:

$$
\tilde{y}(x) = qs_yx/(s_x + qx) \\
x'(x) = qr_x\tilde{y}/(r_y + q\tilde{y})=
\frac{q^2s_yr_xx/(s_x + qx)}{r_y + q^2s_yx/(s_x + qx)}=
\frac{q^2s_yr_xx}{s_xr_y + qr_yx + q^2s_yx}\\
\tilde{\delta}(x)=\frac{q^2s_yr_xx}{s_xr_y + qr_yx + q^2s_yx}-x
$$

Note that the equations from above can be obtained by substituting coefficients $r_x \Rightarrow s_x$, $r_y \Rightarrow s_y$, $s_x \Rightarrow r_x$ и $s_y \Rightarrow r_y$ of the according equations of the direct operation:

$$
y(x)=qr_yx(r_x + qx) \\
x'(x)=\frac{q^2s_xr_yx}{s_yr_x + qs_yx + q^2r_yx} \\
\delta(x)=\frac{q^2s_xr_yx}{s_yr_x + qs_yx + q^2r_yx}-x
$$

The expression of the margin maximum and the optimal input value are:

$$
\delta_{max}=\frac{(q\sqrt{s_xr_y}-\sqrt{s_yr_x})^2}{qs_y+q^2r_y} \quad \Rightarrow \quad
\tilde{\delta}_{max}=
\frac{(q\sqrt{s_yr_x}-\sqrt{s_xr_y})^2}{qr_y+q^2s_y}
\\
x_{opt}=\frac{\sqrt{s_yr_x}(q\sqrt{s_xr_y}-\sqrt{s_yr_x})}{qs_y+q^2r_y}
\quad \Rightarrow \quad
\tilde{x}_{opt}=
\frac{\sqrt{s_xr_y}(q\sqrt{s_yr_x}-\sqrt{s_xr_y})}{qr_y+q^2s_y}
$$

Let's rate the equations:

$$
\delta_{max} > 0
\quad q^2s_xr_y > s_yr_x
\quad s_y/r_y < q^2s_x/r_x \\
\tilde{\delta}_{max} > 0
\quad q^2s_yr_x > s_xr_y
\quad s_y/r_y > s_x/q^2r_x \\
\bar{\delta}_{max} > 0
\quad q^2s_yr_x > s_xr_y
\quad s_y/r_y > s_x/q^2r_x
$$

Note that conditions for the reverse operation and backward operation are the same. Let's compare margins:

$$
q^2s_yr_x > s_xr_y \quad
\bar{\delta}_{max} / \tilde{\delta}_{max}
= \frac{r_y+qs_y}{s_x+qr_x}
$$

<br>
<br>

Finally, let's consider the brackward-reverse operation:

$$
(s_x - \bar{\tilde{x}})(s_y + q\tilde{y}) = s_xs_y \\
(r_x + q\bar{\tilde{x}})(r_y - \tilde{y}') = r_xr_y
$$

$$
\bar{\tilde{x}} = qs_x\tilde{y} / (s_y + q\tilde{y}) \\
\tilde{y}' = qr_y\bar{\tilde{x}} / (r_x + q\bar{\tilde{x}})
= \frac{q^2s_xr_y\tilde{y}}{s_yr_x + qr_x\tilde{y} + q^2s_x\tilde{y}} \\
\bar{\tilde{\delta}}(\tilde{y}) =
\frac{q^2s_xr_y\tilde{y}}{s_yr_x + qr_x\tilde{y} + q^2s_x\tilde{y}} - \tilde{y}
$$

Note that the expression of $\bar{\tilde{\delta}}(\tilde{y})$ can be obtained from $\bar{\delta}(\bar{y})$ with the following substitutions:

$$
\bar{\delta}(\bar{y}) = \frac{q^2s_yr_x\bar{y}}{s_xr_y+qs_x\bar{y}+q^2r_x\bar{y}} - \bar{y}
\quad \bar{y} \Rightarrow \tilde{y} \\
r_x \Rightarrow s_x \quad r_y \Rightarrow s_y \\
s_x \Rightarrow r_x \quad s_y \Rightarrow r_y
$$

Then:

$$
\bar{\delta}_{max} =
\frac{(q\sqrt{s_yr_x}-\sqrt{s_xr_y})^2}{qs_x+q^2r_x}
\quad \Rightarrow \quad
\bar{\tilde{\delta}}_{max} = 
\frac{(q\sqrt{s_xr_y} - \sqrt{s_yr_x})^2}{qr_x+q^2s_x}
\\
\bar{y}_{opt} = \frac{\sqrt{s_xr_y}(q\sqrt{s_yr_x} - \sqrt{s_xr_y})}{qs_x + q^2r_x}
\quad \Rightarrow \quad
\bar{\tilde{y}}_{opt} = \frac{\sqrt{s_yr_x}(q\sqrt{s_xr_y} - \sqrt{s_yr_x})}{qr_x + q^2s_x}
$$

The following are all conditions for all types of operations combined:

$$
\delta_{max} > 0
\quad q^2s_xr_y > s_yr_x
\quad s_y/r_y < q^2s_x/r_x \\
\tilde{\delta}_{max} > 0
\quad q^2s_yr_x > s_xr_y
\quad s_y/r_y > s_x/q^2r_x \\
\bar{\delta}_{max} > 0
\quad q^2s_yr_x > s_xr_y
\quad s_y/r_y > s_x/q^2r_x \\
\bar{\tilde{\delta}}_{max} > 0
\quad q^2s_xr_y > s_yr_x
\quad s_y/r_y < q^2s_x/r_x
$$

$$
q^2s_yr_x > s_xr_y \quad
\bar{\delta}_{max} / \tilde{\delta}_{max}
= \frac{r_y+qs_y}{s_x+qr_x} \\
q^2s_x/r_x > s_y/r_y
\quad
\delta_{max} / \bar{\tilde{\delta}}_{max} =
\frac{r_x+qs_x}{s_y+qr_y}
$$

<br>
<br>

## Algorithm of performing an arbitrage (direct).

The following is the algorithm of arbitrage, the pair `WETH` `USDC` is used as the example.

1. Get reserves of the protocols:

```
q = 0.997
r00 - WETH reserve of the first protocol
r01 - USDC reserve of the first protocol
r10 - WETH reserve of the first protocol
r11 - USDC reserve of the first protocol
```

2. Rate the margin:

```
a = q * sqrt(r10 * r01)
b =     sqrt(r11 * r00)

if (a <= b) // positive margin is impossible, cancel
```

3. Compute the inputs:

```
с = q * (r11 + q * r01)

in1 = b * (a - b) / с                  // amount in for the first protocol
in2 = q * r01 * in1 / (r00 + q * in1)  // amount in for the second protocol
```

4. Compute the margin:

```
margin = (a - b)^2 / c
```

<br>
<br>

## The extended algorithm.

The following is the extended algorithm, which not only allows to perform the operation, but also allows to choose the type of the operation (the order of protocols, the tokens to be inputed and the input values) by the `WETH` `USDC` pair as the example:

1. Get reserves of protocols:

```
q = 0.997
r00 - WETH reserve of the first protocol
r01 - USDC reserve of the first protocol
r10 - WETH reserve of the first protocol
r11 - USDC reserve of the first protocol
```

2. Pre-rate and selection of the operation type:

```
if (q^2 * r10 * r00 > r11 * r00) {
  // backward or reverse operations are possible
  const a = q * sqrt(r11 * r00)
  const b =     sqrt(r10 * r01)
  
  if (r01 + q * r11 > r10 + q * r00) {
    // backward operation
    const c = q * (r10 + q * r00)
    
    // amount of USDC in for the first protocol
    const y = b * (a - b) / c
    
    // amount of WETH in for the second protocol
    const x = q * r00 * y / (r01 + q)
    
    // margin in USDC
    const margin = (a - b)^2 / c
    
  } else {
    // reverse operation
    const c = q * (r01 + q * r11)
    
    // amount of WETH in for the second protocol
    const x = b * (a - b) / c
    
    // amount of USDC in for the first protocol
    const y = q * r11 * x / (r10 + q * x)
    
    // margin in WETH
    const margin = (a - b)^2 / c
  }

} else if (q^2 * r11 * r00 > r10 * r01) {
  // Forward or backward-reverse operations are possible
  const a = q * sqrt(r10 * r01)
  const b =     sqrt(r11 * r00)
    
  if (r00 + q * r10 > r11 + q * r01) {
    // forward
    const c = q * (r11 + q ^ r01)

    // amount of WETH in for the first protocol
    const x = b * (a - b) / с   
    
    // amount of USDC in for the second protocol
    const y = q * r01 * x / (r00 + q * x)  
    
    // margin in WETH
    const margin = (a - b)^2 / c
  } else {
   // backward
   const c = q * (r00 + q ^ r10)
   
   // amount of USDC in for the second protocol
   const y = b * (a - b)^2 / c
   
   // amount of WETH in for the first protocol
   const x = q * r10 * y / (r11 + q * y)
   
   // margin in USDC
   const margin = (a - b)^2 / c
  }
  
}
```

<br>
<br>
<br>
<br>
