UsdnProtocolCoreLibrary
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
| Name | Type | Description |
|---|---|---|
to | address | The address that will receive the assets. |
validator | address | The validator for the pending action. |
posId | Types.PositionId | The unique identifier of the position. |
amountToClose | uint128 | The amount of collateral to remove from the position's amount. |
securityDepositValue | uint64 | The value of the security deposit for the newly created pending action. |
data | Types.ClosePositionData | The close position data. |
Returns
| Name | Type | Description |
|---|---|---|
amountToRefund_ | uint256 | The 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
| Name | Type | Description |
|---|---|---|
to | address | The recipient of the assets. |
validator | address | The address that is supposed to validate the withdrawal and receive the security deposit. |
usdnShares | uint152 | The amount of USDN shares to burn. |
securityDepositValue | uint64 | The value of the security deposit for the newly created pending action. |
data | Vault.WithdrawalData | The withdrawal action data. |
Returns
| Name | Type | Description |
|---|---|---|
amountToRefund_ | uint256 | Refund 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
| Name | Type | Description |
|---|---|---|
currentPrice | uint128 | The given asset price. |
timestamp | uint128 | The timestamp corresponding to the given price. |
Returns
| Name | Type | Description |
|---|---|---|
available_ | uint256 | The long balance value in assets. |
fee_ | int256 | The 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
| Name | Type | Description |
|---|---|---|
adjustedPrice | uint128 | The adjusted price of the asset. |
liqPriceWithoutPenalty | uint128 | The liquidation price of the position without the liquidation penalty. |
userMaxLeverage | uint256 | The 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
| Name | Type | Description |
|---|---|---|
to | address | The address that will be the owner of the position. |
validator | address | The address which is supposed to validate the position and receive the security deposit. |
securityDepositValue | uint64 | The value of the security deposit for the newly created pending action. |
data | Types.InitiateOpenPositionData | The open position action data. |
Returns
| Name | Type | Description |
|---|---|---|
amountToRefund_ | uint256 | The 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
| Name | Type | Description |
|---|---|---|
currentPrice | uint128 | The current price. |
timestamp | uint128 | The timestamp of the current price. |
Returns
| Name | Type | Description |
|---|---|---|
data_ | Types.ApplyPnlAndFundingData | The 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
| Name | Type | Description |
|---|---|---|
validator | address | The address associated with the pending action. |
Returns
| Name | Type | Description |
|---|---|---|
securityDepositValue_ | uint256 | The 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
| Name | Type | Description |
|---|---|---|
validator | address | The address which is supposed to validate the position and receive the security deposit. |
action | Types.PendingAction | The pending action struct. |
Returns
| Name | Type | Description |
|---|---|---|
amountToRefund_ | uint256 | The 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
| Name | Type | Description |
|---|---|---|
rawIndex | uint128 | The raw index of the pending action in the queue. |
to | address payable | The recipient of the funds, which may include security deposit, assets and USDN tokens. |
cleanup | bool | If 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
| Name | Type | Description |
|---|---|---|
tick | int24 | The tick to hold the new position. |
long | Types.Position | The position to save. |
liquidationPenalty | uint24 | The liquidation penalty for the tick. |
Returns
| Name | Type | Description |
|---|---|---|
tickVersion_ | uint256 | The version of the tick. |
index_ | uint256 | The index of the position in the tick array. |
liqMultiplierAccumulator_ | HugeUint.Uint512 | The 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
| Name | Type | Description |
|---|---|---|
validator | address | The address which is supposed to validate the position and receive the security deposit. |
Returns
| Name | Type | Description |
|---|---|---|
action_ | Types.PendingAction | The pending action struct. |
rawIndex_ | uint128 | The 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
| Name | Type | Description |
|---|---|---|
timestamp | uint128 | The targeted timestamp. |
ema | int256 | The EMA of the funding rate. |
Returns
| Name | Type | Description |
|---|---|---|
fundingAsset_ | int256 | The number of asset tokens of funding (with asset decimals). |
fundingPerDay_ | int256 | The 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
| Name | Type | Description |
|---|---|---|
fundingPerDay | int256 | The funding rate per day that was just calculated for the elapsed period. |
secondsElapsed | uint128 | The 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
| Name | Type | Description |
|---|---|---|
fundAsset | int256 | The funding asset amount to be used for the fee calculation. |
Returns
| Name | Type | Description |
|---|---|---|
fee_ | int256 | The absolute value of the calculated fee. |
fundAssetWithFee_ | int256 | The 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
| Name | Type | Description |
|---|---|---|
amount | uint128 | The initial deposit amount. |
price | uint128 | The 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
| Name | Type | Description |
|---|---|---|
amount | uint128 | The initial position amount. |
price | uint128 | The current asset price. |
tick | int24 | The tick corresponding where the position should be stored. |
totalExpo | uint128 | The 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
| Name | Type | Description |
|---|---|---|
validator | address | The address of the pending action which is supposed to validate the position and receive the security deposit. |
Returns
| Name | Type | Description |
|---|---|---|
action_ | Types.PendingAction | The pending action struct if any, otherwise a zero-initialized struct. |
rawIndex_ | uint128 | The 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
| Name | Type | Description |
|---|---|---|
positionTotalExpo | uint128 | The total expo of the deployer's long position. |
longAmount | uint128 | The amount (collateral) of the deployer's long position. |
depositAmount | uint128 | The 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
| Name | Type | Description |
|---|---|---|
ema | int256 | The EMA of the funding rate per day. |
Returns
| Name | Type | Description |
|---|---|---|
fundingPerDay_ | int256 | The funding rate per day with FUNDING_RATE_DECIMALS decimals. |
oldLongExpo_ | int256 | The 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
| Name | Type | Description |
|---|---|---|
timestamp | uint128 | The current timestamp. |
ema | int256 | The EMA of the funding rate per day. |
Returns
| Name | Type | Description |
|---|---|---|
funding_ | int256 | The 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_ | int256 | The funding rate (per day) with FUNDING_RATE_DECIMALS decimals. |
oldLongExpo_ | int256 | The 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
| Name | Type | Description |
|---|---|---|
fundingPerDay | int256 | The funding per day. |
secondsElapsed | uint128 | The number of seconds elapsed to be taken into account. |
emaPeriod | uint128 | The current EMA period. |
previousEMA | int256 | The previous EMA value. |
Returns
| Name | Type | Description |
|---|---|---|
newEMA_ | int256 | The 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
| Name | Type | Description |
|---|---|---|
totalExpo | uint256 | The total expo of the long side of the protocol. |
Returns
| Name | Type | Description |
|---|---|---|
maxLongBalance_ | uint256 | The maximum value the long balance can reach. |