keeper

package
v0.3.0-dev1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 26, 2023 License: AGPL-3.0 Imports: 41 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewMsgServerImpl

func NewMsgServerImpl(keeper types.ClobKeeper) types.MsgServer

NewMsgServerImpl returns an implementation of the MsgServer interface for the provided Keeper.

Types

type CumulativePnL

type CumulativePnL struct {
	// PnL calculations.
	SubaccountPnL               map[satypes.SubaccountId]*big.Int
	SubaccountPositionSizeDelta map[satypes.SubaccountId]*big.Int

	// Metadata.
	NumFills            int
	VolumeQuoteQuantums *big.Int

	// Cached fields used in the calculation of PnL.
	// These should not be modified after initialization.
	ClobPair              types.ClobPair
	MidPriceSubticks      types.Subticks
	PerpetualFundingIndex *big.Int
}

CumulativePnL keeps track of the cumulative PnL for each subaccount per market.

func (*CumulativePnL) AddDeltaToSubaccount

func (c *CumulativePnL) AddDeltaToSubaccount(
	subaccountId satypes.SubaccountId,
	delta *big.Int,
)

AddDeltaToSubaccount adds the given delta to the PnL for the given subaccount.

func (*CumulativePnL) AddPnLForTradeWithFilledQuoteQuantums

func (c *CumulativePnL) AddPnLForTradeWithFilledQuoteQuantums(
	subaccountId satypes.SubaccountId,
	isBuy bool,
	filledQuoteQuantums *big.Int,
	filledQuantums satypes.BaseQuantums,
	feePpm int32,
) (err error)

AddPnLForTradeWithFilledQuoteQuantums calculates the PnL for the given trade and adds it to the cumulative PnL. The PnL for a buy order is calculated as:

PnL = n(p - p_mid) - f

The PnL for a sell order is calculated as:

PnL = n(p_mid - p) - f

where n is the size of the trade, p is the price of the trade, p_mid is the mid price of validator's ordrbook, and f is the fee subaccount pays for the matched trade. This function returns an error if the clob pair associated with the order is a spot clob pair.

func (*CumulativePnL) AddPnLForTradeWithFilledSubticks

func (c *CumulativePnL) AddPnLForTradeWithFilledSubticks(
	subaccountId satypes.SubaccountId,
	isBuy bool,
	filledSubticks types.Subticks,
	filledQuantums satypes.BaseQuantums,
	feePpm int32,
) (err error)

AddPnLForTradeWithFilledSubticks calculates PnL for a given trade using the filled subticks. This method calculates the filledQuoteQuantums before calling AddPnLForTradeWithFilledQuoteQuantums.

func (*CumulativePnL) CalculateMev

func (c *CumulativePnL) CalculateMev(other *CumulativePnL) *big.Float

CalculateMev calculates and returns the mev value given the block proposer PnL and the validator PnL, using the following formula:

MEV = 1/2 * Σ|blockProposerPnL - validatorPnL|

Note that this method modifies the receiver.

type Keeper

type Keeper struct {
	MemClob                      types.MemClob
	UntriggeredConditionalOrders map[types.ClobPairId]*UntriggeredConditionalOrders
	PerpetualIdToClobPairId      map[uint32][]types.ClobPairId

	MaxLiquidationOrdersPerBlock    uint32
	MaxDeleveragingAttemptsPerBlock uint32
	// contains filtered or unexported fields
}

func NewKeeper

func NewKeeper(
	cdc codec.BinaryCodec,
	storeKey storetypes.StoreKey,
	memKey storetypes.StoreKey,
	liquidationsStoreKey storetypes.StoreKey,
	authorities []string,
	memClob types.MemClob,
	subaccountsKeeper types.SubaccountsKeeper,
	assetsKeeper types.AssetsKeeper,
	blockTimeKeeper types.BlockTimeKeeper,
	bankKeeper types.BankKeeper,
	feeTiersKeeper types.FeeTiersKeeper,
	perpetualsKeeper types.PerpetualsKeeper,
	statsKeeper types.StatsKeeper,
	rewardsKeeper types.RewardsKeeper,
	indexerEventManager indexer_manager.IndexerEventManager,
	txDecoder sdk.TxDecoder,
	clobFlags flags.ClobFlags,
	placeOrderRateLimiter rate_limit.RateLimiter[*types.MsgPlaceOrder],
	cancelOrderRateLimiter rate_limit.RateLimiter[*types.MsgCancelOrder],
) *Keeper

func (Keeper) AddOrderToOrderbookCollatCheck

func (k Keeper) AddOrderToOrderbookCollatCheck(
	ctx sdk.Context,
	clobPairId types.ClobPairId,

	subaccountOpenOrders map[satypes.SubaccountId][]types.PendingOpenOrder,
) (
	success bool,
	successPerUpdate map[satypes.SubaccountId]satypes.UpdateResult,
)

AddOrderToOrderbookCollatCheck performs collateralization checks for orders to determine whether or not they may be added to the orderbook.

func (Keeper) AddOrdersForPruning

func (k Keeper) AddOrdersForPruning(ctx sdk.Context, orderIds []types.OrderId, prunableBlockHeight uint32)

AddOrdersForPruning creates or updates a slice of `orderIds` to state for potential future pruning from state. These orders will be checked for pruning from state at `prunableBlockHeight`. If the `orderIds` slice provided contains duplicates, the duplicates will be ignored.

func (Keeper) AddPreexistingStatefulOrder

func (k Keeper) AddPreexistingStatefulOrder(
	ctx sdk.Context,
	order *types.Order,
	blockHeight uint32,
	memclob types.MemClob,
) (
	orderSizeOptimisticallyFilledFromMatchingQuantums satypes.BaseQuantums,
	orderStatus types.OrderStatus,
	offchainUpdates *types.OffchainUpdates,
	err error,
)

AddPreexistingStatefulOrder performs stateful validation on an order and adds it to the specified memclob. This function does not add the order into state, since it is assumed to be preexisting. Function panics if the specified order is not stateful.

func (Keeper) AddSettlementForPositionDelta

func (k Keeper) AddSettlementForPositionDelta(
	ctx sdk.Context,
	perpetualKeeper process.ProcessPerpetualKeeper,
	clobPairToPnLs map[types.ClobPairId]*CumulativePnL,
) (err error)

AddSettlementForPositionDelta Calculate the total settlement for a subaccount's position delta. This function propagates errors from perpetualKeeper.

func (Keeper) AddUntriggeredConditionalOrders

func (k Keeper) AddUntriggeredConditionalOrders(
	ctx sdk.Context,
	placedConditionalOrderIds []types.OrderId,
	placedStatefulCancellationOrderIds map[types.OrderId]struct{},
	expiredStatefulOrderIdsSet map[types.OrderId]struct{},
)

AddUntriggeredConditionalOrders takes in a list of newly-placed conditional order ids and adds them to the in-memory UntriggeredConditionalOrders struct, filtering out orders that have been cancelled or expired in the last block. This function is used in EndBlocker and on application startup.

func (Keeper) CalculateSubaccountPnLForMatches

func (k Keeper) CalculateSubaccountPnLForMatches(
	ctx sdk.Context,
	clobPairToPnLs map[types.ClobPairId]*CumulativePnL,
	operations []types.OperationRaw,
) (
	err error,
)

CalculateSubaccountPnLForMatches calculates the PnL for each subaccount for the given matches. TODO: Delete this function.

func (Keeper) CalculateSubaccountPnLForMevMatches

func (k Keeper) CalculateSubaccountPnLForMevMatches(
	ctx sdk.Context,
	clobPairToPnLs map[types.ClobPairId]*CumulativePnL,
	matches *types.ValidatorMevMatches,
) (
	err error,
)

CalculateSubaccountPnLForMevMatches calculates the PnL for each subaccount for the given matches. It returns an error if any of the match CLOB pairs do not exist or `AddPnLForTradeWithFilledSubticks` returns an error.

func (Keeper) CanDeleverageSubaccount

func (k Keeper) CanDeleverageSubaccount(
	ctx sdk.Context,
	subaccountId satypes.SubaccountId,
) (bool, error)

CanDeleverageSubaccount returns true if a subaccount can be deleveraged. Specifically, this function returns true if both of the following are true: - The insurance fund balance is less-than-or-equal to `MaxInsuranceFundQuantumsForDeleveraging`. - The subaccount's total net collateral is negative. This function returns an error if `GetNetCollateralAndMarginRequirements` returns an error.

func (Keeper) CancelShortTermOrder

func (k Keeper) CancelShortTermOrder(
	ctx sdk.Context,
	msgCancelOrder *types.MsgCancelOrder,
) error

CancelShortTermOrder removes a Short-Term order by `OrderId` (if it exists) from all order-related data structures in the memclob. As well, CancelShortTermOrder adds (or updates) a cancel to the desired `goodTilBlock` in the memclob. If a cancel already exists for this order with a lower `goodTilBlock`, the cancel is updated to the new `goodTilBlock`. This method is meant to be used in the CheckTx flow. It uses the next block height.

An error will be returned if any of the following conditions are true: - The cancel's `GoodTilblock` is less than or equal to the next block height. - The cancel's `GoodTilblock` is greater than the sum of the next block height and `ShortBlockWindow`. - The memclob itself returns an error.

This method assumes the provided MsgCancelOrder has already passed ValidateBasic in CheckTx.

func (Keeper) CancelStatefulOrder

func (k Keeper) CancelStatefulOrder(
	ctx sdk.Context,
	msg *types.MsgCancelOrder,
) error

CancelStatefulOrder performs stateful order cancellation validation and removes the stateful order from state and the memstore.

The following conditions must be true otherwise an error will be returned:

  • Stateful Order Cancellation cancels an existing stateful order.
  • Stateful Order Cancellation GTBT is greater than or equal to than stateful order GTBT.
  • Stateful Order Cancellation GTBT is greater than the block time of previous block.
  • Stateful Order Cancellation GTBT is less than or equal to `StatefulOrderTimeWindow` away from block time of previous block.

Note that this method conditionally updates state depending on the context. This is needed to separate updating committed state during DeliverTx (the stateful order and the ToBeCommitted stateful order count) from uncommitted state that is modified during CheckTx.

func (Keeper) ConvertFillablePriceToSubticks

func (k Keeper) ConvertFillablePriceToSubticks(
	ctx sdk.Context,
	fillablePrice *big.Rat,
	isLiquidatingLong bool,
	clobPair types.ClobPair,
) (
	subticks types.Subticks,
)

ConvertFillablePriceToSubticks converts the fillable price of a liquidation order to subticks. The returned subticks will be rounded to the nearest tick (such that `subticks % clobPair.SubticksPerTick == 0`). This function will round up for sells that close longs, and round down for buys that close shorts.

Note the returned `subticks` will be bounded (inclusive) between `clobPair.SubticksPerTick` and `math.MaxUint64 - math.MaxUint64 % clobPair.SubticksPerTick` (the maximum `uint64` that is a multiple of `clobPair.SubticksPerTick`).

func (Keeper) CountUntriggeredSubaccountOrders

func (k Keeper) CountUntriggeredSubaccountOrders(ctx sdk.Context,
	subaccountId satypes.SubaccountId,
	filter func(types.OrderId) bool,
) uint32

CountUntriggeredSubaccountOrders will count all untriggered orders for a given subaccount that match the provided filter.

func (Keeper) CreatePerpetualClobPair

func (k Keeper) CreatePerpetualClobPair(
	ctx sdk.Context,
	clobPairId uint32,
	perpetualId uint32,
	stepSizeBaseQuantums satypes.BaseQuantums,
	quantumConversionExponent int32,
	subticksPerTick uint32,
	status types.ClobPair_Status,
) (types.ClobPair, error)

CreatePerpetualClobPair creates a new perpetual CLOB pair in the store. Additionally, it creates an order book matching the ID of the newly created CLOB pair.

An error will occur if any of the fields fail validation (see validateClobPair for details), or if the `perpetualId` cannot be found. In the event of an error, the store will not be updated nor will a matching order book be created.

Returns the newly created CLOB pair and an error if one occurs.

func (Keeper) DeleteLongTermOrderPlacement

func (k Keeper) DeleteLongTermOrderPlacement(
	ctx sdk.Context,
	orderId types.OrderId,
)

DeleteLongTermOrderPlacement deletes a long term order and the placement information from state. This function is a no-op if no stateful order exists in state with `orderId`.

func (Keeper) FetchOrderFromOrderId

func (k Keeper) FetchOrderFromOrderId(
	ctx sdk.Context,
	orderId types.OrderId,
	shortTermOrdersMap map[types.OrderId]types.Order,
) (order types.Order, err error)

FetchOrderFromOrderId is a helper function that fetches a order from an order id. If the order id is a short term order, the map will be used to populate the order. If the order id is a long term order, it will be fetched from state. If the order Id is a conditional order, it will be fetched from triggered conditional order state.

func (Keeper) GenerateProcessProposerMatchesEvents

func (k Keeper) GenerateProcessProposerMatchesEvents(
	ctx sdk.Context,
	operations []types.InternalOperation,
) types.ProcessProposerMatchesEvents

GenerateProcessProposerMatchesEvents generates a `ProcessProposerMatchesEvents` object from an operations queue. Currently, it sets the `OrderIdsFilledInLastBlock` field and the `BlockHeight` field. This function expects the proposed operations to be valid, and does not verify that the `GoodTilBlockTime` of order replacement and cancellation is greater than the `GoodTilBlockTime` of the existing order.

func (Keeper) GetAllClobPairs

func (k Keeper) GetAllClobPairs(ctx sdk.Context) (list []types.ClobPair)

GetAllClobPairs returns all clobPair, sorted by ClobPair id.

func (Keeper) GetAllOrderFillStates

func (k Keeper) GetAllOrderFillStates(ctx sdk.Context) (fillStates []OrderIdFillState)

GetAllOrderFillStates iterates over the keeper store, and returns a slice of all fill amounts known to the keeper. This method is called during application startup as a means of hydrating the memclob with the known fill amounts in state.

func (Keeper) GetAllPlacedStatefulOrders

func (k Keeper) GetAllPlacedStatefulOrders(ctx sdk.Context) []types.Order

GetAllPlacedStatefulOrders iterates over all stateful order placements and returns a list of orders, ordered by ascending time priority. Note that this only returns placed orders, and therefore will not return untriggered conditional orders.

func (Keeper) GetAllUntriggeredConditionalOrders

func (k Keeper) GetAllUntriggeredConditionalOrders(ctx sdk.Context) []types.Order

GetAllUntriggeredConditionalOrders iterates over all untriggered conditional order placements and returns a list of untriggered conditional orders, ordered by ascending time priority.

func (Keeper) GetBankruptcyPriceInQuoteQuantums

func (k Keeper) GetBankruptcyPriceInQuoteQuantums(
	ctx sdk.Context,
	subaccountId satypes.SubaccountId,
	perpetualId uint32,
	deltaQuantums *big.Int,
) (
	deltaQuoteQuantums *big.Int,
	err error,
)

Returns the bankruptcy-price of a subaccount’s position delta in quote quantums. Note that the result `deltaQuoteQuantums` is signed and always rounded towards positive infinity so that closing the position at the rounded bankruptcy price does not require any insurance fund payment.

Also note that this function does not check whether the given subaccount is liquidatable, but validates that the provided deltaQuantums is valid with respect to the current position size.

func (Keeper) GetBlockRateLimitConfiguration

func (k Keeper) GetBlockRateLimitConfiguration(
	ctx sdk.Context,
) (config types.BlockRateLimitConfiguration)

GetBlockRateLimitConfiguration gets the block rate limit configuration from state.

func (Keeper) GetClobMetadata

func (k Keeper) GetClobMetadata(
	ctx sdk.Context,
) (
	clobMidPrices map[types.ClobPairId]types.Subticks,
	clobPairs map[types.ClobPairId]types.ClobPair,
)

GetClobMetadata fetches the mid prices for all CLOB pairs and the CLOB pairs themselves. This function falls back to use the oracle price if any of the mid prices are missing.

func (Keeper) GetClobPair

func (k Keeper) GetClobPair(
	ctx sdk.Context,
	id types.ClobPairId,

) (val types.ClobPair, found bool)

GetClobPair returns a clobPair from its index

func (Keeper) GetClobPairIdForPerpetual

func (k Keeper) GetClobPairIdForPerpetual(
	ctx sdk.Context,
	perpetualId uint32,
) (
	clobPairId types.ClobPairId,
	err error,
)

GetClobPairIdForPerpetual gets the first CLOB pair ID associated with the provided perpetual ID. It returns an error if there are no CLOB pair IDs associated with the perpetual ID.

func (Keeper) GetEquityTierLimitConfiguration

func (k Keeper) GetEquityTierLimitConfiguration(
	ctx sdk.Context,
) (config types.EquityTierLimitConfiguration)

GetEquityTierLimitConfiguration gets the equity tier limit configuration from state. The configuration is guaranteed to have been initialized ensuring specific field orderings.

func (Keeper) GetFillablePrice

func (k Keeper) GetFillablePrice(
	ctx sdk.Context,
	subaccountId satypes.SubaccountId,
	perpetualId uint32,
	deltaQuantums *big.Int,
) (
	fillablePrice *big.Rat,
	err error,
)

GetFillablePrice returns the fillable-price of a subaccount’s position. It returns a rational number to avoid rounding errors.

func (Keeper) GetIndexerEventManager

func (k Keeper) GetIndexerEventManager() indexer_manager.IndexerEventManager

func (Keeper) GetInsuranceFundBalance

func (k Keeper) GetInsuranceFundBalance(
	ctx sdk.Context,
) (
	balance *big.Int,
)

GetInsuranceFundBalance returns the current balance of the insurance fund (in quote quantums). This calls the Bank Keeper’s GetBalance() function for the Module Address of the insurance fund.

func (Keeper) GetLiquidationInsuranceFundDelta

func (k Keeper) GetLiquidationInsuranceFundDelta(
	ctx sdk.Context,
	subaccountId satypes.SubaccountId,
	perpetualId uint32,
	isBuy bool,
	fillAmount uint64,
	subticks types.Subticks,
) (
	insuranceFundDeltaQuoteQuantums *big.Int,
	err error,
)

GetLiquidationInsuranceFundDelta returns the net payment value between the liquidated account and the insurance fund. Positive if the liquidated account pays fees to the insurance fund. Negative if the insurance fund covers losses from the subaccount.

func (Keeper) GetLiquidationsConfig

func (k Keeper) GetLiquidationsConfig(
	ctx sdk.Context,
) (config types.LiquidationsConfig)

GetLiquidationsConfig gets the liquidations config from state.

func (Keeper) GetLongTermOrderPlacement

func (k Keeper) GetLongTermOrderPlacement(
	ctx sdk.Context,
	orderId types.OrderId,
) (val types.LongTermOrderPlacement, found bool)

GetLongTermOrderPlacement gets a long term order and the placement information from state. OrderId can be conditional or long term. Returns false if no stateful order exists in state with `orderId`.

func (Keeper) GetLongTermOrderPlacementMemStore

func (k Keeper) GetLongTermOrderPlacementMemStore(ctx sdk.Context) prefix.Store

GetLongTermOrderPlacementMemStore fetches a state store used for creating, reading, updating, and deleting a stateful order placement from state.

func (Keeper) GetLongTermOrderPlacementStore

func (k Keeper) GetLongTermOrderPlacementStore(ctx sdk.Context) prefix.Store

GetLongTermOrderPlacementStore fetches a state store used for creating, reading, updating, and deleting a stateful order placement from state.

func (Keeper) GetMEVDataFromOperations

func (k Keeper) GetMEVDataFromOperations(
	ctx sdk.Context,
	operations []types.OperationRaw,
	clobPairs map[types.ClobPairId]types.ClobPair,
) (
	validatorMevMatches *types.ValidatorMevMatches,
	err error,
)

GetMEVDataFromOperations returns the MEV matches and MEV liquidations from the provided operations queue. It returns an error if a short-term order cannot be decoded. Panics if an order cannot be found.

func (Keeper) GetMaxAndMinPositionNotionalLiquidatable

func (k Keeper) GetMaxAndMinPositionNotionalLiquidatable(
	ctx sdk.Context,
	positionToLiquidate *satypes.PerpetualPosition,
) (
	bigMinPosNotionalLiquidatable *big.Int,
	bigMaxPosNotionalLiquidatable *big.Int,
	err error,
)

GetMaxAndMinPositionNotionalLiquidatable returns the maximum and minimum notional that can be liquidated without exceeding the position block limits. The minimum amount to liquidate is specified by the liquidation config and is overridden by the maximum size of the position. The maximum amount of quantums is calculated using max_position_portion_liquidated_ppm of the liquidation config, overridden by the minimum notional liquidatable.

func (Keeper) GetNextStatefulOrderTransactionIndex

func (k Keeper) GetNextStatefulOrderTransactionIndex(ctx sdk.Context) (
	nextStatefulOrderTransactionIndex uint32,
)

GetNextStatefulOrderTransactionIndex returns the next stateful order block transaction index to be used, defeaulting to zero if not set. It then increments the transaction index by one.

func (Keeper) GetOperations

func (k Keeper) GetOperations(ctx sdk.Context) *types.MsgProposedOperations

func (Keeper) GetOraclePriceSubticksRat

func (k Keeper) GetOraclePriceSubticksRat(ctx sdk.Context, clobPair types.ClobPair) *big.Rat

GetOraclePriceSubticksRat returns the oracle price in subticks for the given `ClobPair`.

func (Keeper) GetOrderFillAmount

func (k Keeper) GetOrderFillAmount(
	ctx sdk.Context,
	orderId types.OrderId,
) (
	exists bool,
	fillAmount satypes.BaseQuantums,
	prunableBlockHeight uint32,
)

GetOrderFillAmount returns the total `fillAmount` and `prunableBlockHeight` from the memStore.

func (Keeper) GetOrdersFilledDuringLatestBlock

func (k Keeper) GetOrdersFilledDuringLatestBlock(ctx sdk.Context) []types.OrderId

GetOrdersFilledDuringLatestBlock returns a list of `OrderIds` filled during the latest block. If no orders were filled during the last block, returns an empty slice.

func (Keeper) GetPerpetualPositionToLiquidate

func (k Keeper) GetPerpetualPositionToLiquidate(
	ctx sdk.Context,
	subaccountId satypes.SubaccountId,
) (
	perpetualId uint32,
	quantums *big.Int,
	err error,
)

GetPerpetualPositionToLiquidate determines which position and position size to liquidate on the passed-in subaccount (after accounting for the `update`). It will return the perpetual id that will be used for liquidating the perpetual position and the number of quantums to liquidate from the perpetual position (positive if long, negative if short). This function returns an error if the subaccount has no perpetual positions to liquidate.

func (Keeper) GetPricePremiumForPerpetual

func (k Keeper) GetPricePremiumForPerpetual(
	ctx sdk.Context,
	perpetualId uint32,
	params perptypes.GetPricePremiumParams,
) (
	premiumPpm int32,
	err error,
)

GetPricePremiumForPerpetual returns the price premium for a perpetual market, according to the memclob state. If the market is not active, returns zero premium ppm.

func (Keeper) GetProcessProposerMatchesEvents

func (k Keeper) GetProcessProposerMatchesEvents(ctx sdk.Context) types.ProcessProposerMatchesEvents

GetProcessProposerMatchesEvents gets the process proposer matches events from the latest block.

func (Keeper) GetStatePosition

func (k Keeper) GetStatePosition(ctx sdk.Context, subaccountId satypes.SubaccountId, clobPairId types.ClobPairId,
) (
	positionSizeQuantums *big.Int,
)

GetStatePosition returns the current size of a subaccount's position for the specified `clobPairId`.

func (Keeper) GetStatefulOrdersTimeSlice

func (k Keeper) GetStatefulOrdersTimeSlice(ctx sdk.Context, goodTilBlockTime time.Time) (
	orderIds []types.OrderId,
)

GetStatefulOrdersTimeSlice gets a slice of stateful order IDs that expire at `goodTilBlockTime`, sorted by order ID.

func (Keeper) GetSubaccountLiquidationInfo

func (k Keeper) GetSubaccountLiquidationInfo(
	ctx sdk.Context,
	subaccountId satypes.SubaccountId,
) (
	liquidationInfo types.SubaccountLiquidationInfo,
)

GetSubaccountLiquidationInfo returns liquidation information of the given subaccount in the current block. If it hasn't been liquidated in the last block, it returns the default `SubaccountLiquidationInfo`.

func (Keeper) GetSubaccountMaxInsuranceLost

func (k Keeper) GetSubaccountMaxInsuranceLost(
	ctx sdk.Context,
	subaccountId satypes.SubaccountId,
	perpetualId uint32,
) (
	bigMaxQuantumsInsuranceLost *big.Int,
	err error,
)

GetSubaccountMaxInsuranceLost returns the maximum insurance fund payout that can be performed in this block without exceeding the subaccount block limits. This function takes into account any previous liquidations in the same block and returns an error if called with a previously liquidated perpetual id.

func (Keeper) GetSubaccountMaxNotionalLiquidatable

func (k Keeper) GetSubaccountMaxNotionalLiquidatable(
	ctx sdk.Context,
	subaccountId satypes.SubaccountId,
	perpetualId uint32,
) (
	bigMaxNotionalLiquidatable *big.Int,
	err error,
)

GetSubaccountMaxNotionalLiquidatable returns the maximum notional that the subaccount can liquidate without exceeding the subaccount block limits. This function takes into account any previous liquidations in the same block and returns an error if called with a previously liquidated perpetual id.

func (Keeper) GetToBeCommittedStatefulOrderCount

func (k Keeper) GetToBeCommittedStatefulOrderCount(
	ctx sdk.Context,
	orderId types.OrderId,
) int32

GetToBeCommittedStatefulOrderCount gets a count of how many stateful orders will be added for the associated subaccount during `DeliverTx`. This is represented by the number of stateful order `placements - removals`. Note that this value can be negative (for example if the stateful order is already on the book and the cancellation is to be committed). OrderId can be conditional or long term.

func (Keeper) GetToBeCommittedStatefulOrderCountTransientStore

func (k Keeper) GetToBeCommittedStatefulOrderCountTransientStore(ctx sdk.Context) prefix.Store

GetToBeCommittedStatefulOrderCountTransientStore fetches a state store used for creating, reading, updating, and deleting a stateful order count from transient state. This represents the number of to be committed `order placements - order removals` during `DeliverTx`.

func (Keeper) GetTriggeredConditionalOrderPlacement

func (k Keeper) GetTriggeredConditionalOrderPlacement(
	ctx sdk.Context,
	orderId types.OrderId,
) (val types.LongTermOrderPlacement, found bool)

GetTriggeredConditionalOrderPlacement gets an triggered conditional order placement from the memstore. Returns false if no triggered conditional order exists in memstore with `orderId`.

func (Keeper) GetTriggeredConditionalOrderPlacementMemStore

func (k Keeper) GetTriggeredConditionalOrderPlacementMemStore(ctx sdk.Context) prefix.Store

GetTriggeredConditionalOrderPlacementMemStore fetches a state store used for creating, reading, updating, and deleting a stateful order placement from state.

func (Keeper) GetTriggeredConditionalOrderPlacementStore

func (k Keeper) GetTriggeredConditionalOrderPlacementStore(ctx sdk.Context) prefix.Store

GetTriggeredConditionalOrderPlacementStore fetches a state store used for creating, reading, updating, and deleting a stateful order placement from state.

func (Keeper) GetUncommittedStatefulOrderCancellation

func (k Keeper) GetUncommittedStatefulOrderCancellation(
	ctx sdk.Context,
	orderId types.OrderId,
) (val types.MsgCancelOrder, found bool)

GetUncommittedStatefulOrderCancellation gets a stateful order cancellation from uncommitted state. OrderId can be conditional or long term. Returns false if no stateful order cancellation exists in uncommitted state with `orderId`.

func (Keeper) GetUncommittedStatefulOrderCancellationTransientStore

func (k Keeper) GetUncommittedStatefulOrderCancellationTransientStore(ctx sdk.Context) prefix.Store

GetUncommittedStatefulOrderCancellationTransientStore fetches a state store used for creating, reading, updating, and deleting a stateful order cancellation from transient state.

func (Keeper) GetUncommittedStatefulOrderCount

func (k Keeper) GetUncommittedStatefulOrderCount(
	ctx sdk.Context,
	orderId types.OrderId,
) int32

GetUncommittedStatefulOrderCount gets a count of uncommitted stateful orders for the associated subaccount. This is represented by the number of stateful order `placements - cancellations` that this validator is aware of during `CheckTx`. Note that this value can be negative (for example if the stateful order is already on the book and the cancellation is uncommitted). OrderId can be conditional or long term.

func (Keeper) GetUncommittedStatefulOrderCountTransientStore

func (k Keeper) GetUncommittedStatefulOrderCountTransientStore(ctx sdk.Context) prefix.Store

GetUncommittedStatefulOrderCountTransientStore fetches a state store used for creating, reading, updating, and deleting a stateful order count from transient state. This represents the number of uncommitted `order placements - order cancellations` during `CheckTx`.

func (Keeper) GetUncommittedStatefulOrderPlacement

func (k Keeper) GetUncommittedStatefulOrderPlacement(
	ctx sdk.Context,
	orderId types.OrderId,
) (val types.LongTermOrderPlacement, found bool)

GetUncommittedStatefulOrderPlacement gets a stateful order and the placement information from uncommitted state. OrderId can be conditional or long term. Returns false if no stateful order exists in uncommitted state with `orderId`.

func (Keeper) GetUncommittedStatefulOrderPlacementTransientStore

func (k Keeper) GetUncommittedStatefulOrderPlacementTransientStore(ctx sdk.Context) prefix.Store

GetUncommittedStatefulOrderPlacementTransientStore fetches a state store used for creating, reading, updating, and deleting a stateful order placement from transient state.

func (Keeper) GetUntriggeredConditionalOrderPlacement

func (k Keeper) GetUntriggeredConditionalOrderPlacement(
	ctx sdk.Context,
	orderId types.OrderId,
) (val types.LongTermOrderPlacement, found bool)

GetUntriggeredConditionalOrderPlacement gets an untriggered conditional order placement from the memstore. Returns false if no untriggered conditional order exists in memstore with `orderId`.

func (Keeper) GetUntriggeredConditionalOrderPlacementMemStore

func (k Keeper) GetUntriggeredConditionalOrderPlacementMemStore(ctx sdk.Context) prefix.Store

GetUntriggeredConditionalOrderPlacementMemStore fetches a state store used for creating, reading, updating, and deleting a stateful order placement from state.

func (Keeper) GetUntriggeredConditionalOrderPlacementStore

func (k Keeper) GetUntriggeredConditionalOrderPlacementStore(ctx sdk.Context) prefix.Store

GetUntriggeredConditionalOrderPlacementStore fetches a state store used for creating, reading, updating, and deleting untriggered conditional order placement from state.

func (Keeper) HasAuthority

func (k Keeper) HasAuthority(authority string) bool

func (Keeper) HydrateClobPairAndPerpetualMapping added in v0.3.0

func (k Keeper) HydrateClobPairAndPerpetualMapping(ctx sdk.Context)

HydrateClobPairAndPerpetualMapping hydrates the in-memory mapping between clob pair and perpetual.

func (Keeper) HydrateUntriggeredConditionalOrders

func (k Keeper) HydrateUntriggeredConditionalOrders(
	ctx sdk.Context,
)

HydrateUntriggeredConditionalOrders inserts all untriggered conditional orders in state into the `UntriggeredConditionalOrders` data structure. Note that all untriggered conditional orders will be ordered by time priority. This function should only be called on application startup.

func (Keeper) InitMemClobOrderbooks

func (k Keeper) InitMemClobOrderbooks(ctx sdk.Context)

InitMemClobOrderbooks initializes the memclob with `ClobPair`s from state. This is called during app initialization in `app.go`, before any ABCI calls are received.

func (Keeper) InitMemStore

func (k Keeper) InitMemStore(ctx sdk.Context)

InitMemStore initializes the memstore of the `clob` keeper. This is called during app initialization in `app.go`, before any ABCI calls are received.

func (Keeper) InitStatefulOrdersInMemClob

func (k Keeper) InitStatefulOrdersInMemClob(
	ctx sdk.Context,
)

InitStatefulOrdersInMemClob places all stateful orders in state on the memclob, placed in ascending order by time priority. This is called during app initialization in `app.go`, before any ABCI calls are received and after all MemClob orderbooks are instantiated.

func (*Keeper) InitalizeBlockRateLimitFromStateIfExists

func (k *Keeper) InitalizeBlockRateLimitFromStateIfExists(ctx sdk.Context)

InitalizeBlockRateLimitFromStateIfExists initializes the `placeOrderRateLimiter` and `cancelOrderRateLimiter` from state. Should be invoked during application start and before CLOB genesis.

func (*Keeper) InitializeBlockRateLimit

func (k *Keeper) InitializeBlockRateLimit(
	ctx sdk.Context,
	config types.BlockRateLimitConfiguration,
) error

InitializeBlockRateLimit initializes the block rate limit configuration in state and uses the configuration to initialize the `placeOrderRateLimiter` and `cancelOrderRateLimiter`. This function should only be called from CLOB genesis or when a block rate limit configuration change is accepted via governance.

Note that any previously tracked rates will be reset.

func (Keeper) InitializeCumulativePnLs

func (k Keeper) InitializeCumulativePnLs(
	ctx sdk.Context,
	perpetualKeeper process.ProcessPerpetualKeeper,
	clobMidPrices map[types.ClobPairId]types.Subticks,
	clobPairs map[types.ClobPairId]types.ClobPair,
) (
	blockProposerPnL map[types.ClobPairId]*CumulativePnL,
	validatorPnL map[types.ClobPairId]*CumulativePnL,
)

InitializeCumulativePnLs initializes the cumulative PnLs for the block proposer and the current validator.

func (Keeper) InitializeCumulativePnLsFromRequest

func (k Keeper) InitializeCumulativePnLsFromRequest(
	ctx sdk.Context,
	req *types.MevNodeToNodeCalculationRequest,
) (
	blockProposerPnL map[types.ClobPairId]*CumulativePnL,
	validatorPnL map[types.ClobPairId]*CumulativePnL,
)

func (*Keeper) InitializeEquityTierLimit

func (k *Keeper) InitializeEquityTierLimit(
	ctx sdk.Context,
	config types.EquityTierLimitConfiguration,
) error

InitializeEquityTierLimit initializes the equity tier limit configuration in state. This function should only be called from CLOB genesis or when an equity tier limit configuration change is accepted via governance.

func (Keeper) InitializeForGenesis

func (k Keeper) InitializeForGenesis(ctx sdk.Context)

func (Keeper) InitializeLiquidationsConfig

func (k Keeper) InitializeLiquidationsConfig(
	ctx sdk.Context,
	config types.LiquidationsConfig,
) error

InitializeLiquidationsConfig initializes the liquidations config in state. This function should only be called from the CLOB genesis.

func (Keeper) InitializeProcessProposerMatchesEvents

func (k Keeper) InitializeProcessProposerMatchesEvents(
	ctx sdk.Context,
)

InitializeProcessProposerMatchesEvents initializes the process proposer matches events. This function should only be called from the CLOB genesis.

func (Keeper) IsConditionalOrderTriggered

func (k Keeper) IsConditionalOrderTriggered(
	ctx sdk.Context,
	orderId types.OrderId,
) (triggered bool)

IsConditionalOrderTriggered checks if a given order ID is triggered or untriggered in state. Note: If the given order ID is neither in triggered or untriggered state, function will return false.

func (Keeper) IsLiquidatable

func (k Keeper) IsLiquidatable(
	ctx sdk.Context,
	subaccountId satypes.SubaccountId,
) (
	bool,
	error,
)

IsLiquidatable returns true if the subaccount is able to be liquidated; that is, if-and-only-if the maintenance margin requirement is non-zero and greater than the net collateral of the subaccount. If `GetNetCollateralAndMarginRequirements` returns an error, this function will return that error to the caller.

func (Keeper) IsPerpetualClobPairActive

func (k Keeper) IsPerpetualClobPairActive(
	ctx sdk.Context,
	perpetualId uint32,
) (bool, error)

IsPerpetualClobPairActive returns true if the ClobPair associated with the provided perpetual id has the active status. Returns an error if the ClobPair cannot be found.

func (Keeper) IsValidInsuranceFundDelta

func (k Keeper) IsValidInsuranceFundDelta(
	ctx sdk.Context,
	insuranceFundDelta *big.Int,
) bool

IsValidInsuranceFundDelta returns true if the insurance fund has enough funds to cover the insurance fund delta. Specifically, this function returns true if either of the following are true: - The `insuranceFundDelta` is non-negative. - The insurance fund balance + `insuranceFundDelta` is greater-than-or-equal-to 0.

func (Keeper) LiquidateSubaccountsAgainstOrderbook added in v0.3.0

func (k Keeper) LiquidateSubaccountsAgainstOrderbook(
	ctx sdk.Context,
	subaccountIds []satypes.SubaccountId,
) error

LiquidateSubaccountsAgainstOrderbook takes a list of subaccount IDs and liquidates them against the orderbook. It will liquidate as many subaccounts as possible up to the maximum number of liquidations per block.

func (Keeper) Logger

func (k Keeper) Logger(ctx sdk.Context) log.Logger

func (Keeper) MaybeDeleverageSubaccount added in v0.3.0

func (k Keeper) MaybeDeleverageSubaccount(
	ctx sdk.Context,
	subaccountId satypes.SubaccountId,
	perpetualId uint32,
	deltaQuantums *big.Int,
) (
	quantumsDeleveraged *big.Int,
	err error,
)

MaybeDeleverageSubaccount is the main entry point to deleverage a subaccount. It attempts to find positions on the opposite side of deltaQuantums and use them to offset the liquidated subaccount's position at the bankruptcy price of the liquidated position.

func (Keeper) MaybeGetLiquidationOrder

func (k Keeper) MaybeGetLiquidationOrder(
	ctx sdk.Context,
	subaccountId satypes.SubaccountId,
) (
	liquidationOrder *types.LiquidationOrder,
	err error,
)

MaybeGetLiquidationOrder takes a subaccount ID and returns a liquidation order that can be used to liquidate the subaccount. If the subaccount is not currently liquidatable, it will do nothing. This function will return an error if calling `IsLiquidatable`, `GetPerpetualPositionToLiquidate` or `GetFillablePrice` returns an error.

func (Keeper) MaybeTriggerConditionalOrders

func (k Keeper) MaybeTriggerConditionalOrders(ctx sdk.Context) (triggeredConditionalOrderIds []types.OrderId)

MaybeTriggerConditionalOrders queries the prices module for price updates and triggers any conditional orders in `UntriggeredConditionalOrders` that can be triggered. For each triggered order, it takes the stateful order placement stored in Untriggered state and moves it to Triggered state. A conditional order trigger event is emitted for each triggered order. Function returns a sorted list of conditional order ids that were triggered, intended to be written to `ProcessProposerMatchesEvents.ConditionalOrderIdsTriggeredInLastBlock`. This function is called in EndBlocker.

func (Keeper) MustAddOrderToStatefulOrdersTimeSlice

func (k Keeper) MustAddOrderToStatefulOrdersTimeSlice(
	ctx sdk.Context,
	goodTilBlockTime time.Time,
	orderId types.OrderId,
)

MustAddOrderToStatefulOrdersTimeSlice adds a new `OrderId` to an existing time slice, or creates a new time slice containing the `OrderId` and writes it to state. It first sorts all order IDs before writing them to state to avoid non-determinism issues.

func (Keeper) MustAddUncommittedStatefulOrderCancellation

func (k Keeper) MustAddUncommittedStatefulOrderCancellation(ctx sdk.Context, msg *types.MsgCancelOrder)

MustAddUncommittedStatefulOrderCancellation adds a new order cancellation by `OrderId` to a transient store and decrements the per subaccount uncommitted stateful order count.

This method will panic if the order cancellation already exists or if the order count underflows a uint32.

func (Keeper) MustAddUncommittedStatefulOrderPlacement

func (k Keeper) MustAddUncommittedStatefulOrderPlacement(ctx sdk.Context, msg *types.MsgPlaceOrder)

MustAddUncommittedStatefulOrderPlacement adds a new order placemenet by `OrderId` to a transient store and increments the per subaccount uncommitted stateful order count.

This method will panic if the order already exists.

func (Keeper) MustFetchOrderFromOrderId

func (k Keeper) MustFetchOrderFromOrderId(
	ctx sdk.Context,
	orderId types.OrderId,
	ordersMap map[types.OrderId]types.Order,
) types.Order

MustFetchOrderFromOrderId fetches an Order object given an orderId. If it is a short term order, `ordersMap` will be used to populate the order. If it is a stateful order, read from state. Note that this function is meant to be used for operation processing during DeliverTx and does not fetch untriggered conditional orders.

Function will panic if for any reason, the order cannot be searched up.

func (Keeper) MustRemoveStatefulOrder

func (k Keeper) MustRemoveStatefulOrder(
	ctx sdk.Context,
	orderId types.OrderId,
)

MustRemoveStatefulOrder removes an order by `OrderId` from an existing time slice. If the time slice is empty after removing the `OrderId`, then the time slice is pruned from state. For the `OrderId` which is removed, this method also calls `DeleteStatefulOrderPlacement` to remove the order placement from state.

func (Keeper) MustSetProcessProposerMatchesEvents

func (k Keeper) MustSetProcessProposerMatchesEvents(
	ctx sdk.Context,
	processProposerMatchesEvents types.ProcessProposerMatchesEvents,
)

MustSetProcessProposerMatchesEvents sets the process proposer matches events from the latest block. This function panics if:

  • the current block height does not match the block height of the ProcessProposerMatchesEvents
  • called outside of deliver TX mode

TODO(DEC-1281): add parameter validation.

func (Keeper) MustTriggerConditionalOrder

func (k Keeper) MustTriggerConditionalOrder(
	ctx sdk.Context,
	orderId types.OrderId,
)

MustTriggerConditionalOrder triggers an untriggered conditional order. The conditional order must already exist in untriggered state, or else this function will panic. The LongTermOrderPlacement object will be removed from the untriggered state store and placed in the triggered state store. TODO(CLOB-746) define private R/W methods for conditional orders

func (Keeper) MustUpdateSubaccountPerpetualLiquidated

func (k Keeper) MustUpdateSubaccountPerpetualLiquidated(
	ctx sdk.Context,
	subaccountId satypes.SubaccountId,
	perpetualId uint32,
)

MustUpdateSubaccountPerpetualLiquidated adds a perpetual id to the subaccount liquidation info for the current block.

func (Keeper) MustValidateReduceOnlyOrder

func (k Keeper) MustValidateReduceOnlyOrder(
	ctx sdk.Context,
	order types.MatchableOrder,
	matchedAmount uint64,
) error

MustValidateReduceOnlyOrder makes sure the given reduce-only order is valid with respect to the current position size. Specifically, this function validates:

  • The reduce-only order is on the opposite side of the existing position.
  • The reduce-only order does not change the subaccount's position side.

func (Keeper) NewUntriggeredConditionalOrders

func (k Keeper) NewUntriggeredConditionalOrders() *UntriggeredConditionalOrders

func (Keeper) OffsetSubaccountPerpetualPosition

func (k Keeper) OffsetSubaccountPerpetualPosition(
	ctx sdk.Context,
	liquidatedSubaccountId satypes.SubaccountId,
	perpetualId uint32,
	deltaQuantumsTotal *big.Int,
) (
	fills []types.MatchPerpetualDeleveraging_Fill,
	deltaQuantumsRemaining *big.Int,
)

OffsetSubaccountPerpetualPosition iterates over all subaccounts and use those with positions on the opposite side to offset the liquidated subaccount's position by `deltaQuantumsTotal`.

This function returns the fills that were processed and the remaining amount to offset. Note that each deleveraging fill is being processed _optimistically_, and the state transitions are still persisted even if there are not enough subaccounts to offset the liquidated subaccount's position.

func (Keeper) PerformOrderCancellationStatefulValidation

func (k Keeper) PerformOrderCancellationStatefulValidation(
	ctx sdk.Context,
	msgCancelOrder *types.MsgCancelOrder,
	blockHeight uint32,
) error

PerformOrderCancellationStatefulValidation performs stateful validation on an order cancellation. The order cancellation can be either stateful or short term. This validation performs state reads.

This validation ensures:

  • Stateful Order Cancellation for the order does not already exist in uncommitted state.
  • Stateful Order Cancellation cancels an uncommitted or existing stateful order.
  • Stateful Order Cancellation GTBT is greater than or equal to than stateful order GTBT.
  • Stateful Order Cancellation GTBT is greater than the block time of previous block.
  • Stateful Order Cancellation GTBT is less than or equal to `StatefulOrderTimeWindow` away from block time of previous block.
  • Short term Order Cancellation GTB must be greater than or equal to blockHeight
  • Short term Order Cancellation GTB is less than or equal to ShortBlockWindow block hight in the future.

func (Keeper) PerformStatefulOrderValidation

func (k Keeper) PerformStatefulOrderValidation(
	ctx sdk.Context,
	order *types.Order,
	blockHeight uint32,
	isPreexistingStatefulOrder bool,
) error

PerformStatefulOrderValidation performs stateful validation on an order. This validation performs state reads.

This validation ensures:

  • The `ClobPairId` on the order is for a valid CLOB.
  • The `Subticks` of the order is a multiple of the ClobPair's `SubticksPerTick`.
  • The `Quantums` of the order is a multiple of the ClobPair's `StepBaseQuantums`.

This validation also ensures that the order is valid for the ClobPair's status.

For short term orders it also ensures:

  • The `GoodTilBlock` of the order is greater than the provided `blockHeight`.
  • The `GoodTilBlock` of the order does not exceed the provided `blockHeight + ShortBlockWindow`.

For stateful orders it also ensures:

  • GTBT is greater than the block time of previous block.
  • GTBT is less than or equal to `StatefulOrderTimeWindow` away from block time of previous block.
  • That there isn't an order cancellation in uncommitted state.
  • That the order does not already exist in uncommitted state unless `isPreexistingStatefulOrder` is true.
  • That the order does not already exist in committed state unless `isPreexistingStatefulOrder` is true.

func (Keeper) PersistMatchDeleveragingToState

func (k Keeper) PersistMatchDeleveragingToState(
	ctx sdk.Context,
	matchDeleveraging *types.MatchPerpetualDeleveraging,
) error

PersistMatchDeleveragingToState writes a MatchPerpetualDeleveraging object to state. This function returns an error if: - CanDeleverageSubaccount returns false, indicating the subaccount failed deleveraging validation. - OffsetSubaccountPerpetualPosition returns an error. - The generated fills do not match the fills in the Operations object. TODO(CLOB-654) Verify deleveraging is triggered by unmatched liquidation orders and for the correct amount.

func (Keeper) PersistMatchLiquidationToState

func (k Keeper) PersistMatchLiquidationToState(
	ctx sdk.Context,
	matchLiquidation *types.MatchPerpetualLiquidation,
	ordersMap map[types.OrderId]types.Order,
) error

PersistMatchLiquidationToState writes a MatchPerpetualLiquidation event and updates the keeper transient store. It also performs stateful validation on the matchLiquidations object.

func (Keeper) PersistMatchOrdersToState

func (k Keeper) PersistMatchOrdersToState(
	ctx sdk.Context,
	matchOrders *types.MatchOrders,
	ordersMap map[types.OrderId]types.Order,
) error

PersistMatchOrdersToState writes a MatchOrders object to state and emits an onchain indexer event for the match.

func (Keeper) PersistMatchToState

func (k Keeper) PersistMatchToState(
	ctx sdk.Context,
	clobMatch *types.ClobMatch,
	ordersMap map[types.OrderId]types.Order,
) error

PersistMatchToState takes in an ClobMatch and writes the match to state. A map of orderId to Order is required to fetch the whole Order object for short term orders.

func (Keeper) PersistOrderRemovalToState added in v0.3.0

func (k Keeper) PersistOrderRemovalToState(
	ctx sdk.Context,
	orderRemoval types.OrderRemoval,
) error

PersistOrderRemovalToState takes in an OrderRemoval, statefully validates it according to RemovalReason, and writes the removal to state.

func (Keeper) PlaceConditionalOrdersTriggeredInLastBlock

func (k Keeper) PlaceConditionalOrdersTriggeredInLastBlock(
	ctx sdk.Context,
	conditionalOrderIdsTriggeredInLastBlock []types.OrderId,
	existingOffchainUpdates *types.OffchainUpdates,
) (
	offchainUpdates *types.OffchainUpdates,
)

PlaceConditionalOrdersTriggeredInLastBlock takes in a list of conditional order ids that were triggered in the last block, verifies they are conditional orders, verifies they are in triggered state, and places the orders on the memclob.

func (Keeper) PlacePerpetualLiquidation

func (k Keeper) PlacePerpetualLiquidation(
	ctx sdk.Context,
	liquidationOrder types.LiquidationOrder,
) (
	orderSizeOptimisticallyFilledFromMatchingQuantums satypes.BaseQuantums,
	orderStatus types.OrderStatus,
	err error,
)

PlacePerpetualLiquidation places an IOC liquidation order onto the book that results in fills of type `PerpetualLiquidation`.

func (Keeper) PlaceShortTermOrder

func (k Keeper) PlaceShortTermOrder(
	ctx sdk.Context,
	msg *types.MsgPlaceOrder,
) (
	orderSizeOptimisticallyFilledFromMatchingQuantums satypes.BaseQuantums,
	orderStatus types.OrderStatus,
	err error,
)

PlaceShortTermOrder places an order on the corresponding orderbook, and performs matching if placing the order causes an overlap. This function will return the result of calling `PlaceOrder` on the keeper's memclob. This method is meant to be used in the CheckTx flow. It uses the next block height.

An error will be returned if any of the following conditions are true:

  • Standard stateful validation fails.
  • The memclob itself returns an error.

This method will panic if the provided order is not a Short-Term order.

func (Keeper) PlaceStatefulOrder

func (k Keeper) PlaceStatefulOrder(
	ctx sdk.Context,
	msg *types.MsgPlaceOrder,
) error

PlaceStatefulOrder performs order validation, equity tier limit check, a collateralization check and writes the order to state and the memstore. The order will not be placed on the orderbook.

An error will be returned if any of the following conditions are true:

  • Standard stateful validation fails.
  • Equity tier limit exceeded.
  • Collateralization check fails.

Note that this method conditionally updates state depending on the context. This is needed to separate updating committed state during DeliverTx from uncommitted state that is modified during CheckTx.

This method will panic if the provided order is not a Stateful order.

func (Keeper) PlaceStatefulOrdersFromLastBlock

func (k Keeper) PlaceStatefulOrdersFromLastBlock(
	ctx sdk.Context,
	placedStatefulOrderIds []types.OrderId,
	existingOffchainUpdates *types.OffchainUpdates,
) (
	offchainUpdates *types.OffchainUpdates,
)

PlaceStatefulOrdersFromLastBlock validates and places stateful orders from the last block onto the memclob. Note that stateful orders could fail to be placed due to various reasons such as collateralization check failures, self-trade errors, etc. In these cases the `checkState` will not be written to. This function is used in: 1. `PrepareCheckState` to place newly placed long term orders from the last block from ProcessProposerMatchesEvents.PlacedStatefulOrderIds. This is step 3 in PrepareCheckState. 2. `PlaceConditionalOrdersTriggeredInLastBlock` to place conditional orders triggered in the last block from ProcessProposerMatchesEvents.ConditionalOrderIdsTriggeredInLastBlock. This is step 4 in PrepareCheckState.

func (Keeper) ProcessDeleveraging

func (k Keeper) ProcessDeleveraging(
	ctx sdk.Context,
	liquidatedSubaccountId satypes.SubaccountId,
	offsettingSubaccountId satypes.SubaccountId,
	perpetualId uint32,
	deltaQuantums *big.Int,
) (
	err error,
)

ProcessDeleveraging processes a deleveraging operation by closing both the liquidated subaccount's position and the offsetting subaccount's position at the bankruptcy price of the _liquidated_ position. This function takes a `deltaQuantums` argument, which is the delta with respect to the liquidated subaccount's position, to allow for partial deleveraging. This function emits a cometbft event if the deleveraging match is successfully written to state.

This function returns an error if: - `deltaQuantums` is not valid with respect to either of the subaccounts. - `GetBankruptcyPriceInQuoteQuantums` returns an error. - subaccount updates cannot be applied when the bankruptcy prices of both subaccounts don't overlap.

func (Keeper) ProcessInternalOperations

func (k Keeper) ProcessInternalOperations(
	ctx sdk.Context,
	operations []types.InternalOperation,
) error

Function will panic if: - any orderId referenced in clobMatch cannot be found. - any orderId referenced in order removal operations cannot be found.

func (Keeper) ProcessProposerOperations

func (k Keeper) ProcessProposerOperations(
	ctx sdk.Context,
	rawOperations []types.OperationRaw,
) error

ProcessProposerOperations updates on-chain state given an []OperationRaw operations queue representing matches that occurred in the previous block. It performs validation on an operations queue. If all validation passes, the operations queue is written to state. The following operations are written to state: - Order Matches, Liquidation Matches, Deleveraging Matches

func (Keeper) ProcessSingleMatch

func (k Keeper) ProcessSingleMatch(
	ctx sdk.Context,
	matchWithOrders *types.MatchWithOrders,
) (
	success bool,
	takerUpdateResult satypes.UpdateResult,
	makerUpdateResult satypes.UpdateResult,
	offchainUpdates *types.OffchainUpdates,
	err error,
)

ProcessSingleMatch accepts a single match and its associated orders matched in the block, persists the resulting subaccount updates and state fill amounts. This function assumes that the provided match with orders has undergone stateless validations. If additional validation of the provided orders or match fails, an error is returned. The following validation occurs in this method:

  • Order is for a valid ClobPair.
  • Order is for a valid Perpetual.
  • Validate the `fillAmount` of a match is divisible by the `ClobPair`'s `StepBaseQuantums`.
  • Validate the new total fill amount of an order does not exceed the total quantums of the order given the fill amounts present in the provided `matchOrders` and in state.
  • Validate the subaccount updates resulting from the match are valid (before persisting the updates to state)
  • For liquidation orders, stateful validations through calling `validateMatchPerpetualLiquidationAgainstSubaccountBlockLimits`.
  • Validating that deleveraging is not required for processing liquidation orders.

This method returns `takerUpdateResult` and `makerUpdateResult` which can be used to determine whether the maker and/or taker failed collateralization checks. This information is particularly pertinent for the `memclob` which calls this method during matching. TODO(DEC-1282): Remove redundant checks from `ProcessSingleMatch` for matching. This method mutates matchWithOrders by setting the fee fields.

func (Keeper) PruneOrdersForBlockHeight

func (k Keeper) PruneOrdersForBlockHeight(ctx sdk.Context, blockHeight uint32) (prunedOrderIds []types.OrderId)

PruneOrdersForBlockHeight checks all orders for prunability given the provided `blockHeight`. If an order is deemed prunable at this `blockHeight`, then it is pruned. Note: An order is only deemed prunable if the `prunableBlockHeight` on the `OrderFillState` is less than or equal to the provided `blockHeight` passed this method. Returns a slice of unique `OrderIds` which were pruned from state.

func (*Keeper) PruneRateLimits

func (k *Keeper) PruneRateLimits(ctx sdk.Context)

func (Keeper) PruneStateFillAmountsForShortTermOrders

func (k Keeper) PruneStateFillAmountsForShortTermOrders(
	ctx sdk.Context,
)

PruneStateFillAmountsForShortTermOrders prunes Short-Term order fill amounts from state that are pruneable at the block height of the most recently committed block.

func (Keeper) PruneUntriggeredConditionalOrders

func (k Keeper) PruneUntriggeredConditionalOrders(
	expiredStatefulOrderIds []types.OrderId,
	cancelledStatefulOrderIds []types.OrderId,
)

PruneUntriggeredConditionalOrders takes in lists of expired and cancelled stateful order ids and removes all respective orders from the in-memory `UntriggeredConditionalOrders` data structure. This data structure stores untriggered orders in a map of ClobPairId -> []Order, so we first group orders by ClobPairId and then call `UntriggeredConditionalOrders.RemoveExpiredUntriggeredConditionalOrders` on each ClobPairId.

func (*Keeper) RateLimitCancelOrder

func (k *Keeper) RateLimitCancelOrder(ctx sdk.Context, msg *types.MsgCancelOrder) error

RateLimitCancelOrder passes order cancellations with valid clob pairs to `cancelOrderRateLimiter`.

func (*Keeper) RateLimitPlaceOrder

func (k *Keeper) RateLimitPlaceOrder(ctx sdk.Context, msg *types.MsgPlaceOrder) error

RateLimitPlaceOrder passes orders with valid clob pairs to `placeOrderRateLimiter`.

func (Keeper) RecordMevMetrics

func (k Keeper) RecordMevMetrics(
	ctx sdk.Context,
	stakingKeeper process.ProcessStakingKeeper,
	perpetualKeeper process.ProcessPerpetualKeeper,
	msgProposedOperations *types.MsgProposedOperations,
)

RecordMevMetrics measures and records MEV by comparing the block proposer's list of matches with its own list of matches.

func (Keeper) RecordMevMetricsIsEnabled

func (k Keeper) RecordMevMetricsIsEnabled() bool

RecordMevMetricsIsEnabled returns true if the MEV telemetry config is enabled.

func (Keeper) RemoveClobPair

func (k Keeper) RemoveClobPair(
	ctx sdk.Context,
	id types.ClobPairId,

)

RemoveClobPair removes a clobPair from the store

func (Keeper) RemoveExpiredStatefulOrdersTimeSlices

func (k Keeper) RemoveExpiredStatefulOrdersTimeSlices(ctx sdk.Context, blockTime time.Time) (
	expiredOrderIds []types.OrderId,
)

RemoveExpiredStatefulOrdersTimeSlices iterates all time slices from 0 until the time specified by `blockTime` (inclusive) and removes the time slices from state. It returns all order IDs that were removed.

func (Keeper) RemoveOrderFillAmount

func (k Keeper) RemoveOrderFillAmount(ctx sdk.Context, orderId types.OrderId)

RemoveOrderFillAmount removes the fill amount of an Order from state and the memstore. This function is a no-op if no order fill amount exists in state and the mem store with `orderId`.

func (Keeper) ReplayPlaceOrder

func (k Keeper) ReplayPlaceOrder(
	ctx sdk.Context,
	msg *types.MsgPlaceOrder,
) (
	orderSizeOptimisticallyFilledFromMatchingQuantums satypes.BaseQuantums,
	orderStatus types.OrderStatus,
	offchainUpdates *types.OffchainUpdates,
	err error,
)

ReplayPlaceOrder returns the result of calling `PlaceOrder` on the memclob. This method does not forward events directly to indexer, but instead returns them in the form of `OffchainUpdates`. This method is meant to be used in the `ReplayOperations` flow, where we replay Short-Term and newly-played stateful orders back onto the memclob.

An error will be returned if any of the following conditions are true: - Standard stateful validation fails. - The memclob itself returns an error.

func (Keeper) SendOffchainMessages

func (k Keeper) SendOffchainMessages(
	offchainUpdates *types.OffchainUpdates,
	additionalHeaders []msgsender.MessageHeader,
	metric string,
)

SendOffchainMessages sends all the `Message` in the offchainUpdates passed in along with any additional headers passed in. No headers will be added if a `nil` or empty list of additional headers is passed in.

func (*Keeper) SetAnteHandler

func (k *Keeper) SetAnteHandler(anteHandler sdk.AnteHandler)

Sets the ante handler after it has been constructed. This breaks a cycle between when the ante handler is constructed and when the clob keeper is constructed.

func (Keeper) SetClobPairIdForPerpetual added in v0.3.0

func (k Keeper) SetClobPairIdForPerpetual(ctx sdk.Context, clobPair types.ClobPair)

SetClobPairIdForPerpetual sets the mapping between clob pair and perpetual.

func (Keeper) SetLongTermOrderPlacement

func (k Keeper) SetLongTermOrderPlacement(
	ctx sdk.Context,
	order types.Order,
	blockHeight uint32,
)

SetLongTermOrderPlacement sets a stateful order in state, along with information about when it was placed. The placed order can either be a conditional order or a long term order. If the order is conditional, it will be placed into the Untriggered Conditional Orders state store. If it is a long term order, it will be placed in the Long Term Order state store. If the `OrderId` doesn't exist then the `to be committed` stateful order count is incremented. Note the following: - If a stateful order placement already exists in state with `order.OrderId`, this function will overwrite it. - The `TransactionIndex` field will be set to the next unused transaction index for this block. - Triggered conditional orders should use the `TriggerConditionalOrder` write path.

func (Keeper) SetOrderFillAmount

func (k Keeper) SetOrderFillAmount(
	ctx sdk.Context,
	orderId types.OrderId,
	fillAmount satypes.BaseQuantums,
	prunableBlockHeight uint32,
)

SetOrderFillAmount writes the total `fillAmount` and `prunableBlockHeight` of an order to on-chain state. TODO(DEC-1219): Determine whether we should continue using `OrderFillState` proto for stateful orders.

func (Keeper) SetToBeCommittedStatefulOrderCount

func (k Keeper) SetToBeCommittedStatefulOrderCount(
	ctx sdk.Context,
	orderId types.OrderId,
	count int32,
)

SetToBeCommittedStatefulOrderCount sets a count of how many stateful orders will be added for the associated subaccount during `DeliverTx`. This represents the number of stateful order `placements - cancellations`. Note that this value can be negative (for example if the stateful order is already on the book and the cancellation is to be committed). OrderId can be conditional or long term.

func (Keeper) SetUncommittedStatefulOrderCount

func (k Keeper) SetUncommittedStatefulOrderCount(
	ctx sdk.Context,
	orderId types.OrderId,
	count int32,
)

SetUncommittedStatefulOrderCount sets a count of uncommitted stateful orders for the associated subaccount. This represents the number of stateful order `placements - cancellations` that this validator is aware of during `CheckTx`. Note that this value can be negative (for example if the stateful order is already on the book and the cancellation is uncommitted). OrderId can be conditional or long term.

func (Keeper) SortLiquidationOrders added in v0.3.0

func (k Keeper) SortLiquidationOrders(
	ctx sdk.Context,
	liquidationOrders []types.LiquidationOrder,
)

SortLiquidationOrders deterministically sorts the liquidation orders in place. Orders are first ordered by their absolute percentage difference from the oracle price in descending order, followed by the their size in quote quantums in descending order, and finally by order hashes.

func (Keeper) StatefulValidateMakerFill

func (k Keeper) StatefulValidateMakerFill(
	ctx sdk.Context,
	fill *types.MakerFill,
	shortTermOrdersMap map[types.OrderId]types.Order,
	takerOrder *types.Order,
) (makerOrder types.Order, err error)

StatefulValidateMakerFill performs stateful validation on a maker fill. Additionally, it returns the maker order referenced in the fill. The following validations are performed: - Validation on any short term orders - Validation that maker order cannot be FOK or IOC - Taker and Maker must be on opposite sides

func (Keeper) UpdateClobPair

func (k Keeper) UpdateClobPair(
	ctx sdk.Context,
	clobPair types.ClobPair,
) error

UpdateClobPair overwrites a ClobPair in state and sends an update to the indexer. This function returns an error if the update includes an unsupported transition for the ClobPair's status.

func (Keeper) UpdateLiquidationsConfig

func (k Keeper) UpdateLiquidationsConfig(
	ctx sdk.Context,
	config types.LiquidationsConfig,
) error

UpdateLiquidationsConfig updates the liquidations config in state.

func (Keeper) UpdateSubaccountLiquidationInfo

func (k Keeper) UpdateSubaccountLiquidationInfo(
	ctx sdk.Context,
	subaccountId satypes.SubaccountId,
	notionalLiquidatedQuoteQuantums *big.Int,
	insuranceFundDeltaQuoteQuantums *big.Int,
)

UpdateSubaccountLiquidationInfo updates the total notional liquidated and total insurance lost of the given subaccount for the current block.

func (Keeper) ValidateLiquidationOrderAgainstProposedLiquidation

func (k Keeper) ValidateLiquidationOrderAgainstProposedLiquidation(
	ctx sdk.Context,
	order *types.LiquidationOrder,
	proposedMatch *types.MatchPerpetualLiquidation,
) error

ValidateLiquidationOrderAgainstProposedLiquidation performs stateless validation of a liquidation order against a proposed liquidation. An error is returned when

  • The CLOB pair IDs of the order and proposed liquidation do not match.
  • The perpetual IDs of the order and proposed liquidation do not match.
  • The total size of the order and proposed liquidation do not match.
  • The side of the order and proposed liquidation do not match.

func (Keeper) ValidateSubaccountEquityTierLimitForNewOrder

func (k Keeper) ValidateSubaccountEquityTierLimitForNewOrder(ctx sdk.Context, order types.Order) error

ValidateSubaccountEquityTierLimitForNewOrder returns an error if adding the order would exceed the equity tier limit on how many open orders a subaccount can have. Short-term fill-or-kill and immediate-or-cancel orders never rest on the book and will always be allowed as they do not apply to the number of open orders that equity tier limits enforce.

Note that the method is dependent on whether we are executing on `checkState` or on `deliverState` for stateful orders. During `checkState` we rely on the uncommitted order count to tell us how many stateful orders exist outside of the MemClob. For `deliverState` we use the `ProcessProposerMatchesEvents` to find out how many orders (minus removals) exists outside of the `MemClob`.

type MevTelemetryConfig

type MevTelemetryConfig struct {
	Enabled    bool
	Host       string
	Identifier string
}

type OrderIdFillState

type OrderIdFillState struct {
	types.OrderFillState
	OrderId types.OrderId
}

OrderIdFillState is a struct that represents an order fill amount in state.

type PnLCalculationParams

type PnLCalculationParams struct {
	// contains filtered or unexported fields
}

type UntriggeredConditionalOrders

type UntriggeredConditionalOrders struct {
	// All untriggered take profit buy orders and stop loss sell orders sorted by time priority.
	// These orders will be triggered when the oracle price goes lower than or equal to the trigger price.
	// This array functions like a max heap.
	OrdersToTriggerWhenOraclePriceLTETriggerPrice []types.Order

	// All untriggered take profit sell orders and stop loss buy orders sorted by time priority.
	// These orders will be triggered when the oracle price goes greater than or equal to the trigger price.
	// This array functions like a min heap.
	OrdersToTriggerWhenOraclePriceGTETriggerPrice []types.Order
}

UntriggeredConditionalOrders is an in-memory struct stored on the clob Keeper. It is intended to efficiently store placed conditional orders and poll out triggered conditional orders on oracle price changes for a given ClobPairId. All orders contained in this data structure are placed conditional orders with the same ClobPairId and are untriggered, unexpired, and uncancelled. Note that we are using a Order list for the initial implementation, but for optimal runtime a an AVL-tree backed priority queue would work. TODO(CLOB-717) Change list to use priority queue.

func NewUntriggeredConditionalOrders

func NewUntriggeredConditionalOrders() *UntriggeredConditionalOrders

func (*UntriggeredConditionalOrders) AddUntriggeredConditionalOrder

func (untriggeredOrders *UntriggeredConditionalOrders) AddUntriggeredConditionalOrder(order types.Order)

AddUntriggeredConditionalOrder adds an untriggered conditional order to the UntriggeredConditionalOrders data structure. It will panic if the order is not a conditional order.

func (*UntriggeredConditionalOrders) IsEmpty

func (untriggeredOrders *UntriggeredConditionalOrders) IsEmpty() bool

IsEmpty returns true if the UntriggeredConditionalOrders' order slices are both empty.

func (*UntriggeredConditionalOrders) PollTriggeredConditionalOrders

func (untriggeredOrders *UntriggeredConditionalOrders) PollTriggeredConditionalOrders(
	oraclePriceSubticksRat *big.Rat,
) []types.OrderId

PollTriggeredConditionalOrders removes all triggered conditional orders from the `UntriggeredConditionalOrders` struct given a new oracle price for a clobPairId. It returns a list of order ids that were triggered. This is only called in EndBlocker. We round up to the nearest subtick int for LTE and down to the nearest subtick int for GTE conditions. This is pessimistic rounding, as we want to trigger orders only when we are sure they are triggerable.

func (*UntriggeredConditionalOrders) RemoveUntriggeredConditionalOrders

func (untriggeredOrders *UntriggeredConditionalOrders) RemoveUntriggeredConditionalOrders(
	orderIdsToRemove []types.OrderId,
)

RemoveUntriggeredConditionalOrders removes a list of order ids from the `UntriggeredConditionalOrders` data structure. This function will panic if the order ids contained involve more than one ClobPairId.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL