When swapping through liquidity via a Multi-Hop Swap or a Limit Order, we iterate through the available TickLiquidity to fill the swap order. Liquidity is always iterated through in order of best to worst price (from the taker’s perspective.) For each swap, we completely exhaust the available reserves before moving on to the next tick. For TickLiquidity instances at the same TickIndex they are iterated through in a deterministic order as follows:
PoolReserves take priority
LimitOrderTranches are iterated through when Pool Reserve liquidity is depleted
LimitOrderTranches are iterated through in alphabetical order of their TrancheKey (LimitOrderTranche.Key.TrancheKey.)
When swapping through PoolReserves the proceeds from the swap are added to the reserves on the reciprocal side of the pool. Ie. The output of TokenA swapped through a PoolReserves will be moved to a PoolReserves holding TokenB.
Alice Performs a Swap using a Taker Limit Order. She wants to swap 100USDC for ATOM at the best possible price.
The first available TickLiquidity holding ATOM is a LimitOrderTranche at tick 19640. Since this is a limit order, when swapped through and depleted the liquidity is removed from state and the USDC Alice paid can be later withdrawn by the limit order Receiver
Alice swaps up to 71.27USDC using this pool before depleting the reserves. This will net her 10ATOM for the swap:
Alice still has 28.73USDC she needs to swap, so we move to the next available tick: 20795
This tick offers ATOM at a price of 8USDC per ATOM and is of type PoolReserve. Any USDC Alice pays for this swap will be placed in the corresponding poolReserves of the Pool (USDC @ Tick −20795 .) Alice swaps the remainder of her USDC here, resulting in an additional 3.5ATOM:
AmountOut=PriceAmountIn=1.00012079528.73=3.59
Done. Alice has swapped 100USDC for 13.59ATOM with an average price of 0.136ATOM per USDC.
NOTE: For the clarity of this example we are assuming that the PoolReserves have a fee of zero. In a real world scenario almost all PoolReserves will have a fee. In a scenario with fees TokenIn will be added to Tick∗−1+(2⋅fee). Learn more about fees in the PoolReserves section.
We are still displaying the tick liquidity at 19640 as a visual aid. In reality this tick is depleted and removedThere are different behaviors a taker limit order can take when swapping. for example, here we were not sensitive to Price.
Learn more about the order types and their unique behaviors in the Order Types section.