💹Applying Interest
This page describes how borrow and deposit interest rates are applied to the positions
The Challenge
The TurboSwap protocol continuously applies compound interest on all positive (long) and negative (short) positions. Implementing this in a naive way is unfeasible on-chain, as the number of positions could be arbitrarily high and iterating through all of them each time would be too expensive.
Thus, the protocol needs to use some tricks to efficiently apply interest to a large number of positions.
Applying Interest on Aggregated Positions
For a particular asset, the protocol stores the following aggregated values:
τi+: the time when the sum of all the long positions in thei-thasset was last updated Vi+(τi+): the sum of all the long positions in thei-thasset as it was at the time momentτi+ ui+(τi+): the hypothetical value at the time momentτi+of a one unit long positions opened in the thei-thasset at the time thei-thasset was just listed with the protocol τi−: the time when the sum of all the short positions in thei-thasset was last updated Vi−(τi−): the sum of all the short positions in thei-thasset as it was at the time momentτi− ui−(τi−): the hypothetical value at the time momentτi+of a one unit short positions opened in the thei-thasset at the time thei-thasset was just listed with the protocol
Knowing these values, the protocol can calculateVi+(t)andui+(t)for any time momentt⩾τi+, and can calculateVi−(t) andui−(t)for any time momentt⩾τi−. See the “Main Concepts” sections for the calculation formulas.
The stored values for an asset ought to be updated only when the borrow interest rate for the asset is about to be changed, or some position in this asset is changed due to a user action. Continuous accumulation of interest doesn't require the stored values to be updated
Applying Interest on Individual Positions
For a particular position, the protocol stored the following values:
τij: the time the position of thej-thaccount in thei-thasset was last updated vij(τij): the position value of thej-thaccount in thei-thasset, as it was at the time momentτij uij(τij): the valueui+(τij)if the position is long, or the value ui−(τij) if the position is short
Knowing these values, the protocol can calculatevij(t)anduij(t)for any time momentt⩾max(τij,τi+,τi−):
The stored values for a position outage to be updated only then the position is changed due to a user action. Continuous accumulation of interest doesn't require the stored values to be updated.
Last updated