
Identify the basic trading price through high frequency Oracle feed;

Based on the oracle price, adjust the trading price to keep LP's reserve in the close proximity to its original status.
1. Basic Price Identification
Staple uses Redstone's ondemand oracle price feed as the basic price indicator for a token.
Aside from its decentralized and robust price feeding infrastructure, Redstone's high price refresh rate (10 sec) ensures that only a rather limited gap, if any, needs to be closed between the oracle price and the market price.
The arbitraging activities from the oracle price to the market price might lead to small loss in LP's assets. Hence, by limiting the arbitrage space through high frequency oracle price feeding, Staple mitigates the impact on LP's profit.
2. Logic Behind the Design of the Curve
To prevent impermanent loss, we have replaced the LP reserve ratio with a highfrequency oracle for determining the trading price. However, any transactions executed in a liquidity pool can still result in a deviation of the LP token's reserve in the pool from its original status, potentially causing a loss to the overall assets in the liquidity pool.
To maintain assets in a liquidity pool as close as possible to their original quantities after a series of transactions, we have defined a price adjustment curve that introduces a price deviation in relation to the token reserve's deviation in the pool from its initial state.
The price deviation encourages arbitrageurs to trade in a way that brings the LP tokens in the pool back to their original status.
To elaborate on the price adjustment curve, we assume a twotoken liquidity pool with $token_0$ and $token_1$, and define the following parameters:

Liability of a liquidity token
The net supply of the token in the liquidity pool.

Asset of a liquidity token
The reserve of the token in the liquidity pool following sequences of transactions.

$L_0$
The amount of liability of $token_0$.

$L_1$
The amount of liability of $token_1$.

$A_0$
The amount of asset of $token_0$.

$A_1$
The amount of asset of $token_1$.

$ALR_0 = \frac{A_0}{L_0}$
The asset liability ratio of $token_0$.

$ALR_1 = \frac{A_1}{L_1}$
The asset liability ratio of $token_1$.

$OP_0$
The oracle price of $token_0$.

$OP_1$
The oracle price of $token_1$.
With the parameters defined above, the objective of the price adjustment curve is to maintain both $ALR_0$ and $ALR_1$ close to or above 1. Consequently, the curve should be designed in such a way that any negative deviation from $ALR_0 = 1$ or $ALR_1 = 1$ results in a price deviation from the oracle. This creates an arbitrage opportunity that incentivizes traders to trade towards the direction of $ALR_0 = 1$ and $ALR_1 = 1$.
To account for both $ALR_0$ and $ALR_1$ in the price adjustment curve, we define the following parameters:

$r_{ alr } = r_{ alr_0 } = \frac{ ALR_0 }{ ALR_1 }$
The ratio of the asset liability ratios: $token_0$ to $token_1$.

$r_{ alr_1 } = \frac{ ALR_1 }{ ALR_0 } = \frac{1}{ r_{alr} }$
The ratio of the asset liability ratios: $token_1$ to $token_0$.
And design the curve to encourage traders to trade towards the direction of $r_{alr} = 1$. Now, the issue arises when $r_{alr}$ is approaching 1: will $ALR_0$ and $ALR_1$ also approach 1 or remain above 1? There are three potential scenarios when $r_{alr}$ is approaching 1:

 When $ALR_0$ and $ALR_1$ are on different sides of 1.

 When both $ALR_0$ and $ALR_1$ are $> 1$.

 When both $ALR_0$ and $ALR_1$ are $< 1$.
Case 1
When $r_{alr}$ is approaching 1, both $ALR_0$ and $ALR_1$ must be approaching 1 as well, but from different sides of 1.
Case 2
Both $token_0$ and $token_1$ have more assets than liabilities in the pool, ensuring liquidity for withdrawals. As $r_{alr}$ approaches 1, the two tokens become more balanced in terms of the assetliability ratio.
Case 3
When $r_{alr}$ approaches 1, it suggests a balanced assetliability ratio between $ALR_0$ and $ALR_1$, but it does not necessarily bring $ALR_0$ and $ALR_1$ back to 1. Case 3 indicates that LPs' assets for both $token_0$ and $token_1$ have decreased following a series of transactions.
The only transaction pattern that could potentially result in a drop in the $ALR$ for both tokens is when the transactions in the pool consistently coincide with a decrease in the price of the purchased token (compared to the previous transaction).
In such situations, a trader needs to deposit less $token_0$ into the liquidity pool and withdraw a larger amount of $token_1$ compared to the scenario where the trading rate was higher. Consequently, the increase in $ALR_0$ cannot compensate for the decrease in $ALR_1$. When this transaction pattern occurs frequently for both tokens, it could lead to a drop in the $ALR$ for both tokens.
This could be understood with an example. Suppose we have $10000 \ token_0$ and $10000 \ token_1$ in the liquidity pool and their starting trading rate is $1:1$. In the first transaction, a trader trades $1000 \ token_0$ for $1000 \ token_1$, bringing the pool to a new status: $11000 \ token_0$ and $9000 \ token_1$. In the next transaction, a trader wants to trade $600 \ token_1$ for $token_0$. At the same time, the trading rate of $token_0$ to $token_1$ drops to $2:1$. Then with $600 \ token_1$, the trader could receive $1200 \ token_0$, leading the pool to $9800 \ token_0$ and $9600 \ token_1$, where $ALR$ for both tokens drops below $1$.
The above analysis demonstrates that pushing $r_{alr}$ toward 1 serves the purpose of moving $ALR_0$ and $ALR_1$ toward 1 or keeping both above 1 in the first two scenarios, but fails to achieve the same objective in case 3. However, it is unlikely that a liquidity pool in Staple will remain in the state of case 3 for an extended period for the following reasons:

Theoretically, there is only a 33% chance that the assets to be purchased happen to experience a price drop, the impact of which on $ALR_0$ and $ALR_1$ could be canceled out by transactions where the purchased token increases in price.

Any transaction that moves $r_{alr}$ away from the center (1) will immediately create an arbitrage opportunity through the price adjustment curve. Most likely, arbitrage bots will trade $r_{alr}$ back to 1 before the oracle price is refreshed, which, once again, cancels out the $ALR$ drop resulting from the transaction coinciding with a price drop in the purchased token.

Depending on the size of a transaction, the price adjustment curve imposes varying levels of price impact or slippage on the trader. All these price impacts and slippages contribute to the LP assets, subsequently affecting the $ALR$ of the token. This further reduces the likelihood that $ALRs$ for both tokens will remain below 1.
From the above, we can see that in most cases, $r_{alr} = 1$ serves the purpose of keeping $ALR_0$ and $ALR_1$ close to or above 1. Therefore, we use $r_{alr}$ as the $X$ axis of the price adjustment curve and the price adjustment factor (for the oracle price) as the $Y$ axis.
3. Requirements for the Price Adjustment Curve
Now we understand that the curve is designed to establish a relationship between the price adjustment factor on the oracle price ($Y$ axis) and the imbalance in the assetliability ratio of the two liquidity tokens $r_{alr}$ ($X$ axis), motivating traders to trade toward $r_{alr} = 1$. To be specific, given an oracle price, the trading rate of a transaction is derived as follows:

Acquire oracle rate for this transaction;

Calculate the current adjustment factor through the price adjustment
curve based on current $r_{alr}$; 
Calculate starting trading rate = oracle rate * adjustment factor;

Determine where the intended transaction volume will shift $r_{alr}$ on the adjustment curve to calculate the end trading rate;

Calculate the average trading price for this transaction based on
the starting rate and end rate.
To simplify the mathematical expression for this, let's define the following symbols:

$P_{o} = P_{ o_0 } = \frac{ OP_0 }{ OP_1 }$
The price calculated from oracle prices: $token_0$ to $token_1$.

$P_{ o_1 } = \frac{ OP_1 }{ OP_0 } = \frac{1}{ P_{o} }$
The price calculated from oracle prices: $token_1$ to $token_0$.

$P_{as} = P_{ as_0 }$
The adjusted starting price from $token_0$ to $token_1$ before a transaction takes place.
Oracle price adjusted by the current $r_{alr}$.

$P_{ as_1 } = \frac{1}{P_{ as_0 }}$
The adjusted starting price from $token_1$ to $token_0$ before a transaction takes place.
Oracle price adjusted by the current $r_{alr}$. 
$P_{ae} = P_{ ae_0 }$
The adjusted end price from $token_0$ to $token_1$ when a transaction is finished.
Before the transaction, we are at a point on the $X$ axis of the price adjustment curve represented by $r_{alr}$. The transaction's volume and direction shift the $r_{alr}$ to a new point that corresponds to a new price adjustment factor on the price adjustment curve. This new price adjustment factor drives the trading price from $P_{as}$ to $P_{ae}$.

$P_{ ae_1 } = \frac{1}{ P_{ ae_0 } }$
The adjusted end price from $token_1$ to $token_0$ when a transaction is finished.

$P_{ av } = P_{ av_0 }$
$P_{ae}$ is not the trading price for this transaction; it represents the adjusted end trading price of this transaction and is also the adjusted starting trading price for the next transaction, assuming that the oracle price remains unchanged for the next transaction.
The actual trading price of this transaction from $token_0$ to $token_1$, $P_{av_0}$, is the weighted average between $P_{as_0}$ and $P_{ae_0}$.

$P_{ av_1 } = \frac{1}{ P_{ av_0 } }$
The trading price of a transaction from $token_1$ to $token_0$.

$G(r_{alr})$
The price adjustment function generates the price adjustment factor with the ratio of asset liability ratios as the input.
With the above definition, we could easily arrive at the following equations:
$P_{ as } = P_{ as_0 } = P_o * G( r_{alr} ) \tag{1}$
$P_{ as_1 } = P_{ o_1 } * G(r_{ alr_1 }) \tag{2}$
The equations simply state that the adjusted starting price of a transaction is the product of the oracle price and the price adjustment function. This relationship holds for any point on the $G(r_{alr})$ curve and for both trading directions. If we disregard transaction fees, which is necessary for mathematical rigor when selecting the price adjustment curve, the following requirement must be satisfied for any point on the price adjustment curve:
$P_{ as } * P_{ as_1 } = 1 \tag{3}$
If we replace $P_{ as }$ and $P_{ as_1 }$ in equation $(3)$ with equation $(1)$ and equation $(2)$, respectively, we get the following equation:
$G( r_{alr} ) * G( {r_{alr} } ^ {1} ) = 1 \tag{4}$
The equation indicates that the price adjustment curve must meet the following requirement: When two $r_{alr}$s are reciprocals, their corresponding $G( r_{alr} )$s must also be reciprocals.
In summary, 5 conditions must be satisfied for $G( r_{alr} )$ to operate as a proper price adjustment function:

$G( r_{ alr } ) * G( { r_{alr} } ^ {1}) = 1$

$G( r_{ alr } )$ must be monotonically decreasing to ensure the price adjustment and the ratio of assetliability deviation for the trading direction always grows in the opposite direction;

To allow the low slippage for the trading, $G(r_{ alr })$ must have an extremely low negative slope near the starting point where $r_{ alr }$ is in the close proximity of 1;

To create a large price adjustment factor that encourage the traders to push $r_{ alr }$ back to the proximity of 1, $G(r_{ alr })$ must have a steep negative slope where $r_{ alr }$ is away from 1;

$G(r_{ alr })$ has the computational complexity that an EVM could handle or can be approximated by simpler calculations that an EVM could handle with sufficient accuracy.
To that end, we designed a 3segment curve for Staple's $G( r_{ alr } )$, where

The first segment aims at low slippage trading and should meet the condition 1, 2, 3, 5 in the above list and;

The second and third segment are intended to keep $r_{ alr }$ in the close proximity of 1 from 2 directions, respectively and should both meet the condition 1, 2, 4, 5 in the above list.
4. The 3segment Price Adjustment Curve
4.1 First Segment
The first segment of $G(r_{alr})$ is defined as follows:
$G( r_{alr} ) = r_{ alr } ^ {  \frac{1}{n}} \tag{5}$
The $n$ here is a creatordefined parameter, representing $r_{alr}$'s sensitivity to the difference between the market price and the oracle price, assuming that the trading price reflects the market price.
$G( r_{alr} ) = r_{ alr }^{\frac{1}{n}} = (1+ (r_{ alr }  1)) ^ {  \frac{1}{n}} \approx 1  \frac{1}{n} * (r_{ alr }  1)$
$r_{ alr } \approx 1 + n * (1  G( r_{alr} ))$
Therefore, the larger $n$ is, the more sensitive $r_{ alr }$ is.
Function $(5)$ is visualized as the dotted blue curve in the graph, where $r_{ alr }$ is the X axis and G is the Y axis. The black curve in this graph is the price adjustment curve, whose 1st segment that overlaps with the blue curve is a smooth monotonically decreasing curve that facilitates lowslippage trading in the proximity of $r_{ alr } = 1$ while also encouraging $r_{ alr }$ to stay close to 1. The other 2 segments of the curve are explained in the next section.
Note that in the black price adjustment curve, we assume a transaction from $token_0$ to $token_1$, and depict the price adjustment factor for trading in that direction.
The curve satisfies:

$G(r_{ alr } ^ {1}) = G( r_{alr} ) ^ {1}$
Proof:
$G(r_{ alr } ^ {1}) = (r_{ alr } ^ {1}) ^ {  \frac{1}{n}} = ( r_{ alr } ^ {  \frac{1}{n}} ) ^ {1} = G(r_{ alr }) ^ {1}$ 
Monotonically decreasing.
As seen in the graph, $G(r_{ alr })$ always decreases when $r_{ alr }$ increases. 
Low slope near $r_{ alr } = 1$.

$r_{ alr } ^ {  \frac{1}{n}}$ could be approximated with polynomials, whose computational complexity is within the capacity of EVM.
4.2 Second Segment
The 2nd segment of $G(r_{alr})$ is designed to push the $r_{alr}$ back to the first segment if the $r_{alr}$ moves beyond a certain range to the right of 1. In this case, a large price should of penalty be generated, e.g. price adjustment factor << 1, that discourages the trade in this direction. The function below describes this segment of the curve. See the black steep curve to the right of the black smooth curve in the graph, where $r_{ alr }$ is the X axis and $G(r_{alr})$ is the Y axis.
$G(r_{ alr }) = r_{ alr } ^ {  \frac{1}{n}} * [\frac{1}{ 1 + \frac{r_{ alr }}{m} \frac{m}{ r_{alr}}}]^2 \tag{6}$
where $m = 1 + p$, and p is a user (trading pair creator) defined parameter of the curve that denotes the threshoof penalty ld of $r_{alr}$ where segment 1 and segment 2 interfaces.
4.3 Third Segment
The third segment is the mirror of segment 2 to the left of segment 1. Its mathematical expression is also identical except for the change of direction and the shift in X:
$G(r_{ alr }) = r_{ alr } ^ {  \frac{1}{n}} * [2  \frac{1}{1 + \frac{1}{m * r_{ alr } }  m* r_{alr}}] ^ 2 \tag{7}$
，where $m = 1 + p$, the same as they are defined in segment 2.
In this case, if $r_{alr}$ is significantly smaller than 1, then the 3rd segment of the curve should generate a large transaction reward in price, e.g., price adjustment factor >> 1, that encourages the trade in this direction. See the black steep curve to the left of black smooth curve in the graph.
4.4 The Complete Price Adjustment Curve:
$y = \begin{cases} x ^ {  \frac{1}{n}} * [2  \frac{1}{1+\frac{1}{xm}  xm}] ^ {2}, & x < \frac{1}{m} \\ x ^ {  \frac{1}{n}}, & \frac{1}{m} \leqslant x \leqslant m \\ x ^ {  \frac{1}{n}} * [ \frac{1}{1 + \frac{x}{m}  \frac{m}{x}}] ^ 2, & x > m \\ \end{cases}$

When $\frac{1}{m} \leqslant x \leqslant m$:

users swap around $P_o$, no extra price should of penalty be imposed;

function $x ^ {\frac{1}{n}}$ generates a rather flat price adjustment curve, resulting in a swap price $P_{ av_{ in } }$ with limited slippage


When $x > m$:
$r_{alr_{in}}$ always increases during a swap.
Therefore, when a transaction pushed $r_{ alr_{ in } }$ out of the acceptable range, the VTP is moved to a unhealthy condition. Extra price penalty need to be charged.
The amount of penalty is $D_{out} * [1  \frac{1}{1 + \frac{x}{m}  \frac{m}{x}}]$ (see equation 32).

When $x < \frac{1}{m}$:
It means that the starting condition of the pool is very bad and this swap is pushing the $r_{alr_{in}}$ to recover.User will receive incentive for doing this swap. And the amount is $D_{out} * [1  \frac{1}{1 + \frac{1}{xm}  xm}]$ see equation 33.
5. RRS and RAS
5.1 RRS
It is explained in Fees for Liquidity Allocation & Deallocation that any (de)allocation action is charged for small fees to prevent the arbitrage that impacts LP's assets. However, when $r_{alr}$ approaches the 2nd/3rd segment of the price adjustment curve, the $G(r_{alr})$ could rise to the point where (de)allocation fee becomes unacceptably high for LPs.
To remedy this, we define a new parameter "reasonable $r_{alr}$ shift" ($RRS$), which indicates the healthy $r_{alr}$ range in which transactions are encouraged to take place. Within this range, (de)allocation fees are charged to LPs. Once transactions shift $r_{alr}$ beyond $RRS$, a price penalty is imposed on the transactions, and LPs are freed from (de)allocation fees.
This way we keep the (de)allocation fee within the reasonable range while restraining the harmful arbitrage as described in Fees for Liquidity Allocation & Deallocation. A balance should be found between the pool liquidity utilization and the limitation in the LP's (de)allocation fee when the value of $RRS$ is to be defined. The typical range of the $RRS$ is 6%  9%.
The price penalty is imposed on top of the 3segment price adjustment curve, thus adding extra logic to the price calculation.
5.2 RAS
To ease the calculation of fees and price penalties, we define another parameter $RAS$ as the reasonable asset shift of a token in a trading pair from the starting point where $r_{alr} = 1$. $RAS$ of a token is its maximal asset shift needed to reach the $RRS$ in a trading pair.
$RAS$ is derived from $RRS$ as follows:
Assume a trader swaps $D$ amount of $token_0$ to $token_1$. $RAS$ is the maximal $D$ needed to reach the $RRS$ in a trading pair. Therefore, to express $RAS$ in terms of $RRS$, we need to express $max\{D\}$ in $RRS$. To that end, we use the swap price $P_{ av_0 }(D)$, which is a function of $D$.
$\frac{r_{ alr_0 }'}{r_{ alr_0 }} = \frac{1 + D / L_0}{ 1  D * P_{ av_0}(D) / L_1} \geqslant 1+D / L_0 + D * P_{ av_0 }(D) / L_1 \tag{8}$
$RRS \geqslant \frac{r_{ alr_0 }'}{r_{ alr_0 }}1 \tag{9}$
Combining equation (8) and equation (9), we get:
$RRS \geqslant D / L_0 + D * P_{ av_0 }(D) / L_1 \tag{10}$
Equation (10) can be transformed to the expression below:
$D \leqslant \frac{RRS}{\frac{1}{L_0} + \frac{ P_{ av_0 }(D)}{ L_1 }} = \frac{RRS}{ \frac{1}{ L_0 } + \frac{ P_a * (\frac{ P_a' }{ P_a }) ^ {\frac{1}{2}}}{L_1}} \leqslant \frac{RRS}{ \frac{1}{L_0} + \frac{ P_a * (1  RRS / (2n))}{L_1}}$
Since $RAS$ is the maximal $D$ needed for $r_{alr}$ to reach $RRS$, we can arrive at the following equation, which expresses $RAS$ in $RRS$.
$RAS = RAS_0 = \frac{RRS}{\frac{1}{ L_0 } + \frac{ P_a * ( 1  RRS / (2n))}{ L_1 }} \tag{11}$
5.3 Price Penalty When $r_{alr}$ Moves Beyond RAS
In graph 5.1, we explained that price penalty is imposed to replace (de)allocation fees when $r_{alr}$ is not within $RRS$, in order to discourage the detrimental arbitrages discussed in Fees for Liquidity Allocation & Deallocation. It's easy to understand that the price penalty should be set to the maximal arbitrage profit.
Therefore, the same calculation for the (de)allocation fees in Fees for Liquidity Allocation & Deallocation applies here for the price penalty.
As seen in Fees for Liquidity Allocation & Deallocation, there are 4 harmful (de)allocation patterns after a swap from $token_0$ to $token_1$:

$ALR_0 > 1$, deallocate $token_0$

$ALR_0 < 1$, allocate $token_0$

$ALR_1 > 1$, allocate $token_1$

$ALR_1 < 1$, deallocate $token_1$
Following a swap from $token_0$ to $token_1$, a detrimental arbitrage could be realized by (de)allocating either $token_0$ or $token_1$. If both tokens are (de)allocated in 2 consecutive transactions and both contribute to the growth of $r_{alr}$, then the arbitrage profits are gained from both (de)allocation actions. Therefore, the price penalty for a transaction that ended up with $r_{alr}$ beyond $RAS$ should encompass the potential arbitrage profits from the (de)allocation of both tokens. Depending on the $ALR$ of $token_0$ and $token_1$, the price penalty of each token is expressed as follows.(Note that all the price penalty is expressed in the amount of token pertinent to the calculation):
5.3.1. $ALR_0' > 1$ (for potential $token_0$ deallocation)
$M1 \leqslant \frac{1}{n} * D * ( A_0'  L_0' ) / A_0' / ( L_0'  D )$
$M1 \leqslant \frac{1}{n} * (A_0 + y  L_0 ) / ( A_0 + y )$
$Penalty = y * \frac{1}{n} * ( A_0 + y  L_0 ) / ( A_0 + y ) \tag{12}$
5.3.2. $ALR_0' < 1$ (for potential $token_0$ allocation)
$M1 \leqslant \frac{1}{n} * D * ( L_0  A_0 ) / A_0 / ( L_0 + D )$
$M1 \leqslant \frac{1}{n} * ( L_0  A_0 ) / A_0$
$Penalty = y * \frac{1}{n} * ( L_0  A_0 ) / A_0 \tag{13}$
5.3.3. $ALR_1' > 1$ (for potential $token_1$ allocation)
$M1 \leqslant \frac{1}{n} * D * ( A_1  L_1 ) / L_1 / ( A_1 + D )$
$M1 \leqslant \frac{1}{n} * ( A_1  L_1 ) / L_1$
$Penalty = y' * \frac{1}{n} * ( A_1  L_1 ) / L_1 \tag{14}$
5.3.4. $ALR_1' < 1$ (for potential $token_1$ deallocation)
$M1 \leqslant \frac{1}{n} * D * ( L_1'  A_1' ) / L_1' / ( A_1'  D )$
$M1 \leqslant \frac{1}{n} * ( L_1  A_1 + y * P_{ av_0 } ) / L_1$
$Penalty = y' * \frac{1}{n} * ( L_1  A_1 + y' ) / L_1 \tag{15}$
where $M = P_{ av_0 } * P_{ av_1 }' = P_{ av_0 } * P_{ av_0 }'^{ 1 }$ (see Fees for Liquidity Allocation & Deallocation), $y'$ is the amount $token_1$ gained from the swap after the price penalty has been imposed on the $token_0$.
The price penalty of a transaction consists of the combination of the penalty for $token_0$ and the penalty for $token_1$, each from 1 of the 2 $ALR$ cases set forth above.
5.4 Visualization of Price Penalty When $r_{alr}$ Moves Beyond RAS
The price penalty for the 4 (de)allocaiton patterns when $r_{alr}$ is out of the $RAS$ are visualized in graph. On top of the parameters defined above, the following parameters are defined to complete the expression of the price penalty curves:

Params

$p$
a user (trading pair creator) defined parameter of the curve that denotes the threshold of $r_{alr}$ where segment 1 and segment 2 interfaces.

$TF_{in}$
Transaction fee for swap in.

$TF_{out}$
Transaction fee for swap out.


$X$ axis
$D/L_0$, where $D$ is the amount of $token_0$ to sell.

$Y$ axis
The price penalty of the transaction.

Lines

Red
The red line of this graph shows the price impacts of swaps in a certain condition.

Purple
The results without any penalty and only with $TF_{in}$ and $TF_{out}$.

Blue
The results with penalty of swapping exceed $RAS$, but without penalty of letting $r_{cov_{in}}$ exceed $1+p$.

Orange
The results with penalty of swapping exceed $RAS$ only during swap in.

6. Swap Price Calculation
6.1 Logic for price calculation
Before we enter into the calculation of trading prices, we first sort out the steps of price calculation (including transaction fees). One thing to note is that the imposition of transaction fees is quite flexible in Staple  at the time a virtual trading pair is being created, the creator could decide the percentage of transaction fees imposed on each of the 2 tokens in a VTP.

At any point of time, the status of a VTP is defined by a set of parameters e.g. $L_0$, $L_1$, $A_0$, $A_1$, $ALR_0$, $ALR_1$, $OP_0$, $OP_1$, $p$, $RAS$. While these parameters are determined by the status of liquidity provision and the history of transactions of a VTP in the real life, they could be manually set when the price calculation is simulated with graph1 and graph2.

Based on the amount of the token to sell and the percentage allocation of transaction fees, calculate the transaction fee for the token to sell.

Calculate the amount of penalty imposed on the token to sell with one applicable formula from equation (12), (13), (14), (15), if the asset liability ratio of this token in the VTP stays out of the $RAS$ range post the transaction.

Calculate the net amount of token to sell by subtracting transaction fees and price penalty, both expressed in the amount of token, from the amount of token to sell in step 1.

Calculate the estimated swap price with a known oracle price and the formula selected from equation (5) (6) (7) based on the relative position of $r_{ alr }$. In section 6.2, 6.3 and 6.4, we express the equation (5) (6) (7) with known parameters without further calculation.

Multiply the net amount of token to sell from step 4 with the estimated swap price from step 5 to roughly estimate the amount of token to buy that will be gained from the transaction.

Calculate the transaction fee for the token to buy with the outcome from step 6 and the determined percentage allocation of transaction fees.

Calculate the amount of penalty imposed on the token to buy with 1 applicable formula from equation (12) (13) (14) (15), if the asset liability ratio of the token to sell in the VTP stays out of the $RAS$ range post the transaction.

Calculate the net amount of token that will be received by subtracting transaction fees and price penalty, both expressed in the amount of token to buy, from the estimated amount of token to receive (see step 6).

The trader's cost in this transaction is the difference in the value of token to sell and the value of received token to buy. The price impact is the ratio of this cost and the value of token to sell.
6.2 Price Calculation for the First Segment
6.2.1 Calculate $P_{av}$
Formula
With the definition of above symbols and price adjustment curve, we are now set to decide $P_{av}$. Assume a swap from $token_0$ to $token_1$ with the starting adjusted price $P_{as}$ and the end adjusted price $P_{as}' = P_{ae}$. We define the average swap price of this transaction to be
$P_{av} =\sqrt{ P_{ as } * P_{ ae } } \tag{16}$
A swap of $D$ $token_0$ for $token_1$ should return $D*P_{av}$ $token_1$ to the trader.
Reasonablity
The price function defined above should satisfy the following requirement:
If a trader swaps $D$ $token_0$ to $D*P_{av}$ $token_1$, and swaps these $token_1$ right back, he should get exactly $D$ amount of $token_0$ when fees are not considered.
Proof
In the forward transaction: $D \ token_0 \rightarrow D * P_{ av_0 } \ token_1$, where $P_{ av_0 } = (P_{ as_0 } * P_{ as_0 }')^{ \frac{1}{2} }$
In the reverse transaction: $D * P_{ av_0 } \ token_1 \rightarrow D * P_{ av_0 } * P_{ av_1 }' \ token_0$, where $P_{ av_1 }' = (P_{ as_1 }' * P_{ as_1 }'')^{ \frac{1}{2}}$
Define $M = P_{ av_0 } * P_{ av_1 }'$,
$M^{2} = P_{ as_0 } * P_{ as_0 }' * P_{ as_1 }' * P_{ as_1 }''= \frac{P_{ as_0 }}{P_{ as_0 }''} = (\frac{ r_{ alr_0 }}{ r_{ alr_0 }''})^{  \frac{1}{n} } \tag{17}$
$M^{2n} = \frac{r_{ alr_0 }''}{r_{ alr_0 }} = \frac{ A_0 + D  D * M }{ A_0 } \tag{18}$
$(1  M^{ 2n }) + D / A_0 * ( 1  M ) = 0 \tag{19}$
If $M>1$, left side of the equation < 0, the equation does not hold;
If $M<1$, left side of the equation > 0, the equation does not hold;
$\therefore M = 1$
$\therefore P_{ av_0 } * P_{ av_1 }' = 1 \tag{20}$
So a trader who swaps $D$ $token_0$ to $D*P_{av}$ $token_1$ will get exactly $D$ $token_0$ through a reverse swap of $token_1$s received from the previous transaction.
6.2.2 Calculate $P_{ae}$
The $P_{av}$ above was calculated based on the known $P_{ae}$. With the oracle input, the transaction input eg. volume and direction and the $G(r_{alr})$ defined above, the end adjusted price $P_{ae}$ could indeed be calculated. However, the complexity of this numerical calculation will lead to huge gas cost. An accurate approximation is needed to derive $P_{ae}$.
Calculation
To derive the formula that approximates $P_{ae}$, we define:
$x = (\frac{P_{ as_0 }'}{P_{ as_0 }})^{\frac{1}{2}} = 1  t \ (t>0)$.
So $P_{ av_0 } = (P_{ as_0 } * P_{as_0}')^{\frac{1}{2}} = x * P_{ as_0 }$.
With the above definition, we can express $P_{ae}$ with the following formula:
$\therefore P_{ae} = P_{ as_0 }' = ( 1  t )^2 * P_{ as_0 } \tag{21}$
Now we try to express it with known parameters. From equation (18), we could get the following equation:
$\frac{P_{ as_0 }'}{P_{ as_0 }} = (\frac{1 + D / A_0 }{1 D * P_{ av_0 } / A_1})^{  \frac{1}{n}} \tag{22}$
By substituting $\frac{P_{ as_0 }'}{P_{ as_0 }}$ in equation (21) with the definition of $x$, we get the following equation:
$( 1  t )^{ 2n }  \frac{ D * P_{ as_0 } / A_1}{ 1 + D / A_0} * t + \frac{D * P_{ as_0 } / A_1  1 }{1 + D / A_0} = 0 \tag{23}$
$(1t)^{2n}$ could be approximated with the following approximate equation to reduce the computational complexity:
$(1t)^{2n} \approx 1 2n * t + n * (2n1) * t^2 \tag{24}$
From equation (23) and (24), we can arrive at:
$t^2at+b = 0 \tag{25}$
where $a = \frac{\frac{D * P_{ as_0 } / A_1}{ 1 + D / A_0} + 2n}{n * (2n  1)}, \ b = \frac{1 + \frac{D * P_{ as_0 } / A_1  1}{ 1 + D / A_0}}{n * (2n  1)} \tag{26}$
$\therefore t=\frac{a  \sqrt{{a}^2  4b}}{2} \tag{27}$
With equation (26) (27), the equation (21) for approximating $P_{ae}$ can be expressed with known parameters.
Validity of the Approximation
In this section, we prove that the $P_{ae}$ approximated with the above numerical solution is smaller than the exact outcome of the loop calculation, meaning a trader will receive slightly less tokens than what he was supposed to.
Suppose $t_0$ satisfies $t_0^2at_0+b = 0$ (see equaiton (25)). Based on the analysis in the previous section, we see that $t_0$ is an approximated value of $P_{ae}$. To prove the approximated $P_{ae}$ is smaller than the exact value, we prove that $1t>1t_0$ (see equation (21)).
From above, we know
$b =(t_0^2at_0) \tag{28}$
$\because (1t)^{2n} \leqslant 12n * t + n * (2n1) * t^2$
So we could express $(1t)^{2n}$ as follows:
$(1t)^{2n}= 12n * t + n * (2n  1) * t^2  n * (2n  1)*\lambda, \lambda \geqslant 0 \tag{29}$
The expression is further simplified to:
$t^2  at + b  \lambda = 0 \tag{30}$
By substituting equation (28) into equation (30), the following equation is gained:
$(t  t_0)( t + t_0  a) = \lambda \tag{31}$
Following equation (27),
$\because t = \frac{a  \sqrt{{a}^2  4b}}{2}$
$\therefore a > 2t$
If $t > t_0$, $0 \leqslant \lambda = (t  t_0 )( t + t_0  a) < 0$
$\therefore t < t_0$
$\therefore 1t > 1  t_0$
Now we have proven that the approximated $P_{ae}$ is smaller than the exact value. However, without providing the proof here, the gas saved in the calculation outweighs the loss from the approximation inaccuracy. Therefore the above numerical solution a valid approach.
6.3 Price Calculation for the Second Segment
With the known amount of token to sell, the equations from Section 6.2, the known percentage allocation of transaction fees in this VTP and equation (12), (13), (14), (15) for $RAS$ penalty, we could now derive the amount of token to be gained from the transaction ($D_{out}$) before the price penalty is imposed from the 2nd segment of the price adjustment curve. Without further proof, the following equation expresses the price penalty from the 2nd segment in terms of the amount of token that should be taken off from $D_{out}$, assuming the swap direction $token_0$ to $token_1$.
$Price \ Penalty = D_{ out } * [1  \frac{1}{1 + \frac{r_{ alr_0 }'}{m}  \frac{m}{ r_{alr_0}'}}] \tag{32}$
6.4 Price Calculation for the Third Segment
As the third segment is the mirror of the second segment around $r_{alr_0} = 1$ （see graph）, the $r_{alr_0}$ is approaching 1 during a swap from $token_0$ to $token_1$. Therefore, rather than price penalty, this transaction creates a price reward as follows:
$Price \ Reward = D_{out} * [1  \frac{1}{1 + \frac{1}{m * r_{ alr_0 }'}  m * r_{ alr_0 }'}] \tag{33}$