To ensure perpetuals converge to their respective underlying, funding is exchanged between long and short positions. For example, if the perp is trading at a premium to the underlying, then longs will pay shorts funding. This encourages further shorts and decreases the differential between perp and spot.

Lyra perpetuals are settled continuously. Specifically, whenever a user adjusts their position (say, via a trade or withdrawal) their unrealized funding and profit and loss is settled to the current perpetual price (not the spot price). Further, traders can have the settle function called on their account by other users (including themself!).

The instantaneous funding rate is calculated as follows.

First, we determine the `impact ask price (IAP)`

and `impact bid price (IBP)`

. These are defined as the average execution price for a market sell (buy) of the `impact notional amount`

(4000) respectively. We use these values to calculate the perpetual premium:

Premium = (max(0, IBP - Spot) - max(0, Spot - IAP)) / Spot

Where:

`IBP`

is the impact bid price.`Spot`

is the spot price of the underlying base asset.`IAP`

is the impact ask price.

Finally, we calculate the funding rate:

Funding Rate = Premium / perpConvergence + Underlying Rate

Where:

`UnderlyingRate= 0.00125%`

(equivalently, 0.01% per 8 hours) and`perpConvergence = 8`

The funding paid from longs to shorts is then calculated as follows:

Funding = -Perp Size x Funding Rate x Spot x Time Held

Where:

`Perp Size`

is the number of perpetual contracts (this number is negative for shorts).`Time Held`

is the duration the position is open for in hours.

The perpetual funding rates are capped at

`PERP_MAX_FUNDING = 0.4% per hour`

`PERP_MIN_FUNDING = -0.4% per hour`

In other words, the maximum rate longs can pay shorts will be 0.4% of the spot price per hour. Similarly, the maximum rate shorts can pay longs will be 0.4% per hour (represented as -0.4%).