PoolInternal

Git Source

Inherits: IPoolInternal, IPoolEvents, ERC1155EnumerableInternal

State Variables

FACTORY

address internal immutable FACTORY;

ROUTER

address internal immutable ROUTER;

WRAPPED_NATIVE_TOKEN

address internal immutable WRAPPED_NATIVE_TOKEN;

FEE_RECEIVER

address internal immutable FEE_RECEIVER;

REFERRAL

address internal immutable REFERRAL;

SETTINGS

address internal immutable SETTINGS;

VAULT_REGISTRY

address internal immutable VAULT_REGISTRY;

VXPREMIA

address internal immutable VXPREMIA;

PROTOCOL_FEE_PERCENTAGE

UD60x18 internal constant PROTOCOL_FEE_PERCENTAGE = UD60x18.wrap(0.5e18);

AMM_PREMIUM_FEE_PERCENTAGE

UD60x18 internal constant AMM_PREMIUM_FEE_PERCENTAGE = UD60x18.wrap(0.03e18);

AMM_NOTIONAL_FEE_PERCENTAGE

UD60x18 internal constant AMM_NOTIONAL_FEE_PERCENTAGE = UD60x18.wrap(0.003e18);

ORDERBOOK_NOTIONAL_FEE_PERCENTAGE

UD60x18 internal constant ORDERBOOK_NOTIONAL_FEE_PERCENTAGE = UD60x18.wrap(0.0008e18);

MAX_PREMIUM_FEE_PERCENTAGE

UD60x18 internal constant MAX_PREMIUM_FEE_PERCENTAGE = UD60x18.wrap(0.125e18);

EXERCISE_FEE_PERCENTAGE

UD60x18 internal constant EXERCISE_FEE_PERCENTAGE = UD60x18.wrap(0.003e18);

MAX_EXERCISE_FEE_PERCENTAGE

UD60x18 internal constant MAX_EXERCISE_FEE_PERCENTAGE = UD60x18.wrap(0.125e18);

WITHDRAWAL_DELAY

uint256 internal constant WITHDRAWAL_DELAY = 60;

FILL_QUOTE_OB_TYPE_HASH

bytes32 internal constant FILL_QUOTE_OB_TYPE_HASH = keccak256(
    "FillQuoteOB(address provider,address taker,uint256 price,uint256 size,bool isBuy,uint256 deadline,uint256 salt)"
);

Functions

constructor

constructor(
    address factory,
    address router,
    address wrappedNativeToken,
    address feeReceiver,
    address referral,
    address settings,
    address vaultRegistry,
    address vxPremia
);

_takerFee

Calculates the fee for a trade based on the size and premium of the trade.

function _takerFee(
    address taker,
    UD60x18 size,
    UD60x18 premium,
    bool isPremiumNormalized,
    UD60x18 strike,
    bool isCallPool,
    bool isOrderbook
) internal view returns (UD60x18);

Parameters

NameTypeDescription
takeraddressThe taker of a trade
sizeUD60x18The size of a trade (number of contracts) (18 decimals)
premiumUD60x18The total cost of option(s) for a purchase (18 decimals)
isPremiumNormalizedboolWhether the premium given is already normalized by strike or not (Ex: For a strike of 1500, and a premium of 750, the normalized premium would be 0.5)
strikeUD60x18The strike of the option (18 decimals)
isCallPoolboolWhether the pool is a call pool or not
isOrderbookboolWhether the fee is for the fillQuoteOB function or not

Returns

NameTypeDescription
<none>UD60x18The taker fee for an option trade denormalized. (18 decimals)

_exerciseFee

Calculates the fee for an exercise. It is the minimum between a percentage of the intrinsic value of options exercised, or a percentage of the notional value.

function _exerciseFee(address taker, UD60x18 size, UD60x18 intrinsicValue, UD60x18 strike, bool isCallPool)
    internal
    view
    returns (UD60x18);

Parameters

NameTypeDescription
takeraddressThe taker of a trade
sizeUD60x18The size of a trade (number of contracts) (18 decimals)
intrinsicValueUD60x18Total intrinsic value of all the contracts exercised, denormalized (18 decimals)
strikeUD60x18The strike of the option (18 decimals)
isCallPoolboolWhether the pool is a call pool or not

Returns

NameTypeDescription
<none>UD60x18The fee to exercise an option, denormalized (18 decimals)

_getQuoteAMM

Gives a quote for a trade

function _getQuoteAMM(address taker, UD60x18 size, bool isBuy)
    internal
    view
    returns (uint256 totalNetPremium, uint256 totalTakerFee);

Parameters

NameTypeDescription
takeraddressThe taker of the trade
sizeUD60x18The number of contracts being traded (18 decimals)
isBuyboolWhether the taker is buying or selling

Returns

NameTypeDescription
totalNetPremiumuint256The premium which has to be paid to complete the trade (Net of fees) (poolToken decimals)
totalTakerFeeuint256The taker fees to pay (Included in premiumNet) (poolToken decimals)

_pendingClaimableFees

Returns amount of claimable fees from pending update of claimable fees for the position. This does not include pData.claimableFees

function _pendingClaimableFees(
    PoolStorage.Layout storage l,
    Position.KeyInternal memory p,
    Position.Data storage pData,
    UD60x18 balance
) internal view returns (UD60x18 claimableFees, SD49x28 feeRate);

_calculateClaimableFees

Returns the amount of fees an LP can claim for a position (without claiming)

function _calculateClaimableFees(SD49x28 feeRate, SD49x28 lastFeeRate, UD50x28 liquidityPerTick)
    internal
    pure
    returns (UD60x18);

_updateClaimableFees

Updates the amount of fees an LP can claim for a position (without claiming)

function _updateClaimableFees(Position.Data storage pData, SD49x28 feeRate, UD50x28 liquidityPerTick) internal;

_updateClaimableFees

Updates the amount of fees an LP can claim for a position

function _updateClaimableFees(
    PoolStorage.Layout storage l,
    Position.KeyInternal memory p,
    Position.Data storage pData,
    UD60x18 balance
) internal;

_claim

Updates the claimable fees of a position and transfers the claimed fees to the operator of the position. Then resets the claimable fees to zero.

function _claim(Position.KeyInternal memory p) internal returns (uint256);

Parameters

NameTypeDescription
pPosition.KeyInternalThe position to claim fees for

Returns

NameTypeDescription
<none>uint256The amount of fees claimed (poolToken decimals)

_claimProtocolFees

Claims the protocol fees and transfers them to the fee receiver

function _claimProtocolFees() internal;

_deposit

Deposits a position (combination of owner/operator, price range, bid/ask collateral, and long/short contracts) into the pool.

function _deposit(Position.KeyInternal memory p, DepositArgsInternal memory args)
    internal
    returns (Position.Delta memory delta);

Parameters

NameTypeDescription
pPosition.KeyInternalThe position key
argsDepositArgsInternalThe deposit parameters

Returns

NameTypeDescription
deltaPosition.DeltaThe amount of collateral / longs / shorts deposited

_deposit

Deposits a position (combination of owner/operator, price range, bid/ask collateral, and long/short contracts) into the pool.

function _deposit(Position.KeyInternal memory p, DepositArgsInternal memory args, bool isBidIfStrandedMarketPrice)
    internal
    returns (Position.Delta memory delta);

Parameters

NameTypeDescription
pPosition.KeyInternalThe position key
argsDepositArgsInternalThe deposit parameters
isBidIfStrandedMarketPriceboolWhether this is a bid or ask order when the market price is stranded (This argument doesnt matter if market price is not stranded)

Returns

NameTypeDescription
deltaPosition.DeltaThe amount of collateral / longs / shorts deposited

_depositFeeAndTicksUpdate

Handles fee/tick updates and mints LP token on deposit

function _depositFeeAndTicksUpdate(
    PoolStorage.Layout storage l,
    Position.Data storage pData,
    Position.KeyInternal memory p,
    UD60x18 belowLower,
    UD60x18 belowUpper,
    UD60x18 size,
    uint256 tokenId
) internal;

_withdraw

Withdraws a position (combination of owner/operator, price range, bid/ask collateral, and long/short contracts) from the pool Tx will revert if market price is not between minMarketPrice and maxMarketPrice.

function _withdraw(Position.KeyInternal memory p, UD60x18 size, UD60x18 minMarketPrice, UD60x18 maxMarketPrice)
    internal
    returns (Position.Delta memory delta);

Parameters

NameTypeDescription
pPosition.KeyInternalThe position key
sizeUD60x18The position size to withdraw (18 decimals)
minMarketPriceUD60x18Min market price, as normalized value. (If below, tx will revert) (18 decimals)
maxMarketPriceUD60x18Max market price, as normalized value. (If above, tx will revert) (18 decimals)

Returns

NameTypeDescription
deltaPosition.DeltaThe amount of collateral / longs / shorts withdrawn

_transferTokens

Handle transfer of collateral / longs / shorts on deposit or withdrawal

WARNING: collateral must be scaled to the collateral token decimals

function _transferTokens(
    PoolStorage.Layout storage l,
    address from,
    address to,
    uint256 collateral,
    UD60x18 longs,
    UD60x18 shorts
) internal;

_writeFrom

Transfers collateral + fees from underwriter and sends long/short tokens to both parties

function _writeFrom(address underwriter, address longReceiver, UD60x18 size, address referrer) internal;

_trade

Completes a trade of size on side via the AMM using the liquidity in the Pool.

function _trade(TradeArgsInternal memory args)
    internal
    returns (uint256 premiumWithFees, Position.Delta memory delta);

Parameters

NameTypeDescription
argsTradeArgsInternalTrade parameters

Returns

NameTypeDescription
premiumWithFeesuint256The premium paid or received by the taker for the trade (poolToken decimals)
deltaPosition.DeltaThe net collateral / longs / shorts change for taker of the trade.

_getPricing

Returns the pricing arguments at the current tick

function _getPricing(PoolStorage.Layout storage l, bool isBuy) internal view returns (Pricing.Args memory);

_getTradeDelta

Compute the change in short / long option contracts of a user in order to transfer the contracts and execute a trade

function _getTradeDelta(address user, UD60x18 size, bool isBuy) internal view returns (Position.Delta memory delta);

_calculateAndUpdateUserAssets

function _calculateAndUpdateUserAssets(
    PoolStorage.Layout storage l,
    address user,
    UD60x18 totalPremium,
    UD60x18 size,
    bool isBuy
) internal returns (Position.Delta memory delta);

_calculateAssetsUpdate

Calculate the asset update for user

function _calculateAssetsUpdate(
    PoolStorage.Layout storage l,
    address user,
    UD60x18 totalPremium,
    UD60x18 size,
    bool isBuy
) internal view returns (Position.Delta memory delta);

_updateUserAssets

Execute a trade by transferring the net change in short and long option contracts and collateral to / from a user.

function _updateUserAssets(PoolStorage.Layout storage l, address user, Position.Delta memory delta) internal;

_calculateQuoteOBPremiumAndFee

Calculates the OB quote premium and fee

function _calculateQuoteOBPremiumAndFee(
    PoolStorage.Layout storage l,
    address taker,
    address referrer,
    UD60x18 size,
    UD60x18 price,
    bool isBuy
) internal view returns (PremiumAndFeeInternal memory r);

_fillQuoteOB

Functionality to support the OB / OTC system. An LP can create a OB quote for which he will do an OTC trade through the exchange. Takers can buy from / sell to the LP partially or fully while having the price guaranteed.

function _fillQuoteOB(FillQuoteOBArgsInternal memory args, QuoteOB memory quoteOB)
    internal
    returns (uint256 premiumTaker, Position.Delta memory deltaTaker);

Parameters

NameTypeDescription
argsFillQuoteOBArgsInternalThe fillQuoteOB parameters
quoteOBQuoteOBThe OB quote given by the provider

Returns

NameTypeDescription
premiumTakeruint256The premium paid by the taker (poolToken decimals)
deltaTakerPosition.DeltaThe net collateral / longs / shorts change for taker of the trade.

_annihilate

Annihilate a pair of long + short option contracts to unlock the stored collateral.

This function can be called post or prior to expiration.

function _annihilate(address owner, UD60x18 size) internal;

_transferPosition

Transfer an LP position to another owner.

This function can be called post or prior to expiration.

function _transferPosition(Position.KeyInternal memory srcP, address newOwner, address newOperator, UD60x18 size)
    internal;

Parameters

NameTypeDescription
srcPPosition.KeyInternalThe position key
newOwneraddressThe new owner of the transferred liquidity
newOperatoraddressThe new operator of the transferred liquidity
sizeUD60x18

_calculateExerciseValue

Calculates the exercise value of a position

function _calculateExerciseValue(PoolStorage.Layout storage l, UD60x18 size) internal returns (UD60x18);

_calculateCollateralValue

Calculates the collateral value of a position

function _calculateCollateralValue(PoolStorage.Layout storage l, UD60x18 size, UD60x18 exerciseValue)
    internal
    view
    returns (UD60x18);

_beforeExerciseOrSettle

Handle operations that need to be done before exercising or settling

function _beforeExerciseOrSettle(PoolStorage.Layout storage l, bool isLong, address holder)
    internal
    returns (UD60x18 size, UD60x18 exerciseValue, UD60x18 collateral);

_exercise

Exercises all long options held by an owner

function _exercise(address holder, UD60x18 costPerHolder)
    internal
    returns (uint256 exerciseValue, uint256 exerciseFee, bool success);

Parameters

NameTypeDescription
holderaddressThe holder of the contracts
costPerHolderUD60x18The cost charged by the authorized operator, per option holder (18 decimals)

Returns

NameTypeDescription
exerciseValueuint256The amount of collateral resulting from the exercise, ignoring costs applied during automatic exercise (poolToken decimals)
exerciseFeeuint256The amount of fees paid to the protocol during exercise (18 decimals)
successboolWhether the exercise was successful or not. This will be false if size to exercise size was zero

_settle

Settles all short options held by an owner

function _settle(address holder, UD60x18 costPerHolder) internal returns (uint256 collateral, bool success);

Parameters

NameTypeDescription
holderaddressThe holder of the contracts
costPerHolderUD60x18The cost charged by the authorized operator, per option holder (18 decimals)

Returns

NameTypeDescription
collateraluint256The amount of collateral resulting from the settlement, ignoring costs applied during automatic settlement (poolToken decimals)
successboolWhether the settlement was successful or not. This will be false if size to settle was zero

_settlePosition

Reconciles a user's position to account for settlement payouts post-expiration.

function _settlePosition(Position.KeyInternal memory p, UD60x18 costPerHolder)
    internal
    returns (uint256 collateral, bool success);

Parameters

NameTypeDescription
pPosition.KeyInternalThe position key
costPerHolderUD60x18The cost charged by the authorized operator, per position holder (18 decimals)

Returns

NameTypeDescription
collateraluint256The amount of collateral resulting from the settlement, ignoring costs applied during automatic settlement (poolToken decimals)
successboolWhether the settlement was successful or not. This will be false if size to settle was zero

_tryCacheSettlementPrice

Fetch and cache the settlement price, if it has not been cached yet. Returns the cached price

function _tryCacheSettlementPrice(PoolStorage.Layout storage l) internal returns (UD60x18);

_deletePosition

Deletes the pKeyHash from positions mapping

function _deletePosition(PoolStorage.Layout storage l, bytes32 pKeyHash) internal;

_getNearestTicksBelow

Returns the nearest tick below lower and the nearest tick below upper

function _getNearestTicksBelow(UD60x18 lower, UD60x18 upper)
    internal
    view
    returns (UD60x18 nearestBelowLower, UD60x18 nearestBelowUpper);

_getNearestTickBelow

Gets the nearest tick that is less than or equal to price

function _getNearestTickBelow(UD60x18 price) internal view returns (UD60x18);

_getTick

Get a tick, reverts if tick is not found

function _getTick(UD60x18 price) internal view returns (Tick memory);

_tryGetTick

Try to get tick, does not revert if tick is not found

function _tryGetTick(UD60x18 price) internal view returns (Tick memory tick, bool tickFound);

_getOrCreateTick

Creates a Tick for a given price, or returns the existing tick.

function _getOrCreateTick(UD60x18 price, UD60x18 priceBelow) internal returns (Tick memory);

Parameters

NameTypeDescription
priceUD60x18The price of the Tick (18 decimals)
priceBelowUD60x18The price of the nearest Tick below (18 decimals)

Returns

NameTypeDescription
<none>Ticktick The Tick for a given price

_removeTickIfNotActive

Removes a tick if it does not mark the beginning or the end of a range order.

function _removeTickIfNotActive(UD60x18 price) internal;

_updateTicks

Updates the tick deltas following a deposit or withdrawal

function _updateTicks(
    UD60x18 lower,
    UD60x18 upper,
    UD50x28 marketPrice,
    SD49x28 delta,
    bool isNewDeposit,
    bool isFullWithdrawal,
    Position.OrderType orderType
) internal;

_updateGlobalFeeRate

Updates the global fee rate

function _updateGlobalFeeRate(PoolStorage.Layout storage l, UD60x18 makerRebate) internal;

_cross

Crosses the active tick either to the left if the LT is selling to the pool. A cross is only executed if no bid or ask liquidity is remaining within the active tick range.

function _cross(bool isBuy) internal;

Parameters

NameTypeDescription
isBuyboolWhether the trade is a buy or a sell.

_rangeFeeRate

Calculates the growth and exposure change between the lower and upper Ticks of a Position.

l         ▼         u
----|----|-------|xxxxxxxxxxxxxxxxxxx|--------|---------
=> (global - external(l) - external(u))
▼    l                   u
----|----|-------|xxxxxxxxxxxxxxxxxxx|--------|---------
=> (global - (global - external(l)) - external(u))
l                   u    ▼
----|----|-------|xxxxxxxxxxxxxxxxxxx|--------|---------
=> (global - external(l) - (global - external(u)))
function _rangeFeeRate(
    PoolStorage.Layout storage l,
    UD60x18 lower,
    UD60x18 upper,
    UD50x28 lowerTickExternalFeeRate,
    UD50x28 upperTickExternalFeeRate
) internal view returns (SD49x28);

_getStrandedArea

Gets the lower and upper bound of the stranded market area when it exists. In case the stranded market area does not exist it will return the stranded market area the maximum tick price for both the lower and the upper, in which case the market price is not stranded given any range order info order.

function _getStrandedArea(PoolStorage.Layout storage l) internal view returns (UD60x18 lower, UD60x18 upper);

Returns

NameTypeDescription
lowerUD60x18Lower bound of the stranded market price area (Default : PoolStorage.MAX_TICK_PRICE + ONE = 2e18) (18 decimals)
upperUD60x18Upper bound of the stranded market price area (Default : PoolStorage.MAX_TICK_PRICE + ONE = 2e18) (18 decimals)

_isMarketPriceStranded

Returns true if the market price is stranded

function _isMarketPriceStranded(PoolStorage.Layout storage l, Position.KeyInternal memory p, bool isBid)
    internal
    view
    returns (bool);

_getStrandedMarketPriceUpdate

In case the market price is stranded the market price needs to be set to the upper (lower) tick of the bid (ask) order.

function _getStrandedMarketPriceUpdate(Position.KeyInternal memory p, bool isBid) internal pure returns (UD50x28);

_revertIfTickWidthInvalid

Revert if the tick width is invalid

function _revertIfTickWidthInvalid(UD60x18 price) internal pure;

_quoteOBHash

Returns the encoded OB quote hash

function _quoteOBHash(IPoolInternal.QuoteOB memory quoteOB) internal view returns (bytes32);

_balanceOfUD60x18

Returns the balance of user for tokenId as UD60x18

function _balanceOfUD60x18(address user, uint256 tokenId) internal view returns (UD60x18);

_mint

Mints amount of id and assigns it to account

function _mint(address account, uint256 id, UD60x18 amount) internal;

_burn

Burns amount of id assigned to account

function _burn(address account, uint256 id, UD60x18 amount) internal;

_useReferral

Applies the primary and secondary referral rebates, if total rebates are greater than zero

function _useReferral(
    PoolStorage.Layout storage l,
    address user,
    address referrer,
    UD60x18 primaryReferralRebate,
    UD60x18 secondaryReferralRebate
) internal;

_isRateNonTerminating

Checks if the liquidity rate of the range results in a non-terminating decimal.

lower should NOT be equal to upper, to avoid running into an infinite loop

function _isRateNonTerminating(UD60x18 lower, UD60x18 upper) internal pure returns (bool);

_revertIfRangeInvalid

Revert if the lower and upper tick range is invalid

function _revertIfRangeInvalid(UD60x18 lower, UD60x18 upper) internal pure;

_revertIfZeroSize

Revert if size is zero

function _revertIfZeroSize(UD60x18 size) internal pure;

_revertIfOptionNotExpired

Revert if option is not expired

function _revertIfOptionNotExpired(PoolStorage.Layout storage l) internal view;

_revertIfOptionExpired

Revert if option is expired

function _revertIfOptionExpired(PoolStorage.Layout storage l) internal view;

_revertIfWithdrawalDelayNotElapsed

Revert if withdrawal delay has not elapsed

function _revertIfWithdrawalDelayNotElapsed(Position.Data storage position) internal view;

_revertIfTradeAboveMaxSlippage

Revert if totalPremium is exceeds max slippage

function _revertIfTradeAboveMaxSlippage(uint256 totalPremium, uint256 premiumLimit, bool isBuy) internal pure;

_revertIfInvalidSize

function _revertIfInvalidSize(UD60x18 lower, UD60x18 upper, UD60x18 size) internal pure;

_revertIfDepositWithdrawalAboveMaxSlippage

Revert if marketPrice is below minMarketPrice or above maxMarketPrice

function _revertIfDepositWithdrawalAboveMaxSlippage(UD60x18 marketPrice, UD60x18 minMarketPrice, UD60x18 maxMarketPrice)
    internal
    pure;

_areQuoteOBAndBalanceValid

Returns true if OB quote and OB quote balance are valid

function _areQuoteOBAndBalanceValid(
    PoolStorage.Layout storage l,
    FillQuoteOBArgsInternal memory args,
    QuoteOB memory quoteOB,
    bytes32 quoteOBHash
) internal view returns (bool isValid, InvalidQuoteOBError error);

_revertIfQuoteOBInvalid

Revert if OB quote is invalid

function _revertIfQuoteOBInvalid(
    PoolStorage.Layout storage l,
    FillQuoteOBArgsInternal memory args,
    QuoteOB memory quoteOB,
    bytes32 quoteOBHash
) internal view;

_revertIfPositionDoesNotExist

Revert if the position does not exist

function _revertIfPositionDoesNotExist(address owner, uint256 tokenId, UD60x18 balance) internal pure;

_revertIfInvalidPositionState

Revert if the position is in an invalid state

function _revertIfInvalidPositionState(uint256 balance, uint256 lastDeposit) internal pure;

_isQuoteOBValid

Returns true if OB quote is valid

function _isQuoteOBValid(
    PoolStorage.Layout storage l,
    FillQuoteOBArgsInternal memory args,
    QuoteOB memory quoteOB,
    bytes32 quoteOBHash,
    bool revertIfInvalid
) internal view returns (bool, InvalidQuoteOBError);

_isQuoteOBBalanceValid

Returns true if OB quote balance is valid

function _isQuoteOBBalanceValid(
    PoolStorage.Layout storage l,
    FillQuoteOBArgsInternal memory args,
    QuoteOB memory quoteOB
) internal view returns (bool, InvalidQuoteOBError);

_revertIfOperatorNotAuthorized

Revert if operator is not msg.sender

function _revertIfOperatorNotAuthorized(address operator) internal view;

_revertIfActionNotAuthorized

Revert if operator is not authorized by holder to call action

function _revertIfActionNotAuthorized(address holder, IUserSettings.Action action) internal view;

_revertIfCostNotAuthorized

Revert if cost in wrapped native token is not authorized by holder

function _revertIfCostNotAuthorized(address holder, UD60x18 costInPoolToken) internal view;

_revertIfCostExceedsPayout

Revert if cost exceeds payout

function _revertIfCostExceedsPayout(UD60x18 cost, UD60x18 payout) internal pure;

_revertIfDifferenceOfSizeAndContractDeltaTooLarge

function _revertIfDifferenceOfSizeAndContractDeltaTooLarge(UD60x18 offset, UD60x18 size) internal pure;

_beforeTokenTransfer

_beforeTokenTransfer wrapper, updates tokenIds set

function _beforeTokenTransfer(
    address operator,
    address from,
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) internal virtual override;