UsdnProtocolUtilsLibrary

Git Source

A library of utility functions for the USDN protocol. This library is not intended to be deployed as an external library.

All functions in this library must be marked as "internal".

State Variables

STORAGE_MAIN

Constant representing the storage slot for the protocol main storage.

Calculated as: keccak256(abi.encode(uint256(keccak256("UsdnProtocol.storage.main")) - 1)) & ~bytes32(uint256(0xff))

bytes32 private constant STORAGE_MAIN = 0xd143a936a6a372725e12535db83a2cfabcb3715dfd88bc350da3399604dc9700;

Functions

_getMainStorage

Gets the main storage pointer.

function _getMainStorage() internal pure returns (Types.Storage storage s_);

Returns

NameTypeDescription
s_Types.StorageThe pointer to the main storage structure.

_refundExcessEther

Refunds excess Ether to prevent unintended locking of funds.

function _refundExcessEther(uint256 securityDepositValue, uint256 amountToRefund, uint256 balanceBefore) internal;

Parameters

NameTypeDescription
securityDepositValueuint256The security deposit for the current action (zero for validation actions).
amountToRefunduint256The amount to refund to the user: the security deposit when executing an action for another user, and/or the initialization security deposit in the case of a validation action.
balanceBeforeuint256The contract's balance before the action.

_refundEther

Refunds Ether to a specified address.

function _refundEther(uint256 amount, address payable to) internal;

Parameters

NameTypeDescription
amountuint256The amount of Ether to refund.
toaddress payableThe address receiving the refund.

_checkPendingFee

Distributes the protocol fee to the fee collector if the pending amount exceeds the threshold.

Attempts to invoke the feeCollectorCallback function on the fee collector if supported.

function _checkPendingFee() internal;

_getOraclePrice

Gets and validate the oracle price for a specified action and timestamp.

function _getOraclePrice(Types.ProtocolAction action, uint256 timestamp, bytes32 actionId, bytes calldata priceData)
    internal
    returns (PriceInfo memory price_);

Parameters

NameTypeDescription
actionTypes.ProtocolActionThe protocol action being performed.
timestampuint256The timestamp for which the price is queried.
actionIdbytes32The unique identifier of the action.
priceDatabytesThe encoded oracle price data.

Returns

NameTypeDescription
price_PriceInfoThe validated price information.

_clearPendingAction

Clears the pending action of a user.

function _clearPendingAction(address user, uint128 rawIndex) internal;

Parameters

NameTypeDescription
useraddressThe user's address.
rawIndexuint128The rawIndex of the pending action in the queue.

_longAssetAvailable

Calculates the long balance, including unreflected PnL (excluding funding).

This function uses the latest total exposure, balance, and stored price as reference values. It adjusts the balance by adding the PnL resulting from the price change.

function _longAssetAvailable(uint128 currentPrice) internal view returns (int256 available_);

Parameters

NameTypeDescription
currentPriceuint128The current price of the asset.

Returns

NameTypeDescription
available_int256The updated balance on the long side.

_tickHash

Calculates the hash of the given tick number and its current version.

function _tickHash(int24 tick) internal view returns (bytes32 hash_, uint256 version_);

Parameters

NameTypeDescription
tickint24The tick number.

Returns

NameTypeDescription
hash_bytes32The hash of the tick.
version_uint256The version of the tick.

_calcBitmapIndexFromTick

Calculates the corresponding index of the given tick in the Bitmap, based on the storage tick spacing.

function _calcBitmapIndexFromTick(int24 tick) internal view returns (uint256 index_);

Parameters

NameTypeDescription
tickint24The tick number, a multiple of the tick spacing.

Returns

NameTypeDescription
index_uint256The index into the Bitmap.

_getEffectivePriceForTick

Gets the effective price, accounting for funding, for a given tick.

function _getEffectivePriceForTick(int24 tick) internal view returns (uint128 price_);

Parameters

NameTypeDescription
tickint24The tick number.

Returns

NameTypeDescription
price_uint128The effective price for the tick.

_tickHash

Generates a hash based on the tick and a version.

function _tickHash(int24 tick, uint256 version) internal pure returns (bytes32);

Parameters

NameTypeDescription
tickint24The tick number.
versionuint256The tick version.

Returns

NameTypeDescription
<none>bytes32The hash value.

_toInt256

Converts a uint128 to an int256.

function _toInt256(uint128 x) internal pure returns (int256);

Parameters

NameTypeDescription
xuint128The uint128 value to convert.

Returns

NameTypeDescription
<none>int256The resulting int256 value.

_positionValueOptimized

Optimized position value calculation when posTotalExpo is known to be a uint128 and currentPrice is guaranteed to be above liqPriceWithoutPenalty.

function _positionValueOptimized(uint128 posTotalExpo, uint128 currentPrice, uint128 liqPriceWithoutPenalty)
    internal
    pure
    returns (uint256 posValue_);

Parameters

NameTypeDescription
posTotalExpouint128The total exposure of the position.
currentPriceuint128The current asset price.
liqPriceWithoutPenaltyuint128The liquidation price without penalty.

Returns

NameTypeDescription
posValue_uint256The calculated position value.

_calcTickWithoutPenalty

Calculates the tick number without considering the liquidation penalty.

function _calcTickWithoutPenalty(int24 tick, uint24 liquidationPenalty) internal pure returns (int24 tick_);

Parameters

NameTypeDescription
tickint24The tick number that holds the position.
liquidationPenaltyuint24The liquidation penalty, measured in ticks.

Returns

NameTypeDescription
tick_int24The tick number adjusted to exclude the liquidation penalty.

_getLiquidationPrice

Calculates the theoretical liquidation price of a position using its entry price and leverage.

function _getLiquidationPrice(uint128 startPrice, uint128 leverage) internal pure returns (uint128 price_);

Parameters

NameTypeDescription
startPriceuint128The entry price of the position.
leverageuint128The leverage of the position.

Returns

NameTypeDescription
price_uint128The computed liquidation price.

_getLeverage

Calculates the leverage of a position using its entry price and liquidation price.

The calculation does not take into account the liquidation penalty.

function _getLeverage(uint128 startPrice, uint128 liquidationPrice) internal pure returns (uint256 leverage_);

Parameters

NameTypeDescription
startPriceuint128The entry price of the position.
liquidationPriceuint128The price at which the position would be liquidated.

Returns

NameTypeDescription
leverage_uint256The computed leverage value.

_convertLongPendingAction

Converts the given LongPendingAction to a PendingAction.

function _convertLongPendingAction(Types.LongPendingAction memory action)
    internal
    pure
    returns (Types.PendingAction memory pendingAction_);

Parameters

NameTypeDescription
actionTypes.LongPendingActionThe long pending action.

Returns

NameTypeDescription
pendingAction_Types.PendingActionThe converted untyped pending action.

_convertWithdrawalPendingAction

Converts the given WithdrawalPendingAction to a PendingAction.

function _convertWithdrawalPendingAction(Types.WithdrawalPendingAction memory action)
    internal
    pure
    returns (Types.PendingAction memory pendingAction_);

Parameters

NameTypeDescription
actionTypes.WithdrawalPendingActionThe withdrawal pending action.

Returns

NameTypeDescription
pendingAction_Types.PendingActionThe converted untyped pending action.

_convertDepositPendingAction

Converts the given DepositPendingAction to a PendingAction.

function _convertDepositPendingAction(Types.DepositPendingAction memory action)
    internal
    pure
    returns (Types.PendingAction memory pendingAction_);

Parameters

NameTypeDescription
actionTypes.DepositPendingActionThe deposit pending action.

Returns

NameTypeDescription
pendingAction_Types.PendingActionThe converted untyped pending action.

_toLongPendingAction

Converts the given PendingAction to a LongPendingAction.

function _toLongPendingAction(Types.PendingAction memory action)
    internal
    pure
    returns (Types.LongPendingAction memory longAction_);

Parameters

NameTypeDescription
actionTypes.PendingActionThe untyped pending action.

Returns

NameTypeDescription
longAction_Types.LongPendingActionThe converted long pending action.

_toDepositPendingAction

Converts the given PendingAction to a DepositPendingAction.

function _toDepositPendingAction(Types.PendingAction memory action)
    internal
    pure
    returns (Types.DepositPendingAction memory vaultAction_);

Parameters

NameTypeDescription
actionTypes.PendingActionThe untyped pending action.

Returns

NameTypeDescription
vaultAction_Types.DepositPendingActionThe converted deposit pending action.

_toWithdrawalPendingAction

Converts the given PendingAction to a WithdrawalPendingAction.

function _toWithdrawalPendingAction(Types.PendingAction memory action)
    internal
    pure
    returns (Types.WithdrawalPendingAction memory vaultAction_);

Parameters

NameTypeDescription
actionTypes.PendingActionThe untyped pending action.

Returns

NameTypeDescription
vaultAction_Types.WithdrawalPendingActionThe converted withdrawal pending action.

_calcBitmapIndexFromTick

Calculates the corresponding index of the given tick in the Bitmap, based on the specified tick spacing.

function _calcBitmapIndexFromTick(int24 tick, int24 tickSpacing) internal pure returns (uint256 index_);

Parameters

NameTypeDescription
tickint24The tick, which must be a multiple of tickSpacing.
tickSpacingint24The tick spacing to use.

Returns

NameTypeDescription
index_uint256The corresponding index into the Bitmap.

_mergeWithdrawalAmountParts

Merges the two parts of the withdrawal amount (USDN shares) stored in the WithdrawalPendingAction.

function _mergeWithdrawalAmountParts(uint24 sharesLSB, uint128 sharesMSB) internal pure returns (uint256 usdnShares_);

Parameters

NameTypeDescription
sharesLSBuint24The lower 24 bits of the USDN shares.
sharesMSBuint128The higher bits of the USDN shares.

Returns

NameTypeDescription
usdnShares_uint256The amount of USDN shares.

_longAssetAvailable

Calculates the updated balance of the long side, considering unreflected PnL (excluding funding).

function _longAssetAvailable(uint256 totalExpo, uint256 balanceLong, uint128 newPrice, uint128 oldPrice)
    internal
    pure
    returns (int256 available_);

Parameters

NameTypeDescription
totalExpouint256The total exposure of the long side.
balanceLonguint256The previous balance of the long side.
newPriceuint128The updated price of the asset.
oldPriceuint128The previous price used to calculate the prior balance.

Returns

NameTypeDescription
available_int256The updated balance of the long side.

_calcImbalanceCloseBps

Calculates the imbalance between the vault and long sides.

A positive value indicates the long trading exposure is smaller than the vault's. If the trading exposure is equal to 0, the imbalance is infinite and int256.max is returned.

function _calcImbalanceCloseBps(int256 vaultBalance, int256 longBalance, uint256 totalExpo)
    internal
    pure
    returns (int256 imbalanceBps_);

Parameters

NameTypeDescription
vaultBalanceint256The balance of the vault.
longBalanceint256The balance of the long side.
totalExpouint256The total exposure of the long side.

Returns

NameTypeDescription
imbalanceBps_int256The imbalance, expressed in basis points.

_calcPositionTotalExpo

Calculates the total exposure of a position.

Reverts if startPrice <= liquidationPrice.

function _calcPositionTotalExpo(uint128 amount, uint128 startPrice, uint128 liquidationPrice)
    internal
    pure
    returns (uint128 totalExpo_);

Parameters

NameTypeDescription
amountuint128The amount of assets used as collateral.
startPriceuint128The asset price when the position was created.
liquidationPriceuint128The liquidation price of the position.

Returns

NameTypeDescription
totalExpo_uint128The total exposure of the position.

_positionValue

Calculates the value of a position based on its liquidation price and the current asset price.

function _positionValue(uint128 positionTotalExpo, uint128 currentPrice, uint128 liqPriceWithoutPenalty)
    internal
    pure
    returns (int256 value_);

Parameters

NameTypeDescription
positionTotalExpouint128The total exposure of the position.
currentPriceuint128The current price of the asset.
liqPriceWithoutPenaltyuint128The liquidation price of the position without the liquidation penalty.

Returns

NameTypeDescription
value_int256The position's value. Negative values indicate bad debt.

_calcFixedPrecisionMultiplier

Calculates a fixed-precision representation of the liquidation price multiplier.

function _calcFixedPrecisionMultiplier(uint256 assetPrice, uint256 longTradingExpo, HugeUint.Uint512 memory accumulator)
    internal
    pure
    returns (uint256 multiplier_);

Parameters

NameTypeDescription
assetPriceuint256The current price of the asset.
longTradingExpouint256The trading exposure of the long side.
accumulatorHugeUint.Uint512The liquidation multiplier accumulator.

Returns

NameTypeDescription
multiplier_uint256The liquidation price multiplier.

_adjustPrice

Variant of _adjustPrice when a fixed precision representation of the liquidation multiplier is known.

function _adjustPrice(uint256 unadjustedPrice, uint256 liqMultiplier) internal pure returns (uint128 price_);

Parameters

NameTypeDescription
unadjustedPriceuint256The unadjusted price for the tick.
liqMultiplieruint256The liquidation price multiplier.

Returns

NameTypeDescription
price_uint128The adjusted price for the tick.

_calcMintUsdnShares

Calculates the amount of USDN shares to mint for a given amount of assets.

function _calcMintUsdnShares(uint256 amount, uint256 vaultBalance, uint256 usdnTotalShares)
    internal
    pure
    returns (uint256 toMint_);

Parameters

NameTypeDescription
amountuint256The amount of assets to be converted into USDN.
vaultBalanceuint256The current balance of the vault.
usdnTotalSharesuint256The total supply of USDN shares.

Returns

NameTypeDescription
toMint_uint256The amount of USDN shares to mint.

_calcSdexToBurn

Calculates the amount of SDEX tokens to burn when minting USDN tokens.

The result is rounded up to ensure at least 1 wei of SDEX is burned.

function _calcSdexToBurn(uint256 usdnAmount, uint64 sdexBurnRatio) internal pure returns (uint256 sdexToBurn_);

Parameters

NameTypeDescription
usdnAmountuint256The amount of USDN to be minted.
sdexBurnRatiouint64The ratio of SDEX burned per minted USDN.

Returns

NameTypeDescription
sdexToBurn_uint256The amount of SDEX tokens to burn.

_calcActionId

Calculates a unique identifier for a pending action.

This identifier can be used by the oracle middleware to link an Initiate call with the corresponding Validate call.

function _calcActionId(address validator, uint128 initiateTimestamp) internal pure returns (bytes32 actionId_);

Parameters

NameTypeDescription
validatoraddressThe address of the validator.
initiateTimestampuint128The timestamp of the Initiate action.

Returns

NameTypeDescription
actionId_bytes32The unique action ID.

_calcAmountToWithdraw

Calculates the amount of assets received when burning USDN shares, accounting for fees.

function _calcAmountToWithdraw(
    uint256 usdnShares,
    uint256 vaultAvailableBalance,
    uint256 usdnSharesTotalSupply,
    uint256 feeBps
) internal pure returns (uint256 expectedAssetsAmount_);

Parameters

NameTypeDescription
usdnSharesuint256The amount of USDN shares to burn.
vaultAvailableBalanceuint256The available amount of assets in the vault.
usdnSharesTotalSupplyuint256The total supply of USDN shares.
feeBpsuint256The fee in basis points.

Returns

NameTypeDescription
expectedAssetsAmount_uint256The expected amount of assets to be received after deducting fees.

_vaultAssetAvailable

Calculates the available balance in the vault for a given price, excluding funding effects.

function _vaultAssetAvailable(
    uint256 totalExpo,
    uint256 balanceVault,
    uint256 balanceLong,
    uint128 newPrice,
    uint128 oldPrice
) internal pure returns (int256 available_);

Parameters

NameTypeDescription
totalExpouint256The total long exposure.
balanceVaultuint256The previous balance of the vault.
balanceLonguint256The previous balance of the long side.
newPriceuint128The updated price.
oldPriceuint128The price used when the previous balances were calculated.

Returns

NameTypeDescription
available_int256The available balance in the vault.

_adjustPrice

Adjusts the tick price by accounting for the effects of funding.

function _adjustPrice(
    uint256 unadjustedPrice,
    uint256 assetPrice,
    uint256 longTradingExpo,
    HugeUint.Uint512 memory accumulator
) internal pure returns (uint128 price_);

Parameters

NameTypeDescription
unadjustedPriceuint256The tick's unadjusted price.
assetPriceuint256The current price of the asset.
longTradingExpouint256The trading exposure of the long side.
accumulatorHugeUint.Uint512The liquidation multiplier accumulator.

Returns

NameTypeDescription
price_uint128The adjusted tick price.

_transferCallback

Invokes a callback on the msg.sender to transfer assets and verifies that they were received.

function _transferCallback(IERC20Metadata token, uint256 amount, address to) internal;

Parameters

NameTypeDescription
tokenIERC20MetadataThe ERC-20 token to transfer.
amountuint256The amount of tokens to transfer.
toaddressThe recipient's address.

_usdnTransferCallback

Invokes a callback on the msg.sender to transfer USDN shares and verifies that they were received.

function _usdnTransferCallback(IUsdn usdn, uint256 shares) internal;

Parameters

NameTypeDescription
usdnIUsdnThe address of the USDN token contract.
sharesuint256The amount of USDN shares to transfer.

_getEffectivePriceForTick

Calculates the effective price for a tick, adjusted for funding effects.

function _getEffectivePriceForTick(
    int24 tick,
    uint256 assetPrice,
    uint256 longTradingExpo,
    HugeUint.Uint512 memory accumulator
) internal pure returns (uint128 price_);

Parameters

NameTypeDescription
tickint24The tick number.
assetPriceuint256The current price of the asset.
longTradingExpouint256The trading exposure of the long side.
accumulatorHugeUint.Uint512The liquidation multiplier accumulator.

Returns

NameTypeDescription
price_uint128The adjusted price for the tick.

_getEffectivePriceForTick

Variant of _getEffectivePriceForTick when a fixed precision representation of the liquidation multiplier is known.

function _getEffectivePriceForTick(int24 tick, uint256 liqMultiplier) internal pure returns (uint128 price_);

Parameters

NameTypeDescription
tickint24The tick number.
liqMultiplieruint256The liquidation price multiplier.

Returns

NameTypeDescription
price_uint128The adjusted price for the tick.