Skip to main content

ExchangeFormulas

ExchangeFormulas

Addresses

ChainAddress
Arbitrum Sepolia0xF8B27E66Ff3A28A14546aF9b123977288A150235
Base Sepolia0x39024b1e621E3E8be2520199349d9490Da4DB7E4
Base Mainnet0x42011F7BB1813564Eb025291A53D55d37b13b567

Functions

constructor

constructor(struct StorageInstance app_) public
Dev note

This contract is not designed to be upgradable and is strictly a logic contract. Hance, we are directly initializing the contract from the constructor.

calculatePrice

Apply two kinds of slippage to oracle price:

  • % penalty in range [0,∞) as amount approaches reserve (where "reserve" is max position increase allowed by risk parameters). Like typical constant-product dex slippage.
  • % offset in range [0,maxShift] proportional to current / max exposure. Improves price for orders reducing exposure
function calculatePrice(
ProductId productId,
bool increasesLongExposure,
FPUnsigned openInterestLong,
FPUnsigned openInterestShort,
FPUnsigned reserveMultiplier,
FPUnsigned amount
) public view returns (
FPUnsigned
)

Parameters

NameTypeDescription
productIdProductIdProduct for which to compute price
increasesLongExposureboolTrue if increasing long or decreasing short.
openInterestLongFPUnsignedTotal size of all this product's longs
openInterestShortFPUnsignedTotal size of all this product's shorts
reserveMultiplierFPUnsignedAdjust synthetic slippage by scaling "reserve" before computing slippage.
amountFPUnsignedSize of this order

Return Values

NameTypeDescription
[0]FPUnsignedFPUnsigned Oracle price with slippage

checkAllExposure

Reverts if exchange total open interest or any product remaining net exposure has been exceeded.

function checkAllExposure() public view

checkExposure

Revert if additional position would exceed risk params

function checkExposure(
ProductId productId,
FPUnsigned newOpenInterest,
FPUnsigned amount,
bool isLong
) public view returns (
FPUnsigned previousRemainingExposure,
FPUnsigned maxProductExposure
)

Parameters

NameTypeDescription
productIdProductIdProduct affected by position increase
newOpenInterestFPUnsignedTotal open interest (long + short) of the vault after position change
amountFPUnsignedAmount of additional open interest for this product
isLongbool

Return Values

NameTypeDescription
previousRemainingExposureFPUnsignedRemaining exposure for this product, before increase
maxProductExposureFPUnsigned

getMaxExposure

function getMaxExposure(
FPUnsigned productWeight,
FPUnsigned productExposureMultiplier
) public view returns (
FPUnsigned maxExposure
)

getMaxSafeWithdrawableMargin

Max margin that can be withdrawn from this position without reverting or liquidating

function getMaxSafeWithdrawableMargin(
FPSigned fundingPayment,
struct PositionPtr position,
FPUnsigned maxLeverage,
FPUnsigned liquidationThreshold
) public view returns (
int256
)
Dev note

If positive, removing this much liquidity should not

  • revert due to exposure/OI limits
  • revert due to out-of-bounds leverage
  • result in a liquidatable position

Parameters

NameTypeDescription
fundingPaymentFPSignedFunding payment owed by this position
positionstruct PositionPtrPosition to be withdrawn from
maxLeverageFPUnsignedMax leverage of this position's product
liquidationThresholdFPUnsignedLiquidation threshold for this product, e.g. 0.7

Return Values

NameTypeDescription
[0]int256int256 Removable margin (+) or required margin add (-)

computeIncrease

function computeIncrease(
struct IExchangeDomain.IncreaseState x
) public returns (
struct IExchangeDomain.IncreaseResult
)

aggregatePosition

Compute position values after incrementing

function aggregatePosition(
FPUnsigned currentPrice,
struct PositionPtr prevPosition,
uint256 margin,
FPUnsigned size,
FPSigned funding
) public view returns (
struct IExchangeDomain.IncreasePreview increase
)
Dev note

Linearly combine two positions into one. At any price or time where neither component would have liquidated or hit the max profit, position should have PnL equal to the sum of the two component PnLs

Parameters

NameTypeDescription
currentPriceFPUnsignedCurrent oracle price with slippage
prevPositionstruct PositionPtrPosition to modify
marginuint256margin amount of increase being applied
sizeFPUnsignedsize of increase being applied
fundingFPSignedCurrent funding value of position's product

computeDecrease

function computeDecrease(
struct PositionPtr position,
uint256 margin,
FPUnsigned size,
bool store
) external returns (
struct IExchangeDomain.DecreasePreview decrease
)

canLiquidate

Liquidation information for a position

function canLiquidate(
struct PositionPtr position,
FPUnsigned price
) public returns (
FPSigned pnl,
FPSigned funding,
bool isLiquidatable
)

Parameters

NameTypeDescription
positionstruct PositionPtrStored position to evaluate
priceFPUnsignedCurrent price of position's product

Return Values

NameTypeDescription
pnlFPSignedPnL of this position, including funding
fundingFPSignedAccrued funding cost (+) or payment (-)
isLiquidatableboolWhether PnL has reached the liquidation threshold

updateOpenInterest

Parameters to update OpenInterest

function updateOpenInterest(
ProductId productId,
FPUnsigned amount,
bool isLong,
bool isIncrease,
bool store
) public

Parameters

NameTypeDescription
productIdProductIdProduct of position being modified
amountFPUnsignedChange in position size
isLongboolWhether this is a long position
isIncreaseboolWhether the position is being increased or decreased.
storeboolWhere OI is being updated or just calculating preview value

increaseProductTotalPosition

function increaseProductTotalPosition(
ProductId productId,
bool isLong,
uint256 margin,
FPUnsigned size,
FPSigned funding,
FPUnsigned price
) public

decreaseProductTotalPosition

Decrease/delete the total position to incorporate a user decrease

function decreaseProductTotalPosition(
struct PositionPtr userPosition,
uint256 margin,
FPUnsigned deltaSize
) external

Parameters

NameTypeDescription
userPositionstruct PositionPtrPosition to stop tracking in productTotalLongs/Shorts
marginuint256Margin by which this position is decreasing
deltaSizeFPUnsignedSize by which this position is decreasing (0 for decreaseMargin)

updateAndGetFundingPayment

Update this position's product's cumulative funding and interest, and then compute the payment owed by the position.

function updateAndGetFundingPayment(
ProductId productId,
bool isLong,
FPUnsigned size,
FPSigned funding
) public returns (
FPSigned fundingPayment
)
Dev note

Integrates current funding rate over time between last update and now. See FundingManager.

Parameters

NameTypeDescription
productIdProductIdproductId of Position that owes (or is owed) a payment
isLongboolisLong of Position that owes (or is owed) a payment
sizeFPUnsignedsize of Position that owes (or is owed) a payment
fundingFPSignedfunding of Position that owes (or is owed) a payment

Return Values

NameTypeDescription
fundingPaymentFPSignedDebt owed by this position. Negative values increase position value.

canTakeProfit

Return whether a position is allowed to take profit: if either

  • the price has changed by more than minPriceChange
  • minProfitTime has elapsed
function canTakeProfit(
bool isLong,
uint256 positionTimestamp,
FPUnsigned positionPrice,
FPUnsigned oraclePrice,
FPUnsigned minPriceChange,
uint256 minProfitTime
) public view returns (
bool
)

Parameters

NameTypeDescription
isLongboolWhether this is a long position
positionTimestampuint256Time position was last increased
positionPriceFPUnsignedComposite price when position was increase/updated
oraclePriceFPUnsignedCurrent oracle price
minPriceChangeFPUnsignedMinimum price change to take profit. This should be larger than the minimum oracle price change
minProfitTimeuint256Time to wait for minPriceChange before realizing profit anyway.

Return Values

NameTypeDescription
[0]boolcanTakeProfit If a position is allowed to take profit.

getPnl

Compute the PnL of a position, in collateral units, based on price action.

function getPnl(
bool isLong,
FPUnsigned positionPrice,
FPUnsigned size,
FPUnsigned price
) public pure returns (
FPSigned pnl
)

Parameters

NameTypeDescription
isLongboolIf this is a long position (false=short)
positionPriceFPUnsignedComposite price when position was increase/updated
sizeFPUnsignedSize (margin * leverage) of the position
priceFPUnsignedCurrent price of the position, including any modifications

Return Values

NameTypeDescription
pnlFPSignedProfit (positive) or loss (negative) attributable to position

getFundingPayment

Compute the funding payment owed by a position

function getFundingPayment(
bool isLong,
FPUnsigned size,
FPSigned funding,
FPSigned cumulativeFunding,
FPUnsigned cumulativeInterest
) public pure returns (
FPSigned fundingPayment
)

Parameters

NameTypeDescription
isLongboolWhether this position is long (false=short)
sizeFPUnsignedSize (margin * leverage) of the position
fundingFPSignedComposite cumulative funding+interest when the position was created/updated
cumulativeFundingFPSignedCurrent cumulative funding for the position's product.
cumulativeInterestFPUnsignedCurrent cumulative base interest rate for the position's product

Return Values

NameTypeDescription
fundingPaymentFPSignedFunding payment owed by the position. Negative values increase the value of the position.

getTradeFee

Compute the trade fee incurred by changing a position's size

function getTradeFee(
FPUnsigned size,
FPUnsigned productFee,
address user,
address sender
) public view returns (
uint256 tradeFee
)

Parameters

NameTypeDescription
sizeFPUnsignedTotal size of the increase/decrease
productFeeFPUnsignedProduct's normal trade fee rate
useraddressOwner of the position
senderaddressSender of the transaction

Return Values

NameTypeDescription
tradeFeeuint256Collateral owed by user

getUtilizationRatio

Compute utilization ratio of the vault, and whether instant redemptions should be allowed.

function getUtilizationRatio(
FPUnsigned totalOpenInterest,
uint256 balance,
FPSigned totalPnl,
uint256 pendingWithdraw,
FPUnsigned healthyUtilizationRatio
) public pure returns (
bool instantRedeemAvailable,
FPSigned utilizationRatio
)
Dev note

Utilization ratio: {totalOpenInterest}{balancependingWithdrawtotalPnl}\frac\{totalOpenInterest\}\{balance - pendingWithdraw - totalPnl\}. If the denominator, effective balance, is zero, return utilizationRatio=0 and allow instant redemptions only if there is no open interest.

Parameters

NameTypeDescription
totalOpenInterestFPUnsignedSum of sizes of all open positions
balanceuint256Collateral balance of the vault (deposits - trader PnL)
totalPnlFPSignedOutstanding total PnL of all positions
pendingWithdrawuint256Estimated collateral value of all pending withdraw requests
healthyUtilizationRatioFPUnsignedThe maximum utilization ratio before instant withdrawals are forbidden

Return Values

NameTypeDescription
instantRedeemAvailableboolutilizationRatiohealthyUtilizationRatioutilizationRatio \leq healthyUtilizationRatio
utilizationRatioFPSignedtotalOpenInterestbalancependingWithdrawtotalPnl\frac{totalOpenInterest}{balance - pendingWithdraw - totalPnl}

getWithdrawDuration

Compute the duration of a withdraw request

function getWithdrawDuration(
FPSigned utilizationRatio,
FPUnsigned requestedShareFraction,
FPUnsigned healthyUtilizationRatio,
uint256 maxWithdrawDuration,
uint256 durationPerUtilizationRatio
) public pure returns (
uint64 withdrawDuration
)

Parameters

NameTypeDescription
utilizationRatioFPSignedutilization ratio (given by _getUtilizationRatio)
requestedShareFractionFPUnsignedFraction of the vault shares requested. [0,1][0,1]
healthyUtilizationRatioFPUnsignedUtilization ratio below which withdraws should be immediate
maxWithdrawDurationuint256Maximum permitted withdraw request duration
durationPerUtilizationRatiouint256See DomFiVault.setTotalDurationPerUtilizationRatio

Return Values

NameTypeDescription
withdrawDurationuint64Length of a withdraw request

canLiquidateBulk

Liquidation information for each position in positionIds

function canLiquidateBulk(
PositionId[] positionIds
) public returns (
FPSigned[] pnl,
FPSigned[] funding,
bool[] isLiquidatable
)

Parameters

NameTypeDescription
positionIdsPositionId[]Positions to compute liquidation info for

Return Values

NameTypeDescription
pnlFPSigned[]Position PnL. See getPositionPnlAndFunding
fundingFPSigned[]Position funding. See getPositionPnlAndFunding
isLiquidatablebool[]Whether this position is liquidatable

getPositionPnlAndFunding

function getPositionPnlAndFunding(
ProductId productId,
bool isLong,
FPUnsigned size,
FPUnsigned positionPrice,
uint256 margin,
FPSigned funding,
FPUnsigned price
) public returns (
FPSigned pnl,
FPSigned fundingDebt
)

getPositionPnlRate

function getPositionPnlRate(PositionId positionId) public returns (FPSigned pnlRate)

getTotalPnl

function getTotalPnl() external returns (FPSigned totalPnl)

validateOI

function validateOI(uint256 balance) external view

canRemove

function canRemove(PositionId positionId) public returns (bool canRemove_, int256 removeableMargin)

Variables

props

positions

products