The movePriceTowardsTarget function is a core piece of logic in the Algebra’s swap logic, handling the price changes during token swaps.
Its purpose is to compute how far the price can move within a given tick range based on the available liquidity and the amount of tokens being swapped in or out. This function ensures that the protocol moves towards the target price and calculates how much of the input token will be swapped, how much output token will be received, and what portion of the input will be taken as a fee.
The function computes:
resultPrice: The price after the swap completes, which will either be the target price or another value if the input is exhausted before reaching the target price.
input: The amount of token0 or token1 actually swapped in.
output: The amount of token0 or token1 received as a result of the swap.
feeAmount: The amount of input token taken as the protocol fee.
There are two main scenarios:
Path A: The provided input amount, after accounting for the fee, is less than or equal to what can be swapped within the active range, meaning the price reaches the target price.
Path B: The provided input amount, after accounting for the fee, exceeds what can be swapped within the active range, meaning the price does not reach the target price.
In this post, we will cover Path A:
In this path, the provided input amount (after accounting for the fee) is smaller than or just enough to move the price to the targetPrice. This means the swap will consume the entire input amount without exceeding the current price range, the current active liquidity is therefore enough to fully cover the input amount (after fee).
Steps:
Fee Deduction:
The input amount has to account for the protocol fee. This is calculated by multiplying the input amount by (Constants.FEE_DENOMINATOR - fee) / Constants.FEE_DENOMINATOR, which gives the input available for the swap after the fee is deducted:
Calculate the Maximum Input:
The function then computes the maximum amount of input token that can be swapped within the current price range without exceeding the targetPrice. This is done using the helper function getInputTokenAmount() which calculates the input token delta based on the current and target prices and the available liquidity.
In trivial terms this can be explained as the input amount which can be absorbed based on the current active liquidity:
Determine Result:
If the input amount (after fees) is enough to reach the targetPrice, then the swap completes within this tick, and the price moves all the way to the target price.
If so, the result price is set to targetPrice, and the fee amount is computed based on the actual input used:
Output Calculation:
The function calculates the amount of the output token received for the swap using either getOutputTokenDelta01() or getOutputTokenDelta10(), depending on the direction of the swap: