UsdnProtocolCoreLibrary

Git Source

Functions

initialize

See initialize.

function initialize(uint128 depositAmount, uint128 longAmount, uint128 desiredLiqPrice, bytes calldata currentPriceData)
    external;

removeBlockedPendingAction

See removeBlockedPendingAction.

function removeBlockedPendingAction(address validator, address payable to) external;

removeBlockedPendingActionNoCleanup

See removeBlockedPendingActionNoCleanup.

function removeBlockedPendingActionNoCleanup(address validator, address payable to) external;

_createClosePendingAction

Prepares the pending action struct for the close position action and add it to the queue.

function _createClosePendingAction(
    address to,
    address validator,
    Types.PositionId memory posId,
    uint128 amountToClose,
    uint64 securityDepositValue,
    Types.ClosePositionData memory data
) external returns (uint256 amountToRefund_);

Parameters

NameTypeDescription
toaddressThe address that will receive the assets.
validatoraddressThe validator for the pending action.
posIdTypes.PositionIdThe unique identifier of the position.
amountToCloseuint128The amount of collateral to remove from the position's amount.
securityDepositValueuint64The value of the security deposit for the newly created pending action.
dataTypes.ClosePositionDataThe close position data.

Returns

NameTypeDescription
amountToRefund_uint256The security deposit value of a stale pending action.

_createWithdrawalPendingAction

Prepares the pending action struct for a withdrawal and adds it to the queue.

function _createWithdrawalPendingAction(
    address to,
    address validator,
    uint152 usdnShares,
    uint64 securityDepositValue,
    Vault.WithdrawalData memory data
) external returns (uint256 amountToRefund_);

Parameters

NameTypeDescription
toaddressThe recipient of the assets.
validatoraddressThe address that is supposed to validate the withdrawal and receive the security deposit.
usdnSharesuint152The amount of USDN shares to burn.
securityDepositValueuint64The value of the security deposit for the newly created pending action.
dataVault.WithdrawalDataThe withdrawal action data.

Returns

NameTypeDescription
amountToRefund_uint256Refund The security deposit value of a stale pending action.

getUserPendingAction

See getUserPendingAction.

function getUserPendingAction(address validator) external view returns (Types.PendingAction memory action_);

funding

See funding.

function funding(uint128 timestamp)
    external
    view
    returns (int256 funding_, int256 fundingPerDay_, int256 oldLongExpo_);

longAssetAvailableWithFunding

Gets the predicted value of the long balance for the given asset price and timestamp.

The effects of the funding and any PnL of the long positions since the last contract state update is taken into account, as well as the fees. If the provided timestamp is older than the last state update, the function reverts with UsdnProtocolTimestampTooOld. The value cannot be below 0.

function longAssetAvailableWithFunding(uint128 currentPrice, uint128 timestamp)
    public
    view
    returns (uint256 available_, int256 fee_);

Parameters

NameTypeDescription
currentPriceuint128The given asset price.
timestampuint128The timestamp corresponding to the given price.

Returns

NameTypeDescription
available_uint256The long balance value in assets.
fee_int256The protocol fees in asset units, either positive or negative.

longTradingExpoWithFunding

See longTradingExpoWithFunding.

function longTradingExpoWithFunding(uint128 currentPrice, uint128 timestamp) public view returns (uint256 expo_);

_checkOpenPositionLeverage

Checks if the position's leverage is in the authorized range of values.

function _checkOpenPositionLeverage(uint128 adjustedPrice, uint128 liqPriceWithoutPenalty, uint256 userMaxLeverage)
    public
    view;

Parameters

NameTypeDescription
adjustedPriceuint128The adjusted price of the asset.
liqPriceWithoutPenaltyuint128The liquidation price of the position without the liquidation penalty.
userMaxLeverageuint256The maximum leverage allowed by the user for the newly created position.

_createOpenPendingAction

Prepares the pending action struct for an open position and adds it to the queue.

function _createOpenPendingAction(
    address to,
    address validator,
    uint64 securityDepositValue,
    Types.InitiateOpenPositionData memory data
) public returns (uint256 amountToRefund_);

Parameters

NameTypeDescription
toaddressThe address that will be the owner of the position.
validatoraddressThe address which is supposed to validate the position and receive the security deposit.
securityDepositValueuint64The value of the security deposit for the newly created pending action.
dataTypes.InitiateOpenPositionDataThe open position action data.

Returns

NameTypeDescription
amountToRefund_uint256The security deposit value of a stale pending action, if any was removed.

_applyPnlAndFunding

Computes the profits and losses on the long side, calculates the funding, applies protocol fees, updates the liquidation multiplier and determines the temporary new balances for each side.

This function updates the state of _lastPrice, _lastUpdateTimestamp, _lastFunding, but does not update the balances. This is left to the caller.

function _applyPnlAndFunding(uint128 currentPrice, uint128 timestamp)
    public
    returns (Types.ApplyPnlAndFundingData memory data_);

Parameters

NameTypeDescription
currentPriceuint128The current price.
timestampuint128The timestamp of the current price.

Returns

NameTypeDescription
data_Types.ApplyPnlAndFundingDataThe data containing the temporary long balance, the temporary vault balance, the last price and a flag indicating if the price is recent.

_removeStalePendingAction

Removes the pending action from the queue if its tick version doesn't match the current tick version, indicating that the tick was liquidated.

This is only applicable to ValidateOpenPosition pending actions.

function _removeStalePendingAction(address validator) public returns (uint256 securityDepositValue_);

Parameters

NameTypeDescription
validatoraddressThe address associated with the pending action.

Returns

NameTypeDescription
securityDepositValue_uint256The security deposit value of the removed stale pending action.

_addPendingAction

Adds a pending action to the queue and removes a possible stale pending action.

Reverts if there is already a pending action for this user.

function _addPendingAction(address validator, Types.PendingAction memory action)
    public
    returns (uint256 amountToRefund_);

Parameters

NameTypeDescription
validatoraddressThe address which is supposed to validate the position and receive the security deposit.
actionTypes.PendingActionThe pending action struct.

Returns

NameTypeDescription
amountToRefund_uint256The security deposit value of a stale pending action, if any was removed.

_removeBlockedPendingAction

Removes a blocked pending action and performs the minimal amount of cleanup necessary.

This function should only be called by the owner of the protocol, it serves as an escape hatch if a pending action ever gets stuck due to something reverting unexpectedly. From the user action timestamp, the caller must wait at least REMOVE_BLOCKED_PENDING_ACTIONS_DELAY after both _lowLatencyValidatorDeadline and _onChainValidatorDeadline.

function _removeBlockedPendingAction(uint128 rawIndex, address payable to, bool cleanup) public;

Parameters

NameTypeDescription
rawIndexuint128The raw index of the pending action in the queue.
toaddress payableThe recipient of the funds, which may include security deposit, assets and USDN tokens.
cleanupboolIf true, will attempt to perform more cleanup at the risk of reverting. Always try true first.

_saveNewPosition

Saves a new long position in the protocol, adjusting the tick data and global variables.

This method does not update the long balance.

function _saveNewPosition(int24 tick, Types.Position memory long, uint24 liquidationPenalty)
    public
    returns (uint256 tickVersion_, uint256 index_, HugeUint.Uint512 memory liqMultiplierAccumulator_);

Parameters

NameTypeDescription
tickint24The tick to hold the new position.
longTypes.PositionThe position to save.
liquidationPenaltyuint24The liquidation penalty for the tick.

Returns

NameTypeDescription
tickVersion_uint256The version of the tick.
index_uint256The index of the position in the tick array.
liqMultiplierAccumulator_HugeUint.Uint512The updated liquidation multiplier accumulator.

_getPendingActionOrRevert

Gets the pending action for a validator.

Reverts if there is no pending action for the validator.

function _getPendingActionOrRevert(address validator)
    public
    view
    returns (Types.PendingAction memory action_, uint128 rawIndex_);

Parameters

NameTypeDescription
validatoraddressThe address which is supposed to validate the position and receive the security deposit.

Returns

NameTypeDescription
action_Types.PendingActionThe pending action struct.
rawIndex_uint128The raw index of the pending action in the queue.

_fundingAsset

Gets the predicted value of the funding (in asset units) since the last state update for the given timestamp.

If the provided timestamp is older than the last state update, the result will be zero.

function _fundingAsset(uint128 timestamp, int256 ema)
    internal
    view
    returns (int256 fundingAsset_, int256 fundingPerDay_);

Parameters

NameTypeDescription
timestampuint128The targeted timestamp.
emaint256The EMA of the funding rate.

Returns

NameTypeDescription
fundingAsset_int256The number of asset tokens of funding (with asset decimals).
fundingPerDay_int256The funding rate (per day) with FUNDING_RATE_DECIMALS decimals.

_updateEMA

Updates the Exponential Moving Average (EMA) of the funding rate (per day).

This function is called every time the protocol state is updated. All required checks are done in the caller function _applyPnlAndFunding. If the number of seconds elapsed is greater than or equal to the EMA period, the EMA is updated to the last funding value.

function _updateEMA(int256 fundingPerDay, uint128 secondsElapsed) internal;

Parameters

NameTypeDescription
fundingPerDayint256The funding rate per day that was just calculated for the elapsed period.
secondsElapseduint128The number of seconds elapsed since the last protocol action.

_calculateFee

Calculates the protocol fee and apply it to the funding asset amount.

The funding factor is only adjusted by the fee rate when the funding is negative (vault pays to the long side).

function _calculateFee(int256 fundAsset) internal returns (int256 fee_, int256 fundAssetWithFee_);

Parameters

NameTypeDescription
fundAssetint256The funding asset amount to be used for the fee calculation.

Returns

NameTypeDescription
fee_int256The absolute value of the calculated fee.
fundAssetWithFee_int256The updated funding asset amount after applying the fee.

_createInitialDeposit

Creates the initial deposit.

To be called from initialize.

function _createInitialDeposit(uint128 amount, uint128 price) internal;

Parameters

NameTypeDescription
amountuint128The initial deposit amount.
priceuint128The current asset price.

_createInitialPosition

Creates the initial long position.

To be called from initialize.

function _createInitialPosition(uint128 amount, uint128 price, int24 tick, uint128 totalExpo) internal;

Parameters

NameTypeDescription
amountuint128The initial position amount.
priceuint128The current asset price.
tickint24The tick corresponding where the position should be stored.
totalExpouint128The total expo of the position.

_getPendingAction

Gets the possible pending action for a validator.

Checks for the presence of a pending action for a validator, compares action_.action to Types.ProtocolAction.None. There is a pending action only if the action is different from Types.ProtocolAction.None.

function _getPendingAction(address validator)
    internal
    view
    returns (Types.PendingAction memory action_, uint128 rawIndex_);

Parameters

NameTypeDescription
validatoraddressThe address of the pending action which is supposed to validate the position and receive the security deposit.

Returns

NameTypeDescription
action_Types.PendingActionThe pending action struct if any, otherwise a zero-initialized struct.
rawIndex_uint128The raw index of the pending action in the queue.

_checkInitImbalance

Checks if the initialize parameters lead to a balanced protocol.

Reverts if the imbalance is exceeded for the deposit or open long actions.

function _checkInitImbalance(uint128 positionTotalExpo, uint128 longAmount, uint128 depositAmount) internal view;

Parameters

NameTypeDescription
positionTotalExpouint128The total expo of the deployer's long position.
longAmountuint128The amount (collateral) of the deployer's long position.
depositAmountuint128The amount of assets for the deployer's deposit.

_fundingPerDay

Computes the funding rate per day and the old long exposure.

function _fundingPerDay(int256 ema) internal view returns (int256 fundingPerDay_, int256 oldLongExpo_);

Parameters

NameTypeDescription
emaint256The EMA of the funding rate per day.

Returns

NameTypeDescription
fundingPerDay_int256The funding rate per day with FUNDING_RATE_DECIMALS decimals.
oldLongExpo_int256The old long trading expo.

_funding

Computes the funding value, funding rate value and the old long exposure.

Reverts if timestamp < s._lastUpdateTimestamp.

function _funding(uint128 timestamp, int256 ema)
    internal
    view
    returns (int256 funding_, int256 fundingPerDay_, int256 oldLongExpo_);

Parameters

NameTypeDescription
timestampuint128The current timestamp.
emaint256The EMA of the funding rate per day.

Returns

NameTypeDescription
funding_int256The funding (proportion of long trading expo that needs to be transferred from one side to the other) with FUNDING_RATE_DECIMALS decimals. If positive, long side pays to vault side, otherwise it's the opposite.
fundingPerDay_int256The funding rate (per day) with FUNDING_RATE_DECIMALS decimals.
oldLongExpo_int256The old long trading expo.

_calcEMA

Calculates the new Exponential Moving Average.

function _calcEMA(int256 fundingPerDay, uint128 secondsElapsed, uint128 emaPeriod, int256 previousEMA)
    internal
    pure
    returns (int256 newEMA_);

Parameters

NameTypeDescription
fundingPerDayint256The funding per day.
secondsElapseduint128The number of seconds elapsed to be taken into account.
emaPerioduint128The current EMA period.
previousEMAint256The previous EMA value.

Returns

NameTypeDescription
newEMA_int256The new EMA value.

_calcMaxLongBalance

Calculates the maximum value of the long balance for the provided total expo.

function _calcMaxLongBalance(uint256 totalExpo) internal pure returns (uint256 maxLongBalance_);

Parameters

NameTypeDescription
totalExpouint256The total expo of the long side of the protocol.

Returns

NameTypeDescription
maxLongBalance_uint256The maximum value the long balance can reach.