UsdnProtocolFallback

Git Source

Inherits: IUsdnProtocolFallback, IUsdnProtocolErrors, IUsdnProtocolEvents, InitializableReentrancyGuard, PausableUpgradeable, AccessControlDefaultAdminRulesUpgradeable

State Variables

MAX_SDEX_BURN_RATIO

The highest value allowed for the ratio of SDEX to burn per minted USDN on deposit.

uint256 internal immutable MAX_SDEX_BURN_RATIO;

MAX_MIN_LONG_POSITION

The highest value allowed for the minimum long position setting.

uint256 internal immutable MAX_MIN_LONG_POSITION;

Functions

constructor

constructor(uint256 maxSdexBurnRatio, uint256 maxMinLongPosition);

Parameters

NameTypeDescription
maxSdexBurnRatiouint256The value of MAX_SDEX_BURN_RATIO.
maxMinLongPositionuint256The value of MAX_MIN_LONG_POSITION.

getActionablePendingActions

Retrieves the list of pending actions that must be validated by the next user action in the protocol.

If this function returns a non-empty list of pending actions, then the next user action MUST include the corresponding list of price update data and raw indices as the last parameter. The user that processes those pending actions will receive the corresponding security deposit.

function getActionablePendingActions(address currentUser, uint256 lookAhead, uint256 maxIter)
    external
    view
    returns (PendingAction[] memory actions_, uint128[] memory rawIndices_);

Parameters

NameTypeDescription
currentUseraddressThe address of the user that will submit the price signatures for third-party actions validations. This is used to filter out their actions from the returned list.
lookAheaduint256Additionally to pending actions which are actionable at this moment block.timestamp, the function will also return pending actions which will be actionable lookAhead seconds later. It is recommended to use a non-zero value in order to account for the interval where the validation transaction will be pending. A value of 30 seconds should already account for most situations and avoid reverts in case an action becomes actionable after a user submits their transaction.
maxIteruint256The maximum number of iterations when looking through the queue to find actionable pending actions. This value will be clamped to [MIN_ACTIONABLE_PENDING_ACTIONS_ITER,_pendingActionsQueue.length()].

Returns

NameTypeDescription
actions_PendingAction[]The pending actions if any, otherwise an empty array.
rawIndices_uint128[]The raw indices of the actionable pending actions in the queue if any, otherwise an empty array. Each entry corresponds to the action in the actions_ array, at the same index.

getUserPendingAction

Retrieves the pending action with user as the given validator.

function getUserPendingAction(address user) external view returns (PendingAction memory action_);

Parameters

NameTypeDescription
useraddressThe user's address.

Returns

NameTypeDescription
action_PendingActionThe pending action if any, otherwise a struct with all fields set to zero and ProtocolAction.None.

tickHash

Computes the hash generated from the given tick number and version.

function tickHash(int24 tick, uint256 version) external pure returns (bytes32 hash_);

Parameters

NameTypeDescription
tickint24The tick number.
versionuint256The tick version.

Returns

NameTypeDescription
hash_bytes32The hash of the given tick number and version.

getEffectivePriceForTick

Computes the liquidation price of the given tick number, taking into account the effects of funding.

Uses the values from storage for the various variables. Note that ticks that are not a multiple of the tick spacing cannot contain a long position.

function getEffectivePriceForTick(int24 tick) external view returns (uint128 price_);

Parameters

NameTypeDescription
tickint24The tick number.

Returns

NameTypeDescription
price_uint128The liquidation price.

getEffectivePriceForTick

Computes the liquidation price of the given tick number, taking into account the effects of funding.

Uses the values from storage for the various variables. Note that ticks that are not a multiple of the tick spacing cannot contain a long position.

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

Parameters

NameTypeDescription
tickint24The tick number.
assetPriceuint256
longTradingExpouint256
accumulatorHugeUint.Uint512

Returns

NameTypeDescription
price_uint128The liquidation price.

previewDeposit

Computes an estimate of USDN tokens to be minted and SDEX tokens to be burned when depositing.

The result is a rough estimate and does not take into account rebases and liquidations.

function previewDeposit(uint256 amount, uint128 price, uint128 timestamp)
    external
    view
    returns (uint256 usdnSharesExpected_, uint256 sdexToBurn_);

Parameters

NameTypeDescription
amountuint256The amount of assets to deposit.
priceuint128The current/projected price of the asset.
timestampuint128The timestamp corresponding to price.

Returns

NameTypeDescription
usdnSharesExpected_uint256The amount of USDN shares to be minted.
sdexToBurn_uint256The amount of SDEX tokens to be burned.

previewWithdraw

Computes an estimate of the amount of assets received when withdrawing.

The result is a rough estimate and does not take into account rebases and liquidations.

function previewWithdraw(uint256 usdnShares, uint128 price, uint128 timestamp)
    external
    view
    returns (uint256 assetExpected_);

Parameters

NameTypeDescription
usdnSharesuint256The amount of USDN shares to use in the withdrawal.
priceuint128The current/projected price of the asset.
timestampuint128The The timestamp corresponding to price.

Returns

NameTypeDescription
assetExpected_uint256The expected amount of assets to be received.

burnSdex

Sends the accumulated SDEX token fees to the dead address. This function can be called by anyone.

function burnSdex() external whenNotPaused initializedAndNonReentrant;

refundSecurityDeposit

Refunds the security deposit to the given validator if it has a liquidated initiated long position.

The security deposit is always sent to the validator even if the pending action is actionable.

function refundSecurityDeposit(address payable validator) external whenNotPaused initializedAndNonReentrant;

Parameters

NameTypeDescription
validatoraddress payableThe address of the validator (must be payable as it will receive some native currency).

removeBlockedPendingAction

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

This function can 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 internal reverting unexpectedly. It will not refund any fees or burned SDEX.

function removeBlockedPendingAction(address validator, address payable to)
    external
    onlyRole(Constants.CRITICAL_FUNCTIONS_ROLE)
    initializedAndNonReentrant;

Parameters

NameTypeDescription
validatoraddressThe address of the validator of the stuck pending action.
toaddress payableWhere the retrieved funds should be sent (security deposit, assets, usdn). Must be payable.

removeBlockedPendingActionNoCleanup

Removes a stuck pending action with no cleanup.

This function can 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 internal reverting unexpectedly. Always try to use removeBlockedPendingAction first, and only call this function if the other one fails. It will not refund any fees or burned SDEX.

function removeBlockedPendingActionNoCleanup(address validator, address payable to)
    external
    onlyRole(Constants.CRITICAL_FUNCTIONS_ROLE);

Parameters

NameTypeDescription
validatoraddressThe address of the validator of the stuck pending action.
toaddress payableWhere the retrieved funds should be sent (security deposit, assets, usdn). Must be payable.

removeBlockedPendingAction

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

This function can 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 internal reverting unexpectedly. It will not refund any fees or burned SDEX.

function removeBlockedPendingAction(uint128 rawIndex, address payable to)
    external
    onlyRole(Constants.CRITICAL_FUNCTIONS_ROLE)
    initializedAndNonReentrant;

Parameters

NameTypeDescription
rawIndexuint128
toaddress payableWhere the retrieved funds should be sent (security deposit, assets, usdn). Must be payable.

removeBlockedPendingActionNoCleanup

Removes a stuck pending action with no cleanup.

This function can 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 internal reverting unexpectedly. Always try to use removeBlockedPendingAction first, and only call this function if the other one fails. It will not refund any fees or burned SDEX.

function removeBlockedPendingActionNoCleanup(uint128 rawIndex, address payable to)
    external
    onlyRole(Constants.CRITICAL_FUNCTIONS_ROLE);

Parameters

NameTypeDescription
rawIndexuint128
toaddress payableWhere the retrieved funds should be sent (security deposit, assets, usdn). Must be payable.

getTickSpacing

The number of ticks between usable ticks. Only tick numbers that are a multiple of the tick spacing can be used for storing long positions.

A tick spacing of 1 is equivalent to a 0.01% increase in price between ticks. A tick spacing of 100 is. equivalent to a ~1.005% increase in price between ticks.

function getTickSpacing() external view returns (int24 tickSpacing_);

Returns

NameTypeDescription
tickSpacing_int24The tick spacing.

getAsset

Gets the address of the protocol's underlying asset (ERC20 token).

function getAsset() external view returns (IERC20Metadata asset_);

Returns

NameTypeDescription
asset_IERC20MetadataThe address of the asset token.

getSdex

Gets the address of the SDEX ERC20 token.

function getSdex() external view returns (IERC20Metadata sdex_);

Returns

NameTypeDescription
sdex_IERC20MetadataThe address of the SDEX token.

getPriceFeedDecimals

Gets the number of decimals of the asset's price feed.

function getPriceFeedDecimals() external view returns (uint8 decimals_);

Returns

NameTypeDescription
decimals_uint8The number of decimals of the asset's price feed.

getAssetDecimals

Gets the number of decimals of the underlying asset token.

function getAssetDecimals() external view returns (uint8 decimals_);

Returns

NameTypeDescription
decimals_uint8The number of decimals of the asset token.

getUsdn

Gets the address of the USDN ERC20 token.

function getUsdn() external view returns (IUsdn usdn_);

Returns

NameTypeDescription
usdn_IUsdnThe address of USDN ERC20 token.

getUsdnMinDivisor

Gets the MIN_DIVISOR constant of the USDN token.

Check the USDN contract for more information.

function getUsdnMinDivisor() external view returns (uint256 minDivisor_);

Returns

NameTypeDescription
minDivisor_uint256The MIN_DIVISOR constant of the USDN token.

getOracleMiddleware

Gets the oracle middleware contract.

function getOracleMiddleware() external view returns (IBaseOracleMiddleware oracleMiddleware_);

Returns

NameTypeDescription
oracleMiddleware_IBaseOracleMiddlewareThe address of the oracle middleware contract.

getLiquidationRewardsManager

Gets the liquidation rewards manager contract.

function getLiquidationRewardsManager()
    external
    view
    returns (IBaseLiquidationRewardsManager liquidationRewardsManager_);

Returns

NameTypeDescription
liquidationRewardsManager_IBaseLiquidationRewardsManagerThe address of the liquidation rewards manager contract.

getRebalancer

Gets the rebalancer contract.

function getRebalancer() external view returns (IBaseRebalancer rebalancer_);

Returns

NameTypeDescription
rebalancer_IBaseRebalancerThe address of the rebalancer contract.

getMinLeverage

Gets the lowest leverage that can be used to open a long position.

function getMinLeverage() external view returns (uint256 minLeverage_);

Returns

NameTypeDescription
minLeverage_uint256The minimum leverage (with LEVERAGE_DECIMALS decimals).

getMaxLeverage

Gets the highest leverage that can be used to open a long position.

A position can have a leverage a bit higher than this value under specific conditions involving a change to the liquidation penalty setting.

function getMaxLeverage() external view returns (uint256 maxLeverage_);

Returns

NameTypeDescription
maxLeverage_uint256The maximum leverage value (with LEVERAGE_DECIMALS decimals).

getLowLatencyValidatorDeadline

Gets the deadline of the exclusivity period for the validator of a pending 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, and retrieve the security deposit for the pending action.

function getLowLatencyValidatorDeadline() external view returns (uint128 deadline_);

Returns

NameTypeDescription
deadline_uint128The low-latency validation deadline of a validator (in seconds).

getOnChainValidatorDeadline

Gets the deadline of the exclusivity period for the validator to confirm their action with the on-chain oracle.

After this deadline, any user can validate the pending action with the on-chain oracle and retrieve its security deposit.

function getOnChainValidatorDeadline() external view returns (uint128 deadline_);

Returns

NameTypeDescription
deadline_uint128The on-chain validation deadline of a validator (in seconds)

getLiquidationPenalty

Gets the liquidation penalty applied to the liquidation price when opening a position.

function getLiquidationPenalty() external view returns (uint24 liquidationPenalty_);

Returns

NameTypeDescription
liquidationPenalty_uint24The liquidation penalty (in ticks).

getSafetyMarginBps

Gets the safety margin for the liquidation price of newly open positions.

function getSafetyMarginBps() external view returns (uint256 safetyMarginBps_);

Returns

NameTypeDescription
safetyMarginBps_uint256The safety margin (in basis points).

getLiquidationIteration

Gets the number of tick liquidations to perform when attempting to liquidate positions during user actions.

function getLiquidationIteration() external view returns (uint16 iterations_);

Returns

NameTypeDescription
iterations_uint16The number of iterations for liquidations during user actions.

getEMAPeriod

Gets the time frame for the EMA calculations.

The EMA is set to the last funding rate when the time elapsed between 2 actions is greater than this value.

function getEMAPeriod() external view returns (uint128 period_);

Returns

NameTypeDescription
period_uint128The time frame of the EMA (in seconds).

getFundingSF

Gets the scaling factor (SF) of the funding rate.

function getFundingSF() external view returns (uint256 scalingFactor_);

Returns

NameTypeDescription
scalingFactor_uint256The scaling factor (with FUNDING_SF_DECIMALS decimals).

getProtocolFeeBps

Gets the fee taken by the protocol during the application of funding.

function getProtocolFeeBps() external view returns (uint16 feeBps_);

Returns

NameTypeDescription
feeBps_uint16The fee applied to the funding (in basis points).

getPositionFeeBps

Gets the fee applied when a long position is opened or closed.

function getPositionFeeBps() external view returns (uint16 feeBps_);

Returns

NameTypeDescription
feeBps_uint16The fee applied to a long position (in basis points).

getVaultFeeBps

Gets the fee applied during a vault deposit or withdrawal.

function getVaultFeeBps() external view returns (uint16 feeBps_);

Returns

NameTypeDescription
feeBps_uint16The fee applied to a vault action (in basis points).

getSdexRewardsRatioBps

Gets the rewards ratio given to the caller when burning SDEX tokens.

function getSdexRewardsRatioBps() external view returns (uint16 rewardsBps_);

Returns

NameTypeDescription
rewardsBps_uint16The rewards ratio (in basis points).

getRebalancerBonusBps

Gets the part of the remaining collateral given as a bonus to the Rebalancer upon liquidation of a tick.

function getRebalancerBonusBps() external view returns (uint16 bonusBps_);

Returns

NameTypeDescription
bonusBps_uint16The fraction of the remaining collateral for the Rebalancer bonus (in basis points).

getSdexBurnOnDepositRatio

Gets the ratio of SDEX tokens to burn per minted USDN.

function getSdexBurnOnDepositRatio() external view returns (uint64 ratio_);

Returns

NameTypeDescription
ratio_uint64The ratio (to be divided by SDEX_BURN_ON_DEPOSIT_DIVISOR).

getSecurityDepositValue

Gets the amount of native tokens used as security deposit when opening a new position.

function getSecurityDepositValue() external view returns (uint64 securityDeposit_);

Returns

NameTypeDescription
securityDeposit_uint64The amount of assets to use as a security deposit (in ether).

getFeeThreshold

Gets the threshold to reach to send accumulated fees to the fee collector.

function getFeeThreshold() external view returns (uint256 threshold_);

Returns

NameTypeDescription
threshold_uint256The amount of accumulated fees to reach (in _assetDecimals).

getFeeCollector

Gets the address of the fee collector.

function getFeeCollector() external view returns (address feeCollector_);

Returns

NameTypeDescription
feeCollector_addressThe address of the fee collector.

getMiddlewareValidationDelay

Returns the amount of time to wait before an action can be validated.

This is also the amount of time to add to the initiate action timestamp to fetch the correct price data to validate said action with a low-latency oracle.

function getMiddlewareValidationDelay() external view returns (uint256 delay_);

Returns

NameTypeDescription
delay_uint256The validation delay (in seconds).

getTargetUsdnPrice

Gets the nominal (target) price of USDN.

function getTargetUsdnPrice() external view returns (uint128 price_);

Returns

NameTypeDescription
price_uint128The price of the USDN token after a rebase (in _priceFeedDecimals).

getUsdnRebaseThreshold

Gets the USDN token price above which a rebase should occur.

function getUsdnRebaseThreshold() external view returns (uint128 threshold_);

Returns

NameTypeDescription
threshold_uint128The rebase threshold (in _priceFeedDecimals).

getMinLongPosition

Gets the minimum collateral amount when opening a long position.

function getMinLongPosition() external view returns (uint256 minLongPosition_);

Returns

NameTypeDescription
minLongPosition_uint256The minimum amount (with _assetDecimals).

getLastFundingPerDay

Gets the value of the funding rate at the last timestamp (getLastUpdateTimestamp).

function getLastFundingPerDay() external view returns (int256 lastFunding_);

Returns

NameTypeDescription
lastFunding_int256The last value of the funding rate (per day) with FUNDING_RATE_DECIMALS decimals.

getLastPrice

Gets the neutral price of the asset used during the last update of the vault and long balances.

function getLastPrice() external view returns (uint128 lastPrice_);

Returns

NameTypeDescription
lastPrice_uint128The most recent known price of the asset (in _priceFeedDecimals).

getLastUpdateTimestamp

Gets the timestamp of the last time a fresh price was provided.

function getLastUpdateTimestamp() external view returns (uint128 lastTimestamp_);

Returns

NameTypeDescription
lastTimestamp_uint128The timestamp of the last update.

getPendingProtocolFee

Gets the fees that were accumulated by the contract and are yet to be sent to the fee collector (in _assetDecimals).

function getPendingProtocolFee() external view returns (uint256 protocolFees_);

Returns

NameTypeDescription
protocolFees_uint256The amount of accumulated fees still in the contract.

getBalanceVault

Gets the amount of assets backing the USDN token.

function getBalanceVault() external view returns (uint256 balanceVault_);

Returns

NameTypeDescription
balanceVault_uint256The amount of assets on the vault side (in _assetDecimals).

getPendingBalanceVault

Gets the pending balance updates due to pending vault actions.

function getPendingBalanceVault() external view returns (int256 pendingBalanceVault_);

Returns

NameTypeDescription
pendingBalanceVault_int256The unreflected balance change due to pending vault actions (in _assetDecimals).

getEMA

Gets the exponential moving average of the funding rate per day.

function getEMA() external view returns (int256 ema_);

Returns

NameTypeDescription
ema_int256The exponential moving average of the funding rate per day.

getBalanceLong

Gets the summed value of all the currently open long positions at _lastUpdateTimestamp.

function getBalanceLong() external view returns (uint256 balanceLong_);

Returns

NameTypeDescription
balanceLong_uint256The balance of the long side (in _assetDecimals).

getTotalExpo

Gets the total exposure of all currently open long positions.

function getTotalExpo() external view returns (uint256 totalExpo_);

Returns

NameTypeDescription
totalExpo_uint256The total exposure of the longs (in _assetDecimals).

getLiqMultiplierAccumulator

Gets the accumulator used to calculate the liquidation multiplier.

function getLiqMultiplierAccumulator() external view returns (HugeUint.Uint512 memory accumulator_);

Returns

NameTypeDescription
accumulator_HugeUint.Uint512The liquidation multiplier accumulator.

getTickVersion

Gets the current version of the given tick.

function getTickVersion(int24 tick) external view returns (uint256 tickVersion_);

Parameters

NameTypeDescription
tickint24The tick number.

Returns

NameTypeDescription
tickVersion_uint256The version of the tick.

getTickData

Gets the tick data for the current tick version.

function getTickData(int24 tick) external view returns (TickData memory tickData_);

Parameters

NameTypeDescription
tickint24The tick number.

Returns

NameTypeDescription
tickData_TickDataThe tick data.

getCurrentLongPosition

Gets the long position at the provided tick and index.

function getCurrentLongPosition(int24 tick, uint256 index) external view returns (Position memory position_);

Parameters

NameTypeDescription
tickint24The tick number.
indexuint256The position index.

Returns

NameTypeDescription
position_PositionThe long position.

getHighestPopulatedTick

Gets the highest tick that has an open position.

function getHighestPopulatedTick() external view returns (int24 tick_);

Returns

NameTypeDescription
tick_int24The highest populated tick.

getTotalLongPositions

Gets the total number of long positions currently open.

function getTotalLongPositions() external view returns (uint256 totalLongPositions_);

Returns

NameTypeDescription
totalLongPositions_uint256The number of long positions.

getDepositExpoImbalanceLimitBps

Gets the expo imbalance limit when depositing assets (in basis points).

function getDepositExpoImbalanceLimitBps() external view returns (int256 depositExpoImbalanceLimitBps_);

Returns

NameTypeDescription
depositExpoImbalanceLimitBps_int256The deposit expo imbalance limit.

getWithdrawalExpoImbalanceLimitBps

Gets the expo imbalance limit when withdrawing assets (in basis points).

function getWithdrawalExpoImbalanceLimitBps() external view returns (int256 withdrawalExpoImbalanceLimitBps_);

Returns

NameTypeDescription
withdrawalExpoImbalanceLimitBps_int256The withdrawal expo imbalance limit.

getOpenExpoImbalanceLimitBps

Gets the expo imbalance limit when opening a position (in basis points).

function getOpenExpoImbalanceLimitBps() external view returns (int256 openExpoImbalanceLimitBps_);

Returns

NameTypeDescription
openExpoImbalanceLimitBps_int256The open expo imbalance limit.

getCloseExpoImbalanceLimitBps

Gets the expo imbalance limit when closing a position (in basis points).

function getCloseExpoImbalanceLimitBps() external view returns (int256 closeExpoImbalanceLimitBps_);

Returns

NameTypeDescription
closeExpoImbalanceLimitBps_int256The close expo imbalance limit.

getRebalancerCloseExpoImbalanceLimitBps

Returns the limit of the imbalance in bps to close the rebalancer position.

function getRebalancerCloseExpoImbalanceLimitBps()
    external
    view
    returns (int256 rebalancerCloseExpoImbalanceLimitBps_);

Returns

NameTypeDescription
rebalancerCloseExpoImbalanceLimitBps_int256The limit of the imbalance in bps to close the rebalancer position.

getLongImbalanceTargetBps

Returns the imbalance desired on the long side after the creation of a rebalancer position.

The creation of the rebalancer position aims for this target but does not guarantee reaching it.

function getLongImbalanceTargetBps() external view returns (int256 longImbalanceTargetBps_);

Returns

NameTypeDescription
longImbalanceTargetBps_int256targetLongImbalance_ The target long imbalance.

getFallbackAddress

Gets the address of the fallback contract.

function getFallbackAddress() external view returns (address fallback_);

Returns

NameTypeDescription
fallback_addressThe address of the fallback contract.

isPaused

Gets the pause status of the USDN protocol.

function isPaused() external view returns (bool isPaused_);

Returns

NameTypeDescription
isPaused_boolTrue if it's paused, false otherwise.

getNonce

Gets the nonce a user can use to generate a delegation signature.

This is to prevent replay attacks when using an eip712 delegation signature.

function getNonce(address user) external view returns (uint256 nonce_);

Parameters

NameTypeDescription
useraddressThe address of the user.

Returns

NameTypeDescription
nonce_uint256The user's nonce.

setOracleMiddleware

Replaces the OracleMiddleware contract with a new implementation.

Cannot be the 0 address.

function setOracleMiddleware(IBaseOracleMiddleware newOracleMiddleware)
    external
    onlyRole(Constants.SET_EXTERNAL_ROLE);

Parameters

NameTypeDescription
newOracleMiddlewareIBaseOracleMiddlewareThe address of the new contract.

setLiquidationRewardsManager

Replaces the LiquidationRewardsManager contract with a new implementation.

Cannot be the 0 address.

function setLiquidationRewardsManager(IBaseLiquidationRewardsManager newLiquidationRewardsManager)
    external
    onlyRole(Constants.SET_EXTERNAL_ROLE);

Parameters

NameTypeDescription
newLiquidationRewardsManagerIBaseLiquidationRewardsManagerThe address of the new contract.

setRebalancer

Replaces the Rebalancer contract with a new implementation.

function setRebalancer(IBaseRebalancer newRebalancer) external onlyRole(Constants.SET_EXTERNAL_ROLE);

Parameters

NameTypeDescription
newRebalancerIBaseRebalancerThe address of the new contract.

setFeeCollector

Sets the fee collector address.

Cannot be the zero address.

function setFeeCollector(address newFeeCollector) external onlyRole(Constants.SET_EXTERNAL_ROLE);

Parameters

NameTypeDescription
newFeeCollectoraddressThe address of the fee collector.

setValidatorDeadlines

Sets the new deadlines of the exclusivity period for the validator to confirm its action and get its security deposit back.

function setValidatorDeadlines(uint128 newLowLatencyValidatorDeadline, uint128 newOnChainValidatorDeadline)
    external
    onlyRole(Constants.CRITICAL_FUNCTIONS_ROLE);

Parameters

NameTypeDescription
newLowLatencyValidatorDeadlineuint128The new exclusivity deadline for low-latency validation (offset from initiate timestamp).
newOnChainValidatorDeadlineuint128The new exclusivity deadline for on-chain validation (offset from initiate timestamp + oracle middleware's low latency delay).

setMinLeverage

Sets the new minimum leverage for a position.

function setMinLeverage(uint256 newMinLeverage) external onlyRole(Constants.SET_PROTOCOL_PARAMS_ROLE);

Parameters

NameTypeDescription
newMinLeverageuint256The new minimum leverage.

setMaxLeverage

Sets the new maximum leverage for a position.

function setMaxLeverage(uint256 newMaxLeverage) external onlyRole(Constants.SET_PROTOCOL_PARAMS_ROLE);

Parameters

NameTypeDescription
newMaxLeverageuint256The new maximum leverage.

setLiquidationPenalty

Sets the new liquidation penalty (in ticks).

function setLiquidationPenalty(uint24 newLiquidationPenalty) external onlyRole(Constants.SET_PROTOCOL_PARAMS_ROLE);

Parameters

NameTypeDescription
newLiquidationPenaltyuint24The new liquidation penalty.

setEMAPeriod

Sets the new exponential moving average period of the funding rate.

function setEMAPeriod(uint128 newEMAPeriod) external onlyRole(Constants.SET_PROTOCOL_PARAMS_ROLE);

Parameters

NameTypeDescription
newEMAPerioduint128The new EMA period.

setFundingSF

Sets the new scaling factor (SF) of the funding rate.

function setFundingSF(uint256 newFundingSF) external onlyRole(Constants.SET_PROTOCOL_PARAMS_ROLE);

Parameters

NameTypeDescription
newFundingSFuint256The new scaling factor (SF) of the funding rate.

setProtocolFeeBps

Sets the protocol fee.

Fees are charged when the funding is applied (Example: 50 bps -> 0.5%).

function setProtocolFeeBps(uint16 newProtocolFeeBps) external onlyRole(Constants.SET_PROTOCOL_PARAMS_ROLE);

Parameters

NameTypeDescription
newProtocolFeeBpsuint16

setPositionFeeBps

Sets the position fee.

function setPositionFeeBps(uint16 newPositionFee) external onlyRole(Constants.SET_PROTOCOL_PARAMS_ROLE);

Parameters

NameTypeDescription
newPositionFeeuint16The new position fee (in basis points).

setVaultFeeBps

Sets the vault fee.

function setVaultFeeBps(uint16 newVaultFee) external onlyRole(Constants.SET_PROTOCOL_PARAMS_ROLE);

Parameters

NameTypeDescription
newVaultFeeuint16The new vault fee (in basis points).

setSdexRewardsRatioBps

Sets the rewards ratio given to the caller when burning SDEX tokens.

function setSdexRewardsRatioBps(uint16 newRewardsBps) external onlyRole(Constants.SET_PROTOCOL_PARAMS_ROLE);

Parameters

NameTypeDescription
newRewardsBpsuint16The new rewards ratio (in basis points).

setRebalancerBonusBps

Sets the rebalancer bonus.

function setRebalancerBonusBps(uint16 newBonus) external onlyRole(Constants.SET_PROTOCOL_PARAMS_ROLE);

Parameters

NameTypeDescription
newBonusuint16The bonus (in basis points).

setSdexBurnOnDepositRatio

Sets the ratio of SDEX tokens to burn per minted USDN.

As this parameter highly depends on the value of the USDN token, the max value for newRatio is given as a constructor argument when the UsdnProtocolFallback contract is deployed and is stored in an immutable variable.

function setSdexBurnOnDepositRatio(uint64 newRatio) external onlyRole(Constants.SET_PROTOCOL_PARAMS_ROLE);

Parameters

NameTypeDescription
newRatiouint64The new ratio.

setSecurityDepositValue

Sets the security deposit value.

The maximum value of the security deposit is 2^64 - 1 = 18446744073709551615 = 18.4 ethers.

function setSecurityDepositValue(uint64 securityDepositValue) external onlyRole(Constants.SET_PROTOCOL_PARAMS_ROLE);

Parameters

NameTypeDescription
securityDepositValueuint64The security deposit value. This value cannot be greater than MAX_SECURITY_DEPOSIT.

setExpoImbalanceLimits

Sets the imbalance limits (in basis point).

newLongImbalanceTargetBps needs to be lower than newCloseLimitBps and higher than the additive inverse of newWithdrawalLimitBps.

function setExpoImbalanceLimits(
    uint256 newOpenLimitBps,
    uint256 newDepositLimitBps,
    uint256 newWithdrawalLimitBps,
    uint256 newCloseLimitBps,
    uint256 newRebalancerCloseLimitBps,
    int256 newLongImbalanceTargetBps
) external onlyRole(Constants.SET_PROTOCOL_PARAMS_ROLE);

Parameters

NameTypeDescription
newOpenLimitBpsuint256The new open limit.
newDepositLimitBpsuint256The new deposit limit.
newWithdrawalLimitBpsuint256The new withdrawal limit.
newCloseLimitBpsuint256The new close limit.
newRebalancerCloseLimitBpsuint256The new rebalancer close limit.
newLongImbalanceTargetBpsint256The new target imbalance limit for the long side. A positive value will target below equilibrium, a negative one will target above equilibrium. If negative, the rebalancerCloseLimit will be useless since the minimum value is 1.

setMinLongPosition

Sets the minimum long position size.

This value is used to prevent users from opening positions that are too small and not worth liquidating. As this parameter highly depends on the value of the underlying asset, the max value for newMinLongPosition is given as a constructor argument when the UsdnProtocolFallback contract is deployed, and is stored in an immutable variable.

function setMinLongPosition(uint256 newMinLongPosition) external onlyRole(Constants.SET_PROTOCOL_PARAMS_ROLE);

Parameters

NameTypeDescription
newMinLongPositionuint256The new minimum long position size (with _assetDecimals).

setSafetyMarginBps

Sets the new safety margin for the liquidation price of newly open positions.

function setSafetyMarginBps(uint256 newSafetyMarginBps) external onlyRole(Constants.SET_OPTIONS_ROLE);

Parameters

NameTypeDescription
newSafetyMarginBpsuint256The new safety margin (in basis points).

setLiquidationIteration

Sets the new number of liquidations iteration for user actions.

function setLiquidationIteration(uint16 newLiquidationIteration) external onlyRole(Constants.SET_OPTIONS_ROLE);

Parameters

NameTypeDescription
newLiquidationIterationuint16The new number of liquidation iteration.

setFeeThreshold

Sets the minimum amount of fees to be collected before they can be withdrawn.

function setFeeThreshold(uint256 newFeeThreshold) external onlyRole(Constants.SET_OPTIONS_ROLE);

Parameters

NameTypeDescription
newFeeThresholduint256The minimum amount of fees to be collected before they can be withdrawn.

setTargetUsdnPrice

Sets the target USDN price.

When a rebase of USDN occurs, it will bring the price back down to this value.

function setTargetUsdnPrice(uint128 newPrice) external onlyRole(Constants.SET_USDN_PARAMS_ROLE);

Parameters

NameTypeDescription
newPriceuint128The new target price (with _priceFeedDecimals). This value cannot be greater than _usdnRebaseThreshold.

setUsdnRebaseThreshold

Sets the USDN rebase threshold.

When the price of USDN exceeds this value, a rebase will be triggered.

function setUsdnRebaseThreshold(uint128 newThreshold) external onlyRole(Constants.SET_USDN_PARAMS_ROLE);

Parameters

NameTypeDescription
newThresholduint128The new threshold value (with _priceFeedDecimals). This value cannot be smaller than _targetUsdnPrice or greater than uint128(2 * 10 ** s._priceFeedDecimals)

pause

Pauses related USDN protocol functions.

Pauses simultaneously all initiate/validate, refundSecurityDeposit and transferPositionOwnership functions. Before pausing, this function will call _applyPnlAndFunding with _lastPrice and the current timestamp. This is done to stop the funding rate from accumulating while the protocol is paused. Be sure to call unpause to update _lastUpdateTimestamp when unpausing.

function pause() external onlyRole(Constants.PAUSER_ROLE);

pauseSafe

Pauses related USDN protocol functions without applying PnLs and the funding.

Pauses simultaneously all initiate/validate, refundSecurityDeposit and transferPositionOwnership functions. This safe version will not call _applyPnlAndFunding before pausing.

function pauseSafe() external onlyRole(Constants.PAUSER_ROLE);

unpause

Unpauses related USDN protocol functions.

Unpauses simultaneously all initiate/validate, refundSecurityDeposit and transferPositionOwnership functions. This function will set _lastUpdateTimestamp to the current timestamp to prevent any funding during the pause. Only meant to be called after a pause call.

function unpause() external onlyRole(Constants.UNPAUSER_ROLE);

unpauseSafe

Unpauses related USDN protocol functions without updating _lastUpdateTimestamp.

Unpauses simultaneously all initiate/validate, refundSecurityDeposit and transferPositionOwnership functions. This safe version will not set _lastUpdateTimestamp to the current timestamp.

function unpauseSafe() external onlyRole(Constants.UNPAUSER_ROLE);