UsdnProtocolLongLibrary

Git Source

Functions

getPositionValue

See getPositionValue.

function getPositionValue(Types.PositionId calldata posId, uint128 price, uint128 timestamp)
    external
    view
    returns (int256 value_);

getEffectiveTickForPrice

See getEffectiveTickForPrice.

function getEffectiveTickForPrice(uint128 price) external view returns (int24 tick_);

minTick

See minTick.

function minTick() public view returns (int24 tick_);

getTickLiquidationPenalty

See getTickLiquidationPenalty.

function getTickLiquidationPenalty(int24 tick) public view returns (uint24 liquidationPenalty_);

getEffectiveTickForPrice

See getEffectiveTickForPrice.

function getEffectiveTickForPrice(
    uint128 price,
    uint256 assetPrice,
    uint256 longTradingExpo,
    HugeUint.Uint512 memory accumulator,
    int24 tickSpacing
) public pure returns (int24 tick_);

_applyPnlAndFundingAndLiquidate

Applies PnL, funding, and liquidates positions if necessary.

If there were any liquidations, it sends the rewards to the msg.sender.

function _applyPnlAndFundingAndLiquidate(
    uint256 neutralPrice,
    uint256 timestamp,
    uint16 iterations,
    Types.ProtocolAction action,
    bytes calldata priceData
) public returns (Types.LiqTickInfo[] memory liquidatedTicks_, bool isLiquidationPending_);

Parameters

NameTypeDescription
neutralPriceuint256The neutral price for the asset.
timestampuint256The timestamp at which the operation is performed.
iterationsuint16The number of iterations for the liquidation process.
actionTypes.ProtocolActionThe type of action that is being performed by the user.
priceDatabytesThe data given to the oracle middleware corresponding to neutralPrice.

Returns

NameTypeDescription
liquidatedTicks_Types.LiqTickInfo[]Information about the liquidated ticks.
isLiquidationPending_boolIf there are remaining ticks that can be liquidated.

_prepareInitiateOpenPositionData

Prepares the data for the initiateOpenPosition function.

function _prepareInitiateOpenPositionData(Types.PrepareInitiateOpenPositionParams calldata params)
    public
    returns (Types.InitiateOpenPositionData memory data_);

Parameters

NameTypeDescription
paramsTypes.PrepareInitiateOpenPositionParamsThe parameters for the _prepareInitiateOpenPositionData function.

Returns

NameTypeDescription
data_Types.InitiateOpenPositionDataThe transient data for the open position action.

_removeAmountFromPosition

Removes amountToRemove from position pos then updates the tick data and the position.

This method does not update the long balance. If the amount to remove is greater than or equal to the position's total amount, the position is deleted instead.

function _removeAmountFromPosition(
    int24 tick,
    uint256 index,
    Types.Position memory pos,
    uint128 amountToRemove,
    uint128 totalExpoToRemove
) public returns (HugeUint.Uint512 memory liqMultiplierAccumulator_);

Parameters

NameTypeDescription
tickint24The tick the position is in.
indexuint256Index of the position in the tick array.
posTypes.PositionThe position to remove the amount from.
amountToRemoveuint128The amount to remove from the position.
totalExpoToRemoveuint128The total exposure to remove from the position.

Returns

NameTypeDescription
liqMultiplierAccumulator_HugeUint.Uint512The updated liquidation multiplier accumulator.

_getTickFromDesiredLiqPrice

Computes the tick number with penalty and liquidation price without penalty from the desired liquidation price.

This function first calculates a tick for the desired liquidation price (no rounding), then adds the penalty to the tick and rounds down to the nearest tick spacing. Then it subtracts the penalty from the final tick and calculates the corresponding liquidation price.

function _getTickFromDesiredLiqPrice(uint128 desiredLiqPriceWithoutPenalty, uint24 liquidationPenalty)
    public
    view
    returns (int24 tickWithPenalty_, uint128 liqPriceWithoutPenalty_);

Parameters

NameTypeDescription
desiredLiqPriceWithoutPenaltyuint128The desired liquidation price without penalty.
liquidationPenaltyuint24The liquidation penalty.

Returns

NameTypeDescription
tickWithPenalty_int24The tick number including the liquidation penalty.
liqPriceWithoutPenalty_uint128The liquidation price without penalty.

_getTickFromDesiredLiqPrice

Computes the tick number with penalty and liquidation price without penalty from the desired liquidation price and protocol state.

This function first calculates a tick for the desired liquidation price (no rounding), then adds the penalty to the tick and rounds down to the nearest tick spacing. Then it subtracts the penalty from the final tick and calculates the corresponding liquidation price.

function _getTickFromDesiredLiqPrice(
    uint128 desiredLiqPriceWithoutPenalty,
    uint256 assetPrice,
    uint256 longTradingExpo,
    HugeUint.Uint512 memory accumulator,
    int24 tickSpacing,
    uint24 liquidationPenalty
) public pure returns (int24 tickWithPenalty_, uint128 liqPriceWithoutPenalty_);

Parameters

NameTypeDescription
desiredLiqPriceWithoutPenaltyuint128The desired liquidation price without penalty.
assetPriceuint256The current price of the asset.
longTradingExpouint256The trading exposure of the long side (total exposure - balance long).
accumulatorHugeUint.Uint512The liquidation multiplier accumulator.
tickSpacingint24The tick spacing.
liquidationPenaltyuint24The liquidation penalty.

Returns

NameTypeDescription
tickWithPenalty_int24The tick number including the liquidation penalty.
liqPriceWithoutPenalty_uint128The liquidation price without penalty.

_getTickFromDesiredLiqPrice

Computes the tick number with penalty and liquidation price without penalty from the desired liquidation price and a fixed precision version of the liquidation multiplier accumulator.

This function first calculates a tick for the desired liquidation price (no rounding), then adds the penalty to the tick and rounds down to the nearest tick spacing. Then it subtracts the penalty from the final tick and calculates the corresponding liquidation price.

function _getTickFromDesiredLiqPrice(
    uint128 desiredLiqPriceWithoutPenalty,
    uint256 liqMultiplier,
    int24 tickSpacing,
    uint24 liquidationPenalty
) public pure returns (int24 tickWithPenalty_, uint128 liqPriceWithoutPenalty_);

Parameters

NameTypeDescription
desiredLiqPriceWithoutPenaltyuint128The desired liquidation price without penalty.
liqMultiplieruint256The liquidation price multiplier (with LIQUIDATION_MULTIPLIER_DECIMALS decimals).
tickSpacingint24The tick spacing.
liquidationPenaltyuint24The liquidation penalty.

Returns

NameTypeDescription
tickWithPenalty_int24The tick number including the liquidation penalty.
liqPriceWithoutPenalty_uint128The liquidation price without penalty.

_findHighestPopulatedTick

Finds the highest tick that contains at least one position.

If there are no ticks with a position left, returns minTick.

function _findHighestPopulatedTick(int24 searchStart) public view returns (int24 tick_);

Parameters

NameTypeDescription
searchStartint24The tick to start searching from.

Returns

NameTypeDescription
tick_int24The highest tick at or below searchStart.

_usdnRebase

Checks if a USDN rebase is required and adjust the divisor if needed.

Only call this function after _applyPnlAndFunding has been called to update the balances.

function _usdnRebase(uint128 assetPrice) internal returns (bool rebased_, bytes memory callbackResult_);

Parameters

NameTypeDescription
assetPriceuint128The current price of the underlying asset.

Returns

NameTypeDescription
rebased_boolWhether a rebase was performed.
callbackResult_bytesThe rebase callback result, if any.

_sendRewardsToLiquidator

Sends rewards to the liquidator.

Should still emit an event if liquidationRewards = 0 to better keep track of those anomalies as rewards for those will be managed off-chain.

function _sendRewardsToLiquidator(
    Types.LiqTickInfo[] memory liquidatedTicks,
    uint256 currentPrice,
    bool rebased,
    Types.RebalancerAction rebalancerAction,
    Types.ProtocolAction action,
    bytes memory rebaseCallbackResult,
    bytes memory priceData
) internal;

Parameters

NameTypeDescription
liquidatedTicksTypes.LiqTickInfo[]Information about the liquidated ticks.
currentPriceuint256The current price of the asset.
rebasedboolWhether a USDN rebase was performed.
rebalancerActionTypes.RebalancerActionThe rebalancer action that was performed.
actionTypes.ProtocolActionThe protocol action that triggered liquidations.
rebaseCallbackResultbytesThe rebase callback result, if any.
priceDatabytesThe data given to the oracle middleware to get a price.

_triggerRebalancer

Triggers the rebalancer if the imbalance on the long side is too high. It will close the rebalancer's position (if there is one) and open a new one with the pending assets, the value of the previous position and the liquidation bonus (if available) with a leverage that would fill enough trading exposure to reach the desired imbalance, up to the max leverages.

Only call this function after liquidations are performed to have a non-zero remainingCollateral value. Will return the provided long and vault balances if no rebalancer is set or if the imbalance is not high enough. If remainingCollateral is negative, the rebalancer bonus will be 0.

function _triggerRebalancer(uint128 lastPrice, uint256 longBalance, uint256 vaultBalance, int256 remainingCollateral)
    internal
    returns (uint256 longBalance_, uint256 vaultBalance_, Types.RebalancerAction action_);

Parameters

NameTypeDescription
lastPriceuint128The last price used to update the protocol.
longBalanceuint256The balance of the long side.
vaultBalanceuint256The balance of the vault side.
remainingCollateralint256The collateral remaining after the liquidations.

Returns

NameTypeDescription
longBalance_uint256The updated long balance not saved into storage yet.
vaultBalance_uint256The updated vault balance not saved into storage yet.
action_Types.RebalancerActionThe action performed by this function.

_flashOpenPosition

Immediately opens a position with the given price.

Should only be used to open the rebalancer's position.

function _flashOpenPosition(
    address user,
    uint128 lastPrice,
    int24 tick,
    uint128 posTotalExpo,
    uint24 liquidationPenalty,
    uint128 amount
) internal returns (Types.PositionId memory posId_);

Parameters

NameTypeDescription
useraddressThe address of the rebalancer.
lastPriceuint128The last price used to update the protocol.
tickint24The tick the position should be opened in.
posTotalExpouint128The total exposure of the position.
liquidationPenaltyuint24The liquidation penalty of the tick.
amountuint128The amount of collateral in the position.

Returns

NameTypeDescription
posId_Types.PositionIdThe ID of the position that was created.

_flashClosePosition

Immediately closes a position with the given price.

Should only be used to close the rebalancer's position.

function _flashClosePosition(Types.PositionId memory posId, uint128 lastPrice, Types.CachedProtocolState memory cache)
    internal
    returns (int256 positionValue_);

Parameters

NameTypeDescription
posIdTypes.PositionIdThe ID of the position to close.
lastPriceuint128The last price used to update the protocol.
cacheTypes.CachedProtocolStateThe cached state of the protocol, will be updated during this call.

Returns

NameTypeDescription
positionValue_int256The value of the closed position.

_liquidatePositions

Liquidates positions that have a liquidation price lower than the current price.

function _liquidatePositions(uint256 currentPrice, uint16 iteration, int256 tempLongBalance, int256 tempVaultBalance)
    internal
    returns (Types.LiquidationsEffects memory effects_);

Parameters

NameTypeDescription
currentPriceuint256The current price of the asset.
iterationuint16The maximum number of ticks to liquidate (minimum is 1).
tempLongBalanceint256The temporary long balance as calculated when applying the PnL and funding.
tempVaultBalanceint256The temporary vault balance as calculated when applying the PnL and funding.

Returns

NameTypeDescription
effects_Types.LiquidationsEffectsThe effects of the liquidations on the protocol.

_updateStateAfterLiquidation

Updates the state of the contract according to the liquidation effects.

function _updateStateAfterLiquidation(LiquidationData memory data, Types.LiquidationsEffects memory effects) internal;

Parameters

NameTypeDescription
dataLiquidationDataThe liquidation data, which gets mutated by the function.
effectsTypes.LiquidationsEffectsThe effects of the liquidations.

_checkImbalanceLimitOpen

Checks and reverts if the position's trading exposure exceeds the imbalance limits.

function _checkImbalanceLimitOpen(
    uint256 openTotalExpoValue,
    uint256 collateralAmount,
    uint256 collateralAmountAfterFees
) internal view;

Parameters

NameTypeDescription
openTotalExpoValueuint256The total exposure of the position to open.
collateralAmountuint256The amount of collateral of the position.
collateralAmountAfterFeesuint256The amount of collateral of the position after fees.

_calcRebalancerPositionTick

Calculates the tick of the rebalancer position to open.

The returned tick must give a leverage higher than or equal to the minimum leverage of the protocol and lower than or equal to the rebalancer and USDN protocol leverages (lowest of the 2).

function _calcRebalancerPositionTick(
    uint128 lastPrice,
    uint128 positionAmount,
    uint256 rebalancerMaxLeverage,
    Types.CachedProtocolState memory cache
) internal view returns (Types.RebalancerPositionData memory posData_);

Parameters

NameTypeDescription
lastPriceuint128The last price used to update the protocol.
positionAmountuint128The amount of assets in the position.
rebalancerMaxLeverageuint256The maximum leverage supported by the rebalancer.
cacheTypes.CachedProtocolStateThe cached protocol state values.

Returns

NameTypeDescription
posData_Types.RebalancerPositionDataThe tick, total exposure and liquidation penalty for the rebalancer position.

_checkSafetyMargin

Checks and reverts if the leverage of a position exceeds the safety margin.

function _checkSafetyMargin(uint128 currentPrice, uint128 liquidationPrice) internal view;

Parameters

NameTypeDescription
currentPriceuint128The current price of the asset.
liquidationPriceuint128The liquidation price of the position.

_getTickLiquidationPenalty

Retrieves the liquidation penalty assigned to the given tickHash.

If there are no positions in it, returns the current setting from storage.

function _getTickLiquidationPenalty(bytes32 tickHash) internal view returns (uint24 liquidationPenalty_);

Parameters

NameTypeDescription
tickHashbytes32The tick hash (hashed tick number + version).

Returns

NameTypeDescription
liquidationPenalty_uint24The liquidation penalty (in tick spacing units).

_calcTickFromBitmapIndex

Converts the given bitmap index to a tick number using the stored tick spacing.

function _calcTickFromBitmapIndex(uint256 index) internal view returns (int24 tick_);

Parameters

NameTypeDescription
indexuint256The index into the bitmap.

Returns

NameTypeDescription
tick_int24The tick corresponding to the index, a multiple of the tick spacing.

_unadjustPrice

Calculates the unadjusted price of a position's liquidation price, which can be used to find the corresponding tick.

function _unadjustPrice(uint256 price, uint256 assetPrice, uint256 longTradingExpo, HugeUint.Uint512 memory accumulator)
    internal
    pure
    returns (uint256 unadjustedPrice_);

Parameters

NameTypeDescription
priceuint256An adjusted liquidation price (taking into account the effects of funding).
assetPriceuint256The current price of the asset.
longTradingExpouint256The trading exposure of the long side (total exposure - balance long).
accumulatorHugeUint.Uint512The liquidation multiplier accumulator.

Returns

NameTypeDescription
unadjustedPrice_uint256The unadjusted price of price.

_unadjustPrice

Calculates the unadjusted price of a position's liquidation price, which can be used to find the corresponding tick, with a fixed precision representation of the liquidation multiplier.

function _unadjustPrice(uint256 price, uint256 liqMultiplier) internal pure returns (uint256 unadjustedPrice_);

Parameters

NameTypeDescription
priceuint256An adjusted liquidation price (taking into account the effects of funding).
liqMultiplieruint256The liquidation price multiplier, with LIQUIDATION_MULTIPLIER_DECIMALS decimals.

Returns

NameTypeDescription
unadjustedPrice_uint256The unadjusted price for the liquidation price.

_tickValue

Calculates the value of a tick, knowing its contained total exposure and the current asset price.

function _tickValue(
    int24 tick,
    uint256 currentPrice,
    uint256 longTradingExpo,
    HugeUint.Uint512 memory accumulator,
    Types.TickData memory tickData
) internal pure returns (int256 value_);

Parameters

NameTypeDescription
tickint24The tick number.
currentPriceuint256The current price of the asset.
longTradingExpouint256The trading exposure of the long side.
accumulatorHugeUint.Uint512The liquidation multiplier accumulator.
tickDataTypes.TickDataThe aggregated data of the tick.

Returns

NameTypeDescription
value_int256The amount of asset tokens the tick is worth.

_calcLiqPriceFromTradingExpo

Calculates the liquidation price without penalty of a position to reach a certain trading exposure.

If the sum of amount and tradingExpo equals 0, reverts.

function _calcLiqPriceFromTradingExpo(uint128 currentPrice, uint128 amount, uint256 tradingExpo)
    internal
    pure
    returns (uint128 liqPrice_);

Parameters

NameTypeDescription
currentPriceuint128The price of the asset.
amountuint128The amount of asset used as collateral.
tradingExpouint256The trading exposure.

Returns

NameTypeDescription
liqPrice_uint128The liquidation price without penalty.

_calcTickFromBitmapIndex

Converts a bitmap index to a tick number using the provided tick spacing.

function _calcTickFromBitmapIndex(uint256 index, int24 tickSpacing) internal pure returns (int24 tick_);

Parameters

NameTypeDescription
indexuint256The index into the bitmap.
tickSpacingint24The tick spacing to use.

Returns

NameTypeDescription
tick_int24The tick corresponding to the index, a multiple of tickSpacing.

_handleNegativeBalances

Handles negative balances by transferring assets from one side to the other.

Balances are unsigned integers and can't be negative. In theory, this can not happen anymore because we have more precise calculations with the liqMultiplierAccumulator compared to the old liquidationMultiplier.

function _handleNegativeBalances(int256 tempLongBalance, int256 tempVaultBalance)
    internal
    pure
    returns (uint256 longBalance_, uint256 vaultBalance_);

Parameters

NameTypeDescription
tempLongBalanceint256The temporary long balance after liquidations
tempVaultBalanceint256The temporary vault balance after liquidations

Returns

NameTypeDescription
longBalance_uint256The new long balance after rebalancing
vaultBalance_uint256The new vault balance after rebalancing

_calcImbalanceOpenBps

Calculates the current imbalance for the open action checks.

If the value is positive, the long trading exposure is larger than the vault trading exposure. In case of an empty vault balance, returns int256.max since the resulting imbalance would be infinity.

function _calcImbalanceOpenBps(int256 vaultExpo, int256 longBalance, uint256 totalExpo)
    internal
    pure
    returns (int256 imbalanceBps_);

Parameters

NameTypeDescription
vaultExpoint256The vault exposure (including the pending vault balance and the fees of the position to open).
longBalanceint256The balance of the long side (including the long position to open).
totalExpouint256The total exposure of the long side (including the long position to open).

Returns

NameTypeDescription
imbalanceBps_int256The imbalance (in basis points).

_unadjustedPriceToTick

Calculates the tick corresponding to an unadjusted price, without rounding to the tick spacing.

function _unadjustedPriceToTick(uint256 unadjustedPrice) internal pure returns (int24 tick_);

Parameters

NameTypeDescription
unadjustedPriceuint256The unadjusted price.

Returns

NameTypeDescription
tick_int24The tick number, bound by MIN_TICK.

_roundTickDown

Rounds a tick down to a multiple of the tick spacing.

The function is bound by minTick, so the first tick which is a multiple of the tick spacing and greater than or equal to MIN_TICK.

function _roundTickDown(int24 tick, int24 tickSpacing) internal pure returns (int24 roundedTick_);

Parameters

NameTypeDescription
tickint24The tick number.
tickSpacingint24The tick spacing.

Returns

NameTypeDescription
roundedTick_int24The rounded tick number.

_roundTickDownWithPenalty

Rounds the given tick down to a multiple of the tick spacing .

The result will always be above MIN_TICK + liquidationPenalty.

function _roundTickDownWithPenalty(int24 tickWithPenalty, int24 tickSpacing, uint24 liqPenalty)
    internal
    pure
    returns (int24 roundedTick_);

Parameters

NameTypeDescription
tickWithPenaltyint24The tick number with the liquidation penalty.
tickSpacingint24The tick spacing.
liqPenaltyuint24The liquidation penalty.

Returns

NameTypeDescription
roundedTick_int24The rounded tick number.

_getEffectiveTickForPriceNoRounding

Calculates the effective tick for a given price without rounding to the tick spacing.

function _getEffectiveTickForPriceNoRounding(
    uint128 price,
    uint256 assetPrice,
    uint256 longTradingExpo,
    HugeUint.Uint512 memory accumulator
) internal pure returns (int24 tick_);

Parameters

NameTypeDescription
priceuint128The price to be adjusted.
assetPriceuint256The current asset price.
longTradingExpouint256The long trading exposure.
accumulatorHugeUint.Uint512The liquidation multiplier accumulator.

Returns

NameTypeDescription
tick_int24The tick number.

_getEffectiveTickForPriceNoRounding

Calculates the effective tick for a given price without rounding to the tick spacing with a fixed precision representation of the liquidation multiplier.

function _getEffectiveTickForPriceNoRounding(uint128 price, uint256 liqMultiplier)
    internal
    pure
    returns (int24 tick_);

Parameters

NameTypeDescription
priceuint128The price to be adjusted.
liqMultiplieruint256The liquidation price multiplier (with LIQUIDATION_MULTIPLIER_DECIMALS decimals).

Returns

NameTypeDescription
tick_int24The tick number.

_calcRebaseTotalSupply

Calculates the required USDN total supply to reach targetPrice.

function _calcRebaseTotalSupply(uint256 vaultBalance, uint128 assetPrice, uint128 targetPrice, uint8 assetDecimals)
    internal
    pure
    returns (uint256 totalSupply_);

Parameters

NameTypeDescription
vaultBalanceuint256The balance of the vault.
assetPriceuint128The price of the underlying asset.
targetPriceuint128The target USDN price to reach.
assetDecimalsuint8The number of decimals of the asset.

Returns

NameTypeDescription
totalSupply_uint256The required total supply to achieve targetPrice.

Structs

LiquidationData

Structure to hold the temporary data during liquidations.

struct LiquidationData {
    int256 tempLongBalance;
    int256 tempVaultBalance;
    int24 currentTick;
    int24 iTick;
    uint256 totalExpoToRemove;
    uint256 accumulatorValueToRemove;
    uint256 longTradingExpo;
    uint256 currentPrice;
    HugeUint.Uint512 accumulator;
    bool isLiquidationPending;
}

Properties

NameTypeDescription
tempLongBalanceint256The updated long balance not saved into storage yet.
tempVaultBalanceint256The updated vault balance not saved into storage yet.
currentTickint24The current tick (corresponding to the current asset price).
iTickint24Tick iterator index.
totalExpoToRemoveuint256The total exposure to remove due to liquidations.
accumulatorValueToRemoveuint256The value to remove from the liquidation multiplier accumulator due to liquidations.
longTradingExpouint256The long trading exposure.
currentPriceuint256The current price of the asset.
accumulatorHugeUint.Uint512The liquidation multiplier accumulator before liquidations.
isLiquidationPendingboolWhether some ticks are still populated above the current price (left to liquidate).

ApplyPnlAndFundingAndLiquidateData

Data structure for the _applyPnlAndFundingAndLiquidate function.

struct ApplyPnlAndFundingAndLiquidateData {
    int256 tempLongBalance;
    int256 tempVaultBalance;
    uint128 lastPrice;
    bool rebased;
    bytes callbackResult;
    Types.RebalancerAction rebalancerAction;
}

Properties

NameTypeDescription
tempLongBalanceint256The updated long balance not saved into storage yet.
tempVaultBalanceint256The updated vault balance not saved into storage yet.
lastPriceuint128The last price used to update the protocol.
rebasedboolA boolean indicating if the USDN token was rebased.
callbackResultbytesThe result of the USDN rebase callback.
rebalancerActionTypes.RebalancerActionThe action performed by the _triggerRebalancer function.

TriggerRebalancerData

Data structure for the _triggerRebalancer function.

struct TriggerRebalancerData {
    uint128 positionAmount;
    uint256 rebalancerMaxLeverage;
    Types.PositionId rebalancerPosId;
    uint128 positionValue;
}

Properties

NameTypeDescription
positionAmountuint128The amount of assets in the rebalancer's position.
rebalancerMaxLeverageuint256The maximum leverage of the rebalancer.
rebalancerPosIdTypes.PositionIdThe ID of the rebalancer's position.
positionValueuint128The value of the rebalancer's position.