keeper

package
v0.0.0-...-41d3419 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2025 License: AGPL-3.0, AGPL-3.0-or-later Imports: 32 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddYieldToSubaccount

func AddYieldToSubaccount(
	subaccount types.Subaccount,
	perpIdToPerp map[uint32]perptypes.Perpetual,
	assetYieldIndex *big.Rat,
	availableYieldInQuantums *big.Int,
) (
	settledSubaccount types.Subaccount,
	totalNewYieldInQuantums *big.Int,
	err error,
)

func GetCollateralPoolStateTransition

func GetCollateralPoolStateTransition(
	settledUpdateWithUpdatedSubaccount SettledUpdate,
	quoteAssetId uint32,
) (*types.CollateralTransferPerpetualPositionStateTransition, error)

GetCollateralPoolStateTransition checks whether a perpetual position will be opened or closed for a subaccount and therefore whether we need to transfer between the dummy collateral pool and the collateral pool for the perpetual. This function assumes that the subaccount is valid under collateral pool constraints. The input `settledUpdate` must have an updated subaccount (`settledUpdate.SettledSubaccount`), so all the updates must have been applied already to the subaccount.

func GetDeltaOpenInterestFromUpdates

func GetDeltaOpenInterestFromUpdates(
	settledUpdates []SettledUpdate,
	updateType types.UpdateType,
) (ret *perptypes.OpenInterestDelta)

For `Match` updates:

  • returns a struct `OpenInterest` if input updates results in OI delta.
  • returns nil if OI delta is zero.
  • panics if update format is invalid.

For other update types, returns nil.

func GetSettledSubaccountWithPerpetuals

func GetSettledSubaccountWithPerpetuals(
	subaccount types.Subaccount,
	perpetuals map[uint32]perptypes.Perpetual,
	assetYieldIndex *big.Rat,
	availableYield *big.Int,
	earnsTdaiYield bool,
	quoteAssetId uint32,
) (
	settledSubaccount types.Subaccount,
	fundingPayments map[uint32]dtypes.SerializableInt,
	totalNewYield *big.Int,
	err error,
)

GetSettledSubaccountWithPerpetuals returns 1. a new settled subaccount given an unsettled subaccount, updating the AssetPositions, FundingIndex, and LastFundingPayment fields accordingly (does not persist any changes) and 2. a map with perpetual ID as key and last funding payment as value (for emitting funding payments to indexer).

Note that this is a stateless utility function.

func HandleInsufficientYieldDueToNegativeTNC

func HandleInsufficientYieldDueToNegativeTNC(
	totalNewYield *big.Int,
	availableYield *big.Int,
) (
	yieldToTransfer *big.Int,
)

func IsValidCollateralPoolUpdate

func IsValidCollateralPoolUpdate(
	settledUpdate SettledUpdate,
	perpIdToCollateralPoolId map[uint32]uint32,
) (types.UpdateResult, error)

func IsValidStateTransitionForUndercollateralizedSubaccount

func IsValidStateTransitionForUndercollateralizedSubaccount(
	bigCurNetCollateral *big.Int,
	bigCurInitialMargin *big.Int,
	bigCurMaintenanceMargin *big.Int,
	bigNewNetCollateral *big.Int,
	bigNewMaintenanceMargin *big.Int,
) types.UpdateResult

IsValidStateTransitionForUndercollateralizedSubaccount returns an `UpdateResult` denoting whether this state transition is valid. This function accepts the collateral and margin requirements of a subaccount before and after an update ("cur" and "new", respectively).

This function should only be called if the account is undercollateralized after the update.

A state transition is valid if the subaccount enters a "less-or-equally-risky" state after an update. i.e.`newNetCollateral / newMaintenanceMargin >= curNetCollateral / curMaintenanceMargin`.

Otherwise, the state transition is invalid. If the account was previously undercollateralized, `types.StillUndercollateralized` is returned. If the account was previously collateralized and is now undercollateralized, `types.NewlyUndercollateralized` is returned.

Note that the inequality `newNetCollateral / newMaintenanceMargin >= curNetCollateral / curMaintenanceMargin` has divide-by-zero issue when margin requirements are zero. To make sure the state transition is valid, we special case this scenario and only allow state transition that improves net collateral.

func NewMsgServerImpl

func NewMsgServerImpl(keeper Keeper) types.MsgServer

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

func UpdateSubaccountPositions

func UpdateSubaccountPositions(
	settledUpdates []SettledUpdate,
	perpIdToFundingIndex map[uint32]dtypes.SerializableInt,
	perpIdToYieldIndex map[uint32]string,
)

Types

type Keeper

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

func NewKeeper

func NewKeeper(
	cdc codec.BinaryCodec,
	storeKey storetypes.StoreKey,
	assetsKeeper types.AssetsKeeper,
	bankKeeper types.BankKeeper,
	perpetualsKeeper types.PerpetualsKeeper,
	ratelimitKeeper types.RatelimitKeeper,
	blocktimeKeeper types.BlocktimeKeeper,
	indexerEventManager indexer_manager.IndexerEventManager,
) *Keeper

func (Keeper) CanUpdateSubaccounts

func (k Keeper) CanUpdateSubaccounts(
	ctx sdk.Context,
	updates []types.Update,
	updateType types.UpdateType,
) (
	success bool,
	successPerUpdate []types.UpdateResult,
	err error,
)

CanUpdateSubaccounts will validate all `updates` to the relevant subaccounts. The `updates` do not have to contain unique `SubaccountIds`. Each update is considered in isolation. Thus if two updates are provided with the same `SubaccountId`, they are validated without respect to each other.

Returns a `success` value of `true` if all updates are valid. Returns a `successPerUpdates` value, which is a slice of `UpdateResult`. These map to the updates and are used to indicate which of the updates caused a failure, if any.

func (Keeper) ClaimYieldForSubaccountFromIdAndSetNewState

func (k Keeper) ClaimYieldForSubaccountFromIdAndSetNewState(
	ctx sdk.Context,
	subaccountId *types.SubaccountId,
) (
	err error,
)

TODO: [YBCP-89]

func (Keeper) DepositFundsFromAccountToSubaccount

func (k Keeper) DepositFundsFromAccountToSubaccount(
	ctx sdk.Context,
	fromAccount sdk.AccAddress,
	toSubaccountId types.SubaccountId,
	assetId uint32,
	quantums *big.Int,
) error

DepositFundsFromAccountToSubaccount returns an error if the call to `k.CanUpdateSubaccounts()` fails. Otherwise, increases the asset quantums in the subaccount, translates the `assetId` and `quantums` into a `sdk.Coin`, and calls `bankKeeper.SendCoinsFromAccountToModule()`. TODO(CORE-168): Change function interface to accept `denom` and `amount` instead of `assetId` and `quantums`.

func (Keeper) DepositYieldToSubaccount

func (k Keeper) DepositYieldToSubaccount(
	ctx sdk.Context,
	subaccountId types.SubaccountId,
	totalYieldInQuantums *big.Int,
) error

func (Keeper) DoesSubaccountEarnTDaiYield

func (k Keeper) DoesSubaccountEarnTDaiYield(
	ctx sdk.Context,
	subaccount types.Subaccount,
) (
	earnsTdaiYield bool,
	err error,
)

func (Keeper) ForEachSubaccount

func (k Keeper) ForEachSubaccount(ctx sdk.Context, callback func(types.Subaccount) (finished bool))

ForEachSubaccount performs a callback across all subaccounts. The callback function should return a boolean if we should end iteration or not. This is more performant than GetAllSubaccount because it does not fetch all at once. and you do not need to iterate through all the subaccounts.

func (Keeper) GetAllSubaccount

func (k Keeper) GetAllSubaccount(ctx sdk.Context) (list []types.Subaccount)

GetAllSubaccount returns all subaccount. For more performant searching and iteration, use `ForEachSubaccount`.

func (Keeper) GetCollateralPoolAddressFromPerpetualId

func (k Keeper) GetCollateralPoolAddressFromPerpetualId(ctx sdk.Context, perpetualId uint32) (sdk.AccAddress, error)

GetCollateralPoolAddressFromPerpetualId returns the collateral pool address based on the perpetual ID passed in as an argument.

func (Keeper) GetCollateralPoolAddressFromSubaccountId

func (k Keeper) GetCollateralPoolAddressFromSubaccountId(ctx sdk.Context, subaccountId types.SubaccountId) (
	sdk.AccAddress,
	error,
)

GetCollateralPoolAddressFromSubaccountId returns the collateral pool address for a subaccount based on the subaccount's perpetual positions. If the subaccount has no perpetual positions open, the default collateral pool address is the module's pool address.

func (Keeper) GetCollateralPoolFromSubaccount

func (k Keeper) GetCollateralPoolFromSubaccount(ctx sdk.Context, subaccount types.Subaccount) (
	perptypes.CollateralPool,
	error,
)

GetCollateralPoolFromSubaccount returns the collateral pool for a corresponding subaccount

func (Keeper) GetIndexerEventManager

func (k Keeper) GetIndexerEventManager() indexer_manager.IndexerEventManager

func (Keeper) GetNegativeTncSubaccountSeenAtBlock

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

GetNegativeTncSubaccountSeenAtBlock gets the last block height a negative TNC subaccount was seen in state for the given collateral pool address and a boolean for whether it exists in state.

func (Keeper) GetNetCollateralAndMarginRequirements

func (k Keeper) GetNetCollateralAndMarginRequirements(
	ctx sdk.Context,
	update types.Update,
) (
	bigNetCollateral *big.Int,
	bigInitialMargin *big.Int,
	bigMaintenanceMargin *big.Int,
	err error,
)

GetNetCollateralAndMarginRequirements returns the total net collateral, total initial margin requirement, and total maintenance margin requirement for the subaccount as if the `update` was applied. It is used to get information about speculative changes to the subaccount.

The provided update can also be "zeroed" in order to get information about the current state of the subaccount (i.e. with no changes).

If two position updates reference the same position, an error is returned.

All return values are denoted in quote quantums.

func (Keeper) GetRandomSubaccount

func (k Keeper) GetRandomSubaccount(ctx sdk.Context, rand *rand.Rand) (types.Subaccount, error)

GetRandomSubaccount returns a random subaccount. Will return an error if there are no subaccounts.

func (Keeper) GetSettledSubaccount

func (k Keeper) GetSettledSubaccount(
	ctx sdk.Context,
	subaccount types.Subaccount,
) (
	settledSubaccount types.Subaccount,
	fundingPayments map[uint32]dtypes.SerializableInt,
	yieldForSubaccount *big.Int,
	err error,
)

getSettledSubaccount returns 1. a new settled subaccount given an unsettled subaccount, updating the AssetPositions (including yield claims), FundingIndex, and L astFundingPayment fields accordingly (does not persist any changes) and 2. a map with perpetual ID as key and last funding payment as value (for emitting funding payments to indexer).

func (Keeper) GetSubaccount

func (k Keeper) GetSubaccount(
	ctx sdk.Context,
	id types.SubaccountId,
) (val types.Subaccount)

GetSubaccount returns a subaccount from its index.

Note that this function is getting called very frequently; metrics in this function should be sampled to reduce CPU time.

func (Keeper) InitializeForGenesis

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

func (Keeper) IsValidMultiCollateralUpdate

func (k Keeper) IsValidMultiCollateralUpdate(
	ctx sdk.Context,
	settledUpdate SettledUpdate,
	perpIdToParams map[uint32]perptypes.PerpetualParams,
) (types.UpdateResult, error)

func (Keeper) Logger

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

func (Keeper) SetNegativeTncSubaccountSeenAtBlock

func (k Keeper) SetNegativeTncSubaccountSeenAtBlock(
	ctx sdk.Context,
	perpetualId uint32,
	blockHeight uint32,
) error

SetNegativeTncSubaccountSeenAtBlock sets a block number in state where a negative TNC subaccount was seen for a specific collateral pool. This function will overwrite previous values at this key. This function will panic if the old block height is greater than the new block height.

func (Keeper) SetSubaccount

func (k Keeper) SetSubaccount(ctx sdk.Context, subaccount types.Subaccount)

SetSubaccount set a specific subaccount in the store from its index. Note that empty subaccounts are removed from state.

func (Keeper) TransferFeesToFeeCollectorModule

func (k Keeper) TransferFeesToFeeCollectorModule(
	ctx sdk.Context,
	assetId uint32,
	quantums *big.Int,
	perpetualId uint32,
) error

TransferFeesToFeeCollectorModule translates the assetId and quantums into a sdk.Coin, and moves the funds from subaccounts module to the `fee_collector` module account by calling bankKeeper.SendCoins(). Does not change any individual subaccount state.

func (Keeper) TransferFundsFromSubaccountToSubaccount

func (k Keeper) TransferFundsFromSubaccountToSubaccount(
	ctx sdk.Context,
	senderSubaccountId types.SubaccountId,
	recipientSubaccountId types.SubaccountId,
	assetId uint32,
	quantums *big.Int,
) error

TransferFundsFromSubaccountToSubaccount returns an error if the call to `k.CanUpdateSubaccounts()` fails. Otherwise, updates the asset quantums in the subaccounts, translates the `assetId` and `quantums` into a `sdk.Coin`, and call `bankKeeper.SendCoins()` if the collateral pools for the two subaccounts are different. TODO(CORE-168): Change function interface to accept `denom` and `amount` instead of `assetId` and `quantums`.

func (Keeper) TransferInsuranceFundPayments

func (k Keeper) TransferInsuranceFundPayments(
	ctx sdk.Context,
	insuranceFundDelta *big.Int,
	perpetualId uint32,
	assetId uint32,
) error

TransferInsuranceFundPayments transfers funds in and out of the insurance fund to the subaccounts module by calling `bankKeeper.SendCoins`. This function transfers funds

  • from the insurance fund to the subaccounts module when `insuranceFundDelta` is negative.
  • from the subaccounts module to the insurance fund when `insuranceFundDelta` is positive.
  • does nothing if `insuranceFundDelta` is zero.

If the sender account does not have enough balance for the transfer, an error is returned. Note this function does not change any individual subaccount state.

func (Keeper) TransferLiquidityFee

func (k Keeper) TransferLiquidityFee(
	ctx sdk.Context,
	liquidityFeeQuoteQuantums *big.Int,
	perpetualId uint32,
	assetId uint32,
) error

func (Keeper) TransferRouterFee

func (k Keeper) TransferRouterFee(
	ctx sdk.Context,
	routerFeeQuoteQuantums *big.Int,
	routerFeeOwner string,
	perpetualId uint32,
	assetId uint32,
) error

func (Keeper) TransferValidatorFee

func (k Keeper) TransferValidatorFee(
	ctx sdk.Context,
	validatorFeeQuoteQuantums *big.Int,
	perpetualId uint32,
	assetId uint32,
) error

func (Keeper) UpdateSubaccounts

func (k Keeper) UpdateSubaccounts(
	ctx sdk.Context,
	updates []types.Update,
	updateType types.UpdateType,
) (
	success bool,
	successPerUpdate []types.UpdateResult,
	err error,
)

UpdateSubaccounts validates and applies all `updates` to the relevant subaccounts as long as this is a valid state-transition for all subaccounts involved. All `updates` are made atomically, meaning that all state-changes will either succeed or all will fail.

Returns a boolean indicating whether the update was successfully applied or not. If `false`, then no updates to any subaccount were made. A second return value returns an array of `UpdateResult` which map to the `updates` to indicate which of the updates caused a failure, if any. This function also transfers collateral between the cross-perpetual collateral pool and isolated perpetual collateral pools if any of the updates led to an isolated perpetual posititon to be opened or closed. This is done using the `x/bank` keeper and updates `x/bank` state.

Each `SubaccountId` in the `updates` must be unique or an error is returned.

func (Keeper) WithdrawFundsFromSubaccountToAccount

func (k Keeper) WithdrawFundsFromSubaccountToAccount(
	ctx sdk.Context,
	fromSubaccountId types.SubaccountId,
	toAccount sdk.AccAddress,
	assetId uint32,
	quantums *big.Int,
) error

WithdrawFundsFromSubaccountToAccount returns an error if the call to `k.CanUpdateSubaccounts()` fails. Otherwise, deducts the asset quantums from the subaccount, translates the `assetId` and `quantums` into a `sdk.Coin`, and calls `bankKeeper.SendCoins()`.

type SettledUpdate

type SettledUpdate struct {
	// The `Subaccount` for which this update applies to, in its settled form.
	SettledSubaccount types.Subaccount
	// A list of changes to make to any `AssetPositions` in the `Subaccount`.
	AssetUpdates []types.AssetUpdate
	// A list of changes to make to any `PerpetualPositions` in the `Subaccount`.
	PerpetualUpdates []types.PerpetualUpdate
}

SettledUpdate is used internally in the subaccounts keeper to to specify changes to one or more `Subaccounts` (for example the result of a trade, transfer, etc). The subaccount is always in its settled state.

Jump to

Keyboard shortcuts

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