IUsdnProtocolTypes

Git Source

Structs

Position

Information about a long user position.

struct Position {
    bool validated;
    uint40 timestamp;
    address user;
    uint128 totalExpo;
    uint128 amount;
}

Properties

NameTypeDescription
validatedboolWhether the position was validated.
timestampuint40The timestamp of the position start.
useraddressThe user's address.
totalExpouint128The total exposure of the position (0 for vault deposits). The product of the initial collateral and the initial leverage.
amountuint128The amount of initial collateral in the position.

PendingAction

A pending action in the queue.

struct PendingAction {
    ProtocolAction action;
    uint40 timestamp;
    uint24 var0;
    address to;
    address validator;
    uint64 securityDepositValue;
    int24 var1;
    uint128 var2;
    uint128 var3;
    uint256 var4;
    uint256 var5;
    uint256 var6;
    uint256 var7;
}

Properties

NameTypeDescription
actionProtocolActionThe action type.
timestampuint40The timestamp of the initiate action.
var0uint24See DepositPendingAction, WithdrawalPendingAction and LongPendingAction.
toaddressThe target of the action.
validatoraddressThe address that is supposed to validate the action.
securityDepositValueuint64The security deposit of the pending action.
var1int24See DepositPendingAction, WithdrawalPendingAction and LongPendingAction.
var2uint128See DepositPendingAction, WithdrawalPendingAction and LongPendingAction.
var3uint128See DepositPendingAction, WithdrawalPendingAction and LongPendingAction.
var4uint256See DepositPendingAction, WithdrawalPendingAction and LongPendingAction.
var5uint256See DepositPendingAction, WithdrawalPendingAction and LongPendingAction.
var6uint256See DepositPendingAction, WithdrawalPendingAction and LongPendingAction.
var7uint256See DepositPendingAction, WithdrawalPendingAction and LongPendingAction.

DepositPendingAction

A pending action in the queue for a vault deposit.

struct DepositPendingAction {
    ProtocolAction action;
    uint40 timestamp;
    uint24 feeBps;
    address to;
    address validator;
    uint64 securityDepositValue;
    uint24 _unused;
    uint128 amount;
    uint128 assetPrice;
    uint256 totalExpo;
    uint256 balanceVault;
    uint256 balanceLong;
    uint256 usdnTotalShares;
}

Properties

NameTypeDescription
actionProtocolActionThe action type.
timestampuint40The timestamp of the initiate action.
feeBpsuint24Fee for the deposit, in BPS.
toaddressThe recipient of the funds.
validatoraddressThe address that is supposed to validate the action.
securityDepositValueuint64The security deposit of the pending action.
_unuseduint24Unused field to align the struct to PendingAction.
amountuint128The amount of assets of the pending deposit.
assetPriceuint128The price of the asset at the time of the last update.
totalExpouint256The total exposure at the time of the last update.
balanceVaultuint256The balance of the vault at the time of the last update.
balanceLonguint256The balance of the long position at the time of the last update.
usdnTotalSharesuint256The total supply of USDN shares at the time of the action.

WithdrawalPendingAction

A pending action in the queue for a vault withdrawal.

struct WithdrawalPendingAction {
    ProtocolAction action;
    uint40 timestamp;
    uint24 feeBps;
    address to;
    address validator;
    uint64 securityDepositValue;
    uint24 sharesLSB;
    uint128 sharesMSB;
    uint128 assetPrice;
    uint256 totalExpo;
    uint256 balanceVault;
    uint256 balanceLong;
    uint256 usdnTotalShares;
}

Properties

NameTypeDescription
actionProtocolActionThe action type.
timestampuint40The timestamp of the initiate action.
feeBpsuint24Fee for the withdrawal, in BPS.
toaddressThe recipient of the funds.
validatoraddressThe address that is supposed to validate the action.
securityDepositValueuint64The security deposit of the pending action.
sharesLSBuint243 least significant bytes of the withdrawal shares amount (uint152).
sharesMSBuint12816 most significant bytes of the withdrawal shares amount (uint152).
assetPriceuint128The price of the asset at the time of the last update.
totalExpouint256The total exposure at the time of the last update.
balanceVaultuint256The balance of the vault at the time of the last update.
balanceLonguint256The balance of the long position at the time of the last update.
usdnTotalSharesuint256The total shares supply of USDN at the time of the action.

LongPendingAction

A pending action in the queue for a long position.

struct LongPendingAction {
    ProtocolAction action;
    uint40 timestamp;
    uint24 closeLiqPenalty;
    address to;
    address validator;
    uint64 securityDepositValue;
    int24 tick;
    uint128 closeAmount;
    uint128 closePosTotalExpo;
    uint256 tickVersion;
    uint256 index;
    uint256 liqMultiplier;
    uint256 closeBoundedPositionValue;
}

Properties

NameTypeDescription
actionProtocolActionThe action type.
timestampuint40The timestamp of the initiate action.
closeLiqPenaltyuint24The liquidation penalty of the tick (only used when closing a position).
toaddressThe recipient of the position.
validatoraddressThe address that is supposed to validate the action.
securityDepositValueuint64The security deposit of the pending action.
tickint24The tick of the position.
closeAmountuint128The portion of the initial position amount to close (only used when closing a position).
closePosTotalExpouint128The total expo of the position (only used when closing a position).
tickVersionuint256The version of the tick.
indexuint256The index of the position in the tick list.
liqMultiplieruint256A fixed precision representation of the liquidation multiplier (with LIQUIDATION_MULTIPLIER_DECIMALS decimals) used to calculate the effective price for a given tick number.
closeBoundedPositionValueuint256The amount that was removed from the long balance on initiateClosePosition (only used when closing a position).

PreviousActionsData

The data allowing to validate an actionable pending action.

struct PreviousActionsData {
    bytes[] priceData;
    uint128[] rawIndices;
}

Properties

NameTypeDescription
priceDatabytes[]An array of bytes, each representing the data to be forwarded to the oracle middleware to validate a pending action in the queue.
rawIndicesuint128[]An array of raw indices in the pending actions queue, in the same order as the corresponding priceData.

LiqTickInfo

Information of a liquidated tick.

struct LiqTickInfo {
    uint256 totalPositions;
    uint256 totalExpo;
    int256 remainingCollateral;
    uint128 tickPrice;
    uint128 priceWithoutPenalty;
}

Properties

NameTypeDescription
totalPositionsuint256The total number of positions in the tick.
totalExpouint256The total expo of the tick.
remainingCollateralint256The remaining collateral after liquidation.
tickPriceuint128The corresponding price.
priceWithoutPenaltyuint128The price without the liquidation penalty.

LiquidationsEffects

The effects of executed liquidations on the protocol.

struct LiquidationsEffects {
    uint256 liquidatedPositions;
    int256 remainingCollateral;
    uint256 newLongBalance;
    uint256 newVaultBalance;
    bool isLiquidationPending;
    LiqTickInfo[] liquidatedTicks;
}

Properties

NameTypeDescription
liquidatedPositionsuint256The total number of liquidated positions.
remainingCollateralint256The remaining collateral after liquidation.
newLongBalanceuint256The new balance of the long side.
newVaultBalanceuint256The new balance of the vault side.
isLiquidationPendingboolWhether some ticks are still populated above the current price (left to liquidate).
liquidatedTicksLiqTickInfo[]Information about the liquidated ticks.

TickData

Accumulator for tick data.

Since the liquidation penalty is a parameter that can be updated, we need to ensure that positions that get created with a given penalty, use this penalty throughout their lifecycle. As such, once a tick gets populated by a first position, it gets assigned the current liquidation penalty parameter value and can't use another value until it gets liquidated or all positions exit the tick.

struct TickData {
    uint256 totalExpo;
    uint248 totalPos;
    uint24 liquidationPenalty;
}

Properties

NameTypeDescription
totalExpouint256The sum of the total expo of each position in the tick.
totalPosuint248The number of positions in the tick.
liquidationPenaltyuint24The liquidation penalty for the positions in the tick.

PositionId

The unique identifier for a long position.

struct PositionId {
    int24 tick;
    uint256 tickVersion;
    uint256 index;
}

Properties

NameTypeDescription
tickint24The tick of the position.
tickVersionuint256The version of the tick.
indexuint256The index of the position in the tick list.

InitiateOpenPositionParams

Parameters for the internal _initiateOpenPosition function.

struct InitiateOpenPositionParams {
    address user;
    address to;
    address validator;
    uint128 amount;
    uint128 desiredLiqPrice;
    uint128 userMaxPrice;
    uint256 userMaxLeverage;
    uint256 deadline;
    uint64 securityDepositValue;
}

Properties

NameTypeDescription
useraddressThe address of the user initiating the open position.
toaddressThe address that will be the owner of the position.
validatoraddressThe address that is supposed to validate the action.
amountuint128The amount of assets to deposit.
desiredLiqPriceuint128The desired liquidation price, including the liquidation penalty.
userMaxPriceuint128The maximum price at which the position can be opened. The userMaxPrice is compared with the price after confidence interval, penalty, etc...
userMaxLeverageuint256The maximum leverage for the newly created position.
deadlineuint256The deadline of the open position to be initiated.
securityDepositValueuint64The value of the security deposit for the newly created pending action.

PrepareInitiateOpenPositionParams

Parameters for the internal {UsdnProtocolLongLibrary._prepareInitiateOpenPosition} function.

struct PrepareInitiateOpenPositionParams {
    address validator;
    uint128 amount;
    uint128 desiredLiqPrice;
    uint256 userMaxPrice;
    uint256 userMaxLeverage;
    bytes currentPriceData;
}

Properties

NameTypeDescription
validatoraddressThe address that is supposed to validate the action.
amountuint128The amount of assets to deposit.
desiredLiqPriceuint128The desired liquidation price, including the liquidation penalty.
userMaxPriceuint256The maximum price at which the position can be opened. The userMaxPrice is compared with the price after confidence interval, penalty, etc...
userMaxLeverageuint256The maximum leverage for the newly created position.
currentPriceDatabytesThe current price data.

PrepareInitiateClosePositionParams

Parameters for the internal _prepareClosePositionData function.

struct PrepareInitiateClosePositionParams {
    address to;
    address validator;
    PositionId posId;
    uint128 amountToClose;
    uint256 userMinPrice;
    uint256 deadline;
    bytes currentPriceData;
    bytes delegationSignature;
    bytes32 domainSeparatorV4;
}

Properties

NameTypeDescription
toaddressThe recipient of the funds.
validatoraddressThe address that is supposed to validate the action.
posIdPositionIdThe unique identifier of the position.
amountToCloseuint128The amount of collateral to remove from the position's amount.
userMinPriceuint256The minimum price at which the position can be closed.
deadlineuint256The deadline until the position can be closed.
currentPriceDatabytesThe current price data.
delegationSignaturebytesAn EIP712 signature that proves the caller is authorized by the owner of the position to close it on their behalf.
domainSeparatorV4bytes32The domain separator v4.

InitiateClosePositionParams

Parameters for the internal _initiateClosePosition function.

struct InitiateClosePositionParams {
    address to;
    address payable validator;
    uint256 deadline;
    PositionId posId;
    uint128 amountToClose;
    uint256 userMinPrice;
    uint64 securityDepositValue;
    bytes32 domainSeparatorV4;
}

Properties

NameTypeDescription
toaddressThe recipient of the funds.
validatoraddress payableThe address that is supposed to validate the action.
deadlineuint256The deadline of the close position to be initiated.
posIdPositionIdThe unique identifier of the position.
amountToCloseuint128The amount to close.
userMinPriceuint256The minimum price at which the position can be closed.
securityDepositValueuint64The value of the security deposit for the newly created pending action.
domainSeparatorV4bytes32The domain separator v4 for EIP712 signature.

ClosePositionData

Structure to hold the transient data during _initiateClosePosition

struct ClosePositionData {
    Position pos;
    uint24 liquidationPenalty;
    uint128 totalExpoToClose;
    uint128 lastPrice;
    uint256 tempPositionValue;
    uint256 longTradingExpo;
    HugeUint.Uint512 liqMulAcc;
    bool isLiquidationPending;
}

Properties

NameTypeDescription
posPositionThe position to close.
liquidationPenaltyuint24The liquidation penalty.
totalExpoToCloseuint128The total expo to close.
lastPriceuint128The price after the last balances update.
tempPositionValueuint256The bounded value of the position that was removed from the long balance.
longTradingExpouint256The long trading expo.
liqMulAccHugeUint.Uint512The liquidation multiplier accumulator.
isLiquidationPendingboolWhether some ticks are still populated above the current price (left to liquidate).

ValidateOpenPositionData

Structure to hold the transient data during _validateOpenPosition.

struct ValidateOpenPositionData {
    LongPendingAction action;
    uint128 startPrice;
    uint128 lastPrice;
    bytes32 tickHash;
    Position pos;
    uint128 liqPriceWithoutPenaltyNorFunding;
    uint128 liqPriceWithoutPenalty;
    uint256 leverage;
    uint256 oldPosValue;
    uint24 liquidationPenalty;
    bool isLiquidationPending;
}

Properties

NameTypeDescription
actionLongPendingActionThe long pending action.
startPriceuint128The new entry price of the position.
lastPriceuint128The price of the last balances update.
tickHashbytes32The tick hash.
posPositionThe position object.
liqPriceWithoutPenaltyNorFundinguint128The liquidation price without penalty nor funding used to calculate the user leverage and the new total expo.
liqPriceWithoutPenaltyuint128The new liquidation price without penalty.
leverageuint256The new leverage.
oldPosValueuint256The value of the position according to the old entry price and the _lastPrice.
liquidationPenaltyuint24The liquidation penalty for the position's tick.
isLiquidationPendingboolWhether some ticks are still populated above the current price (left to liquidate).

InitiateOpenPositionData

Structure to hold the transient data during _initiateOpenPosition.

struct InitiateOpenPositionData {
    uint128 adjustedPrice;
    PositionId posId;
    uint24 liquidationPenalty;
    uint128 positionTotalExpo;
    uint256 positionValue;
    uint256 liqMultiplier;
    bool isLiquidationPending;
}

Properties

NameTypeDescription
adjustedPriceuint128The adjusted price with position fees applied.
posIdPositionIdThe unique identifier of the position.
liquidationPenaltyuint24The liquidation penalty.
positionTotalExpouint128The total expo of the position. The product of the initial collateral and the initial leverage.
positionValueuint256The value of the position, taking into account the position fee.
liqMultiplieruint256The liquidation multiplier represented with fixed precision.
isLiquidationPendingboolWhether some ticks are still populated above the current price (left to liquidate).

CachedProtocolState

Structure to hold the state of the protocol.

struct CachedProtocolState {
    uint256 totalExpo;
    uint256 tradingExpo;
    uint256 longBalance;
    uint256 vaultBalance;
    HugeUint.Uint512 liqMultiplierAccumulator;
}

Properties

NameTypeDescription
totalExpouint256The long total expo.
tradingExpouint256The long trading expo.
longBalanceuint256The long balance.
vaultBalanceuint256The vault balance.
liqMultiplierAccumulatorHugeUint.Uint512The liquidation multiplier accumulator.

CalcRebalancerPositionTickData

Structure to hold transient data during the {UsdnProtocolActionsLongLibrary._calcRebalancerPositionTick} function.

struct CalcRebalancerPositionTickData {
    uint256 protocolMaxLeverage;
    int256 longImbalanceTargetBps;
    uint256 tradingExpoToFill;
    uint256 highestUsableTradingExpo;
    uint24 currentLiqPenalty;
    uint128 liqPriceWithoutPenalty;
}

Properties

NameTypeDescription
protocolMaxLeverageuint256The protocol maximum leverage.
longImbalanceTargetBpsint256The long imbalance target in basis points.
tradingExpoToFilluint256The trading expo to fill.
highestUsableTradingExpouint256The highest usable trading expo.
currentLiqPenaltyuint24The current liquidation penalty.
liqPriceWithoutPenaltyuint128The liquidation price without penalty.

RebalancerPositionData

Structure to hold the return values of the {UsdnProtocolActionsLongLibrary._calcRebalancerPositionTick} function.

struct RebalancerPositionData {
    int24 tick;
    uint128 totalExpo;
    uint24 liquidationPenalty;
}

Properties

NameTypeDescription
tickint24The tick of the rebalancer position, includes liquidation penalty.
totalExpouint128The total expo of the rebalancer position.
liquidationPenaltyuint24The liquidation penalty of the tick.

ApplyPnlAndFundingData

Data structure for the _applyPnlAndFunding function.

struct ApplyPnlAndFundingData {
    int256 tempLongBalance;
    int256 tempVaultBalance;
    uint128 lastPrice;
}

Properties

NameTypeDescription
tempLongBalanceint256The new balance of the long side, could be negative (temporarily).
tempVaultBalanceint256The new balance of the vault side, could be negative (temporarily).
lastPriceuint128The last price.

TickPriceConversionData

Data structure for tick to price conversion functions.

struct TickPriceConversionData {
    uint256 tradingExpo;
    HugeUint.Uint512 accumulator;
    int24 tickSpacing;
}

Properties

NameTypeDescription
tradingExpouint256The long side trading expo.
accumulatorHugeUint.Uint512The liquidation multiplier accumulator.
tickSpacingint24The tick spacing.

Storage

Structure to hold the state of the protocol.

Note: storage-location: erc7201:UsdnProtocol.storage.main.

struct Storage {
    int24 _tickSpacing;
    IERC20Metadata _asset;
    uint8 _assetDecimals;
    uint8 _priceFeedDecimals;
    IUsdn _usdn;
    IERC20Metadata _sdex;
    uint256 _usdnMinDivisor;
    IBaseOracleMiddleware _oracleMiddleware;
    IBaseLiquidationRewardsManager _liquidationRewardsManager;
    IBaseRebalancer _rebalancer;
    mapping(address => bool) _isRebalancer;
    uint256 _minLeverage;
    uint256 _maxLeverage;
    uint128 _lowLatencyValidatorDeadline;
    uint128 _onChainValidatorDeadline;
    uint256 _safetyMarginBps;
    uint16 _liquidationIteration;
    uint16 _protocolFeeBps;
    uint16 _rebalancerBonusBps;
    uint24 _liquidationPenalty;
    uint128 _EMAPeriod;
    uint256 _fundingSF;
    uint256 _feeThreshold;
    int256 _openExpoImbalanceLimitBps;
    int256 _withdrawalExpoImbalanceLimitBps;
    int256 _depositExpoImbalanceLimitBps;
    int256 _closeExpoImbalanceLimitBps;
    int256 _rebalancerCloseExpoImbalanceLimitBps;
    int256 _longImbalanceTargetBps;
    uint16 _positionFeeBps;
    uint16 _vaultFeeBps;
    uint16 _sdexRewardsRatioBps;
    uint32 __unused;
    address _feeCollector;
    uint64 _securityDepositValue;
    uint128 _targetUsdnPrice;
    uint128 _usdnRebaseThreshold;
    uint256 _minLongPosition;
    int256 _lastFundingPerDay;
    uint128 _lastPrice;
    uint128 _lastUpdateTimestamp;
    uint256 _pendingProtocolFee;
    mapping(address => uint256) _pendingActions;
    DoubleEndedQueue.Deque _pendingActionsQueue;
    uint256 _balanceVault;
    int256 _pendingBalanceVault;
    int256 _EMA;
    uint256 _balanceLong;
    uint256 _totalExpo;
    HugeUint.Uint512 _liqMultiplierAccumulator;
    mapping(int24 => uint256) _tickVersion;
    mapping(bytes32 => Position[]) _longPositions;
    mapping(bytes32 => TickData) _tickData;
    int24 _highestPopulatedTick;
    uint256 _totalLongPositions;
    LibBitmap.Bitmap _tickBitmap;
    address _protocolFallbackAddr;
    mapping(address => uint256) _nonce;
    uint64 _sdexBurnOnDepositRatio;
}

Properties

NameTypeDescription
_tickSpacingint24The liquidation tick spacing for storing long positions. A tick spacing of 1 is equivalent to a 0.01% increase in liquidation price between ticks. A tick spacing of 100 is equivalent to a ~1.005% increase in liquidation price between ticks.
_assetIERC20MetadataThe asset ERC20 contract. Assets with a blacklist are not supported because the protocol would be DoS if transfers revert.
_assetDecimalsuint8The number of decimals used by the _asset.
_priceFeedDecimalsuint8The price feed decimals (18).
_usdnIUsdnThe USDN ERC20 contract.
_sdexIERC20MetadataThe SDEX ERC20 contract.
_usdnMinDivisoruint256The minimum divisor for USDN.
_oracleMiddlewareIBaseOracleMiddlewareThe oracle middleware contract.
_liquidationRewardsManagerIBaseLiquidationRewardsManagerThe liquidation rewards manager contract.
_rebalancerIBaseRebalancerThe rebalancer contract.
_isRebalancermapping(address => bool)Whether an address is or has been a rebalancer.
_minLeverageuint256The minimum leverage for a position.
_maxLeverageuint256The maximum leverage for a position.
_lowLatencyValidatorDeadlineuint128The deadline for a user to confirm their action with a low-latency oracle. After this deadline, any user can validate the action with the low-latency oracle until the OracleMiddleware's _lowLatencyDelay. This is an offset compared to the timestamp of the initiate action.
_onChainValidatorDeadlineuint128The deadline for a user to confirm their action with an on-chain oracle. After this deadline, any user can validate the action with the on-chain oracle. This is an offset compared to the timestamp of the initiate action + the oracle middleware's _lowLatencyDelay.
_safetyMarginBpsuint256Safety margin for the liquidation price of newly open positions, in basis points.
_liquidationIterationuint16The number of iterations to perform during the user's action (in tick).
_protocolFeeBpsuint16The protocol fee in basis points.
_rebalancerBonusBpsuint16Part of the remaining collateral that is given as a bonus to the Rebalancer upon liquidation of a tick, in basis points. The rest is sent to the Vault balance.
_liquidationPenaltyuint24The liquidation penalty (in ticks).
_EMAPerioduint128The moving average period of the funding rate.
_fundingSFuint256The scaling factor (SF) of the funding rate.
_feeThresholduint256The threshold above which the fee will be sent.
_openExpoImbalanceLimitBpsint256The imbalance limit of the long expo for open actions (in basis points). As soon as the difference between the vault expo and the long expo exceeds this basis point limit in favor of long the open rebalancing mechanism is triggered, preventing the opening of a new long position.
_withdrawalExpoImbalanceLimitBpsint256The imbalance limit of the long expo for withdrawal actions (in basis points). As soon as the difference between vault expo and long expo exceeds this basis point limit in favor of long, the withdrawal rebalancing mechanism is triggered, preventing the withdrawal of the existing vault position.
_depositExpoImbalanceLimitBpsint256The imbalance limit of the vault expo for deposit actions (in basis points). As soon as the difference between the vault expo and the long expo exceeds this basis point limit in favor of the vault, the deposit vault rebalancing mechanism is triggered, preventing the opening of a new vault position.
_closeExpoImbalanceLimitBpsint256The imbalance limit of the vault expo for close actions (in basis points). As soon as the difference between the vault expo and the long expo exceeds this basis point limit in favor of the vault, the close rebalancing mechanism is triggered, preventing the close of an existing long position.
_rebalancerCloseExpoImbalanceLimitBpsint256The imbalance limit of the vault expo for close actions from the rebalancer (in basis points). As soon as the difference between the vault expo and the long expo exceeds this basis point limit in favor of the vault, the close rebalancing mechanism is triggered, preventing the close of an existing long position from the rebalancer contract.
_longImbalanceTargetBpsint256The target imbalance on the long side (in basis points) This value will be used to calculate how much of the missing trading expo the rebalancer position will try to compensate. A negative value means the rebalancer will compensate enough to go above the equilibrium. A positive value means the rebalancer will compensate but stay below the equilibrium.
_positionFeeBpsuint16The position fee in basis points.
_vaultFeeBpsuint16The fee for vault deposits and withdrawals, in basis points.
_sdexRewardsRatioBpsuint16The ratio of SDEX rewards to send to the user (in basis points).
__unuseduint32Old slot for _sdexBurnOnDepositRatio.
_feeCollectoraddressThe fee collector's address.
_securityDepositValueuint64The deposit required for a new position.
_targetUsdnPriceuint128The nominal (target) price of USDN (with _priceFeedDecimals).
_usdnRebaseThresholduint128The USDN price threshold to trigger a rebase (with _priceFeedDecimals).
_minLongPositionuint256The minimum long position size (with _assetDecimals).
_lastFundingPerDayint256The funding rate calculated at the last update timestamp.
_lastPriceuint128The price of the asset during the last balances update (with price feed decimals).
_lastUpdateTimestampuint128The timestamp of the last balances update.
_pendingProtocolFeeuint256The pending protocol fee accumulator.
_pendingActionsmapping(address => uint256)The pending actions by the user (1 per user max). The value stored is an index into the pendingActionsQueue deque, shifted by one. A value of 0 means no pending action. Since the deque uses uint128 indices, the highest index will not overflow when adding one.
_pendingActionsQueueDoubleEndedQueue.DequeThe queue of pending actions.
_balanceVaultuint256The balance of deposits (with _assetDecimals).
_pendingBalanceVaultint256The unreflected balance change due to pending vault actions (with _assetDecimals).
_EMAint256The exponential moving average of the funding (0.0003 at initialization).
_balanceLonguint256The balance of long positions (with _assetDecimals).
_totalExpouint256The total exposure of the long positions (with _assetDecimals).
_liqMultiplierAccumulatorHugeUint.Uint512The accumulator used to calculate the liquidation multiplier. This is the sum, for all ticks, of the total expo of positions inside the tick, multiplied by the unadjusted price of the tick which is _tickData[tickHash].liquidationPenalty below The unadjusted price is obtained with `TickMath.getPriceAtTick.
_tickVersionmapping(int24 => uint256)The liquidation tick version.
_longPositionsmapping(bytes32 => Position[])The long positions per versioned tick (liquidation price).
_tickDatamapping(bytes32 => TickData)Accumulated data for a given tick and tick version.
_highestPopulatedTickint24The highest tick with a position.
_totalLongPositionsuint256Cache of the total long positions count.
_tickBitmapLibBitmap.BitmapThe bitmap used to quickly find populated ticks.
_protocolFallbackAddraddressThe address of the fallback contract.
_noncemapping(address => uint256)The user EIP712 nonce.
_sdexBurnOnDepositRatiouint64The ratio of USDN to SDEX tokens to burn on deposit.

InitStorage

Structure to hold initial parameters for the protocol.

struct InitStorage {
    int24 tickSpacing;
    IERC20Metadata asset;
    IUsdn usdn;
    IERC20Metadata sdex;
    IBaseOracleMiddleware oracleMiddleware;
    IBaseLiquidationRewardsManager liquidationRewardsManager;
    uint256 minLeverage;
    uint256 maxLeverage;
    uint128 lowLatencyValidatorDeadline;
    uint128 onChainValidatorDeadline;
    uint256 safetyMarginBps;
    uint16 liquidationIteration;
    uint16 protocolFeeBps;
    uint16 rebalancerBonusBps;
    uint24 liquidationPenalty;
    uint128 emaPeriod;
    uint256 fundingSF;
    uint256 feeThreshold;
    int256 openExpoImbalanceLimitBps;
    int256 withdrawalExpoImbalanceLimitBps;
    int256 depositExpoImbalanceLimitBps;
    int256 closeExpoImbalanceLimitBps;
    int256 rebalancerCloseExpoImbalanceLimitBps;
    int256 longImbalanceTargetBps;
    uint16 positionFeeBps;
    uint16 vaultFeeBps;
    uint16 sdexRewardsRatioBps;
    uint64 sdexBurnOnDepositRatio;
    address feeCollector;
    uint64 securityDepositValue;
    uint128 targetUsdnPrice;
    uint128 usdnRebaseThreshold;
    uint256 minLongPosition;
    int256 EMA;
    address protocolFallbackAddr;
}

Properties

NameTypeDescription
tickSpacingint24The liquidation tick spacing for storing long positions.
assetIERC20MetadataThe asset ERC20 contract.
usdnIUsdnThe USDN ERC20 contract.
sdexIERC20MetadataThe SDEX ERC20 contract.
oracleMiddlewareIBaseOracleMiddlewareThe oracle middleware contract.
liquidationRewardsManagerIBaseLiquidationRewardsManagerThe liquidation rewards manager contract.
minLeverageuint256The minimum leverage for a position.
maxLeverageuint256The maximum leverage for a position.
lowLatencyValidatorDeadlineuint128The deadline for a user to confirm their action with a low-latency oracle.
onChainValidatorDeadlineuint128The deadline for a user to confirm their action with an on-chain oracle.
safetyMarginBpsuint256Safety margin for the liquidation price of newly open positions, in basis points.
liquidationIterationuint16The number of iterations to perform during the user's action (in tick).
protocolFeeBpsuint16The protocol fee in basis points.
rebalancerBonusBpsuint16Part of the remaining collateral that is given as a bonus to the Rebalancer upon liquidation of a tick, in basis points. The rest is sent to the Vault balance.
liquidationPenaltyuint24The liquidation penalty (in ticks).
emaPerioduint128The moving average period of the funding rate.
fundingSFuint256The scaling factor (SF) of the funding rate.
feeThresholduint256The threshold above which the fee will be sent.
openExpoImbalanceLimitBpsint256The imbalance limit of the long expo for open actions (in basis points).
withdrawalExpoImbalanceLimitBpsint256The imbalance limit of the long expo for withdrawal actions (in basis points).
depositExpoImbalanceLimitBpsint256The imbalance limit of the vault expo for deposit actions (in basis points).
closeExpoImbalanceLimitBpsint256The imbalance limit of the vault expo for close actions (in basis points).
rebalancerCloseExpoImbalanceLimitBpsint256The imbalance limit of the vault expo for close actions from the rebalancer (in basis points).
longImbalanceTargetBpsint256The target imbalance on the long side (in basis points)
positionFeeBpsuint16The position fee in basis points.
vaultFeeBpsuint16The fee for vault deposits and withdrawals, in basis points.
sdexRewardsRatioBpsuint16The ratio of SDEX rewards to send to the user (in basis points).
sdexBurnOnDepositRatiouint64The ratio of USDN to SDEX tokens to burn on deposit.
feeCollectoraddressThe fee collector's address.
securityDepositValueuint64The deposit required for a new position.
targetUsdnPriceuint128The nominal (target) price of USDN (with _priceFeedDecimals).
usdnRebaseThresholduint128The USDN price threshold to trigger a rebase (with _priceFeedDecimals).
minLongPositionuint256The minimum long position size (with _assetDecimals).
EMAint256The exponential moving average of the funding (0.0003 at initialization).
protocolFallbackAddraddressThe address of the fallback contract.

Enums

ProtocolAction

All possible action types for the protocol.

This is used for pending actions and to interact with the oracle middleware.

enum ProtocolAction {
    None,
    Initialize,
    InitiateDeposit,
    ValidateDeposit,
    InitiateWithdrawal,
    ValidateWithdrawal,
    InitiateOpenPosition,
    ValidateOpenPosition,
    InitiateClosePosition,
    ValidateClosePosition,
    Liquidation
}

LongActionOutcome

The outcome of the call targeting a long position.

enum LongActionOutcome {
    Processed,
    Liquidated,
    PendingLiquidations
}

RebalancerAction

Classifies how far in its logic the _triggerRebalancer function made it to.

Used to estimate the gas spent by the function call to more accurately calculate liquidation rewards.

enum RebalancerAction {
    None,
    NoImbalance,
    PendingLiquidation,
    NoCloseNoOpen,
    Closed,
    Opened,
    ClosedOpened
}