UsdnProtocolUtilsLibrary
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
Name | Type | Description |
---|---|---|
s_ | Types.Storage | The 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
Name | Type | Description |
---|---|---|
securityDepositValue | uint256 | The security deposit for the current action (zero for validation actions). |
amountToRefund | uint256 | The 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. |
balanceBefore | uint256 | The contract's balance before the action. |
_refundEther
Refunds Ether to a specified address.
function _refundEther(uint256 amount, address payable to) internal;
Parameters
Name | Type | Description |
---|---|---|
amount | uint256 | The amount of Ether to refund. |
to | address payable | The 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
Name | Type | Description |
---|---|---|
action | Types.ProtocolAction | The protocol action being performed. |
timestamp | uint256 | The timestamp for which the price is queried. |
actionId | bytes32 | The unique identifier of the action. |
priceData | bytes | The encoded oracle price data. |
Returns
Name | Type | Description |
---|---|---|
price_ | PriceInfo | The validated price information. |
_clearPendingAction
Clears the pending action of a user.
function _clearPendingAction(address user, uint128 rawIndex) internal;
Parameters
Name | Type | Description |
---|---|---|
user | address | The user's address. |
rawIndex | uint128 | The 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
Name | Type | Description |
---|---|---|
currentPrice | uint128 | The current price of the asset. |
Returns
Name | Type | Description |
---|---|---|
available_ | int256 | The 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
Name | Type | Description |
---|---|---|
tick | int24 | The tick number. |
Returns
Name | Type | Description |
---|---|---|
hash_ | bytes32 | The hash of the tick. |
version_ | uint256 | The 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
Name | Type | Description |
---|---|---|
tick | int24 | The tick number, a multiple of the tick spacing. |
Returns
Name | Type | Description |
---|---|---|
index_ | uint256 | The 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
Name | Type | Description |
---|---|---|
tick | int24 | The tick number. |
Returns
Name | Type | Description |
---|---|---|
price_ | uint128 | The 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
Name | Type | Description |
---|---|---|
tick | int24 | The tick number. |
version | uint256 | The tick version. |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | The hash value. |
_toInt256
Converts a uint128
to an int256
.
function _toInt256(uint128 x) internal pure returns (int256);
Parameters
Name | Type | Description |
---|---|---|
x | uint128 | The uint128 value to convert. |
Returns
Name | Type | Description |
---|---|---|
<none> | int256 | The 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
Name | Type | Description |
---|---|---|
posTotalExpo | uint128 | The total exposure of the position. |
currentPrice | uint128 | The current asset price. |
liqPriceWithoutPenalty | uint128 | The liquidation price without penalty. |
Returns
Name | Type | Description |
---|---|---|
posValue_ | uint256 | The 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
Name | Type | Description |
---|---|---|
tick | int24 | The tick number that holds the position. |
liquidationPenalty | uint24 | The liquidation penalty, measured in ticks. |
Returns
Name | Type | Description |
---|---|---|
tick_ | int24 | The 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
Name | Type | Description |
---|---|---|
startPrice | uint128 | The entry price of the position. |
leverage | uint128 | The leverage of the position. |
Returns
Name | Type | Description |
---|---|---|
price_ | uint128 | The 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
Name | Type | Description |
---|---|---|
startPrice | uint128 | The entry price of the position. |
liquidationPrice | uint128 | The price at which the position would be liquidated. |
Returns
Name | Type | Description |
---|---|---|
leverage_ | uint256 | The 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
Name | Type | Description |
---|---|---|
action | Types.LongPendingAction | The long pending action. |
Returns
Name | Type | Description |
---|---|---|
pendingAction_ | Types.PendingAction | The 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
Name | Type | Description |
---|---|---|
action | Types.WithdrawalPendingAction | The withdrawal pending action. |
Returns
Name | Type | Description |
---|---|---|
pendingAction_ | Types.PendingAction | The 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
Name | Type | Description |
---|---|---|
action | Types.DepositPendingAction | The deposit pending action. |
Returns
Name | Type | Description |
---|---|---|
pendingAction_ | Types.PendingAction | The 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
Name | Type | Description |
---|---|---|
action | Types.PendingAction | The untyped pending action. |
Returns
Name | Type | Description |
---|---|---|
longAction_ | Types.LongPendingAction | The 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
Name | Type | Description |
---|---|---|
action | Types.PendingAction | The untyped pending action. |
Returns
Name | Type | Description |
---|---|---|
vaultAction_ | Types.DepositPendingAction | The 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
Name | Type | Description |
---|---|---|
action | Types.PendingAction | The untyped pending action. |
Returns
Name | Type | Description |
---|---|---|
vaultAction_ | Types.WithdrawalPendingAction | The 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
Name | Type | Description |
---|---|---|
tick | int24 | The tick, which must be a multiple of tickSpacing . |
tickSpacing | int24 | The tick spacing to use. |
Returns
Name | Type | Description |
---|---|---|
index_ | uint256 | The 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
Name | Type | Description |
---|---|---|
sharesLSB | uint24 | The lower 24 bits of the USDN shares. |
sharesMSB | uint128 | The higher bits of the USDN shares. |
Returns
Name | Type | Description |
---|---|---|
usdnShares_ | uint256 | The 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
Name | Type | Description |
---|---|---|
totalExpo | uint256 | The total exposure of the long side. |
balanceLong | uint256 | The previous balance of the long side. |
newPrice | uint128 | The updated price of the asset. |
oldPrice | uint128 | The previous price used to calculate the prior balance. |
Returns
Name | Type | Description |
---|---|---|
available_ | int256 | The 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
Name | Type | Description |
---|---|---|
vaultBalance | int256 | The balance of the vault. |
longBalance | int256 | The balance of the long side. |
totalExpo | uint256 | The total exposure of the long side. |
Returns
Name | Type | Description |
---|---|---|
imbalanceBps_ | int256 | The 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
Name | Type | Description |
---|---|---|
amount | uint128 | The amount of assets used as collateral. |
startPrice | uint128 | The asset price when the position was created. |
liquidationPrice | uint128 | The liquidation price of the position. |
Returns
Name | Type | Description |
---|---|---|
totalExpo_ | uint128 | The 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
Name | Type | Description |
---|---|---|
positionTotalExpo | uint128 | The total exposure of the position. |
currentPrice | uint128 | The current price of the asset. |
liqPriceWithoutPenalty | uint128 | The liquidation price of the position without the liquidation penalty. |
Returns
Name | Type | Description |
---|---|---|
value_ | int256 | The 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
Name | Type | Description |
---|---|---|
assetPrice | uint256 | The current price of the asset. |
longTradingExpo | uint256 | The trading exposure of the long side. |
accumulator | HugeUint.Uint512 | The liquidation multiplier accumulator. |
Returns
Name | Type | Description |
---|---|---|
multiplier_ | uint256 | The 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
Name | Type | Description |
---|---|---|
unadjustedPrice | uint256 | The unadjusted price for the tick. |
liqMultiplier | uint256 | The liquidation price multiplier. |
Returns
Name | Type | Description |
---|---|---|
price_ | uint128 | The 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
Name | Type | Description |
---|---|---|
amount | uint256 | The amount of assets to be converted into USDN. |
vaultBalance | uint256 | The current balance of the vault. |
usdnTotalShares | uint256 | The total supply of USDN shares. |
Returns
Name | Type | Description |
---|---|---|
toMint_ | uint256 | The 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
Name | Type | Description |
---|---|---|
usdnAmount | uint256 | The amount of USDN to be minted. |
sdexBurnRatio | uint64 | The ratio of SDEX burned per minted USDN. |
Returns
Name | Type | Description |
---|---|---|
sdexToBurn_ | uint256 | The 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
Name | Type | Description |
---|---|---|
validator | address | The address of the validator. |
initiateTimestamp | uint128 | The timestamp of the Initiate action. |
Returns
Name | Type | Description |
---|---|---|
actionId_ | bytes32 | The 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
Name | Type | Description |
---|---|---|
usdnShares | uint256 | The amount of USDN shares to burn. |
vaultAvailableBalance | uint256 | The available amount of assets in the vault. |
usdnSharesTotalSupply | uint256 | The total supply of USDN shares. |
feeBps | uint256 | The fee in basis points. |
Returns
Name | Type | Description |
---|---|---|
expectedAssetsAmount_ | uint256 | The 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
Name | Type | Description |
---|---|---|
totalExpo | uint256 | The total long exposure. |
balanceVault | uint256 | The previous balance of the vault. |
balanceLong | uint256 | The previous balance of the long side. |
newPrice | uint128 | The updated price. |
oldPrice | uint128 | The price used when the previous balances were calculated. |
Returns
Name | Type | Description |
---|---|---|
available_ | int256 | The 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
Name | Type | Description |
---|---|---|
unadjustedPrice | uint256 | The tick's unadjusted price. |
assetPrice | uint256 | The current price of the asset. |
longTradingExpo | uint256 | The trading exposure of the long side. |
accumulator | HugeUint.Uint512 | The liquidation multiplier accumulator. |
Returns
Name | Type | Description |
---|---|---|
price_ | uint128 | The 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
Name | Type | Description |
---|---|---|
token | IERC20Metadata | The ERC-20 token to transfer. |
amount | uint256 | The amount of tokens to transfer. |
to | address | The 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
Name | Type | Description |
---|---|---|
usdn | IUsdn | The address of the USDN token contract. |
shares | uint256 | The 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
Name | Type | Description |
---|---|---|
tick | int24 | The tick number. |
assetPrice | uint256 | The current price of the asset. |
longTradingExpo | uint256 | The trading exposure of the long side. |
accumulator | HugeUint.Uint512 | The liquidation multiplier accumulator. |
Returns
Name | Type | Description |
---|---|---|
price_ | uint128 | The 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
Name | Type | Description |
---|---|---|
tick | int24 | The tick number. |
liqMultiplier | uint256 | The liquidation price multiplier. |
Returns
Name | Type | Description |
---|---|---|
price_ | uint128 | The adjusted price for the tick. |