Skip to main content

Swap

The swap function is the central mechanism for swapping between Fixed Tokens and Loan Tokens. When swapping, the protocol finds the nearest tick (liquidity or limit) with a positive balance of the output token. Using the tick bitmap, the protocol processes liquidity in the following order per tick:

  1. Liquidity of partially filled limit orders
  2. Liquidity of unfilled limit orders
  3. Liquidity ticks

This ensures that at all times, on a per tick basis only 3 batch ids can contain liquidity.

Swap

Parameters

  • PoolKey key: Contains pool configuration (tokens, maturity, tick parameters).
  • int256 amount: The amount to swap. A positive value indicates exact out, while a negative value indicates exact in.
  • uint8 limitTick: A boundary tick that limits how far the swap can execute, acting as the slippage limit.
  • bool isLimitOrder: Determines if any remaining input amount once the limitTick is reached should be added as a limit order.
  • bool fixedTokenForLoanToken: Indicates whether the output should be in Loan Tokens or Fixed Tokens.

Users can specify the direction of their swap (e.g., Lend or borrow) using fixedTokenForLoanToken and specify exactIn or exactOut using the sign of the amount.

Swap Output

  • amountInFilled: The amount of input tokens consumed.
  • amountOutFilled: The amount of output tokens delivered.
  • limitOrderAmount: The portion added as a limit order.
  • batchId: Identifies the batch of limit order involved (if applicable).

Swapping Mechanics

Slippage Limit:

The limitTick parameter acts as an interest rate slippage limit when swapping.

Remaining Input as Limit Order:

If isLimitOrder is true, any remaining input amount when the limitTick is reached is placed as a limit order.

Non-Deterministic Limit Orders:

If swapping with an exact out amount and isLimitOrder == true, and the swap breaches the slippage limit, the transaction reverts. Limit orders must be specified with an exact input amount since they execute asynchronously and cannot guarantee an exact output amount.

Exchange Rate Calculation

The exchange rate is determined at each tick by the tick's corresponding interest rate using the exchange rate formula:

exchangeRate=e(timeToMaturityInYearstickInterestRate)\text{exchangeRate} = e^{(\text{timeToMaturityInYears} \cdot \text{tickInterestRate})}

User swap exchange rate

Swapper pay fees to liquidity providers and limit order users when swapping. The fee corresponds to bpsPerTick. This is such that:

  • When swapping Loan Tokens to Fixed Tokens (lending), users receive Fixed Tokens at the tick's rate minus bpsPerTick.
  • When swapping Fixed Tokens to Loan Tokens, users receive Loan Tokens at the tick's rate plus bpsPerTick.

This means that in the absence of Pool Fees, Liquidity Providers and Limit order users receive a rate that is improved by bpsPerTick compared to the tick at which they added liquidity or a limit order.