Documentation ¶
Index ¶
- Constants
- func FundingPayment(position types.Position, marketLatestCumulativePremiumFraction sdk.Dec) sdk.Dec
- func MarginRatio(position types.Position, positionNotional sdk.Dec, ...) sdk.Dec
- func NewMsgServerImpl(keeper Keeper) types.MsgServer
- func NewQuerier(k Keeper) types.QueryServer
- func PositionNotionalSpot(amm types.AMM, position types.Position) (positionNotional sdk.Dec, err error)
- func PrettyLiquidateResponse(resps []*types.MsgMultiLiquidateResponse_LiquidationResponse) (pretty string, err error)
- func UnrealizedPnl(position types.Position, positionNotional sdk.Dec) (unrealizedPnlSigned sdk.Dec)
- type ArgsCreateMarket
- type Hooks
- type Keeper
- func (k Keeper) AddMargin(ctx sdk.Context, pair asset.Pair, traderAddr sdk.AccAddress, ...) (res *types.MsgAddMarginResponse, err error)
- func (k Keeper) Admin() admin
- func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, _ uint64)
- func (k Keeper) BeforeEpochStart(ctx sdk.Context, epochIdentifier string, epochNumber uint64)
- func (k Keeper) CalcTwap(ctx sdk.Context, pair asset.Pair, twapCalcOption types.TwapCalcOption, ...) (price sdk.Dec, err error)
- func (k Keeper) ChangeMarketEnabledParameter(ctx sdk.Context, pair asset.Pair, enabled bool) (err error)
- func (k Keeper) ClosePosition(ctx sdk.Context, pair asset.Pair, traderAddr sdk.AccAddress) (*types.PositionResp, error)
- func (k Keeper) DecrementPrepaidBadDebt(ctx sdk.Context, market types.Market, amount sdkmath.Int)
- func (k Keeper) EditPriceMultiplier(ctx sdk.Context, pair asset.Pair, newPriceMultiplier sdk.Dec) (err error)
- func (k Keeper) EditSwapInvariant(ctx sdk.Context, pair asset.Pair, newSwapInvariant sdk.Dec) (err error)
- func (k Keeper) Hooks() Hooks
- func (k Keeper) IncrementPrepaidBadDebt(ctx sdk.Context, market types.Market, amount sdkmath.Int)
- func (k Keeper) Logger(ctx sdk.Context) log.Logger
- func (k Keeper) MarketOrder(ctx sdk.Context, pair asset.Pair, dir types.Direction, ...) (positionResp *types.PositionResp, err error)
- func (k Keeper) MultiLiquidate(ctx sdk.Context, liquidator sdk.AccAddress, ...) ([]*types.MsgMultiLiquidateResponse_LiquidationResponse, error)
- func (k Keeper) PartialClose(ctx sdk.Context, pair asset.Pair, traderAddr sdk.AccAddress, sizeAmt sdk.Dec) (*types.PositionResp, error)
- func (k Keeper) PositionNotionalTWAP(ctx sdk.Context, position types.Position, twapLookbackWindow time.Duration) (positionNotional sdk.Dec, err error)
- func (k Keeper) RemoveMargin(ctx sdk.Context, pair asset.Pair, traderAddr sdk.AccAddress, ...) (res *types.MsgRemoveMarginResponse, err error)
- func (k Keeper) SwapBaseAsset(ctx sdk.Context, market types.Market, amm types.AMM, dir types.Direction, ...) (updatedAMM *types.AMM, quoteAssetDelta sdk.Dec, err error)
- func (k Keeper) SwapQuoteAsset(ctx sdk.Context, market types.Market, amm types.AMM, dir types.Direction, ...) (updatedAMM *types.AMM, baseAssetDelta sdk.Dec, err error)
- func (k Keeper) WithdrawFromVault(ctx sdk.Context, market types.Market, receiver sdk.AccAddress, ...) (err error)
- func (k Keeper) ZeroPrepaidBadDebt(ctx sdk.Context, market types.Market)
Constants ¶
const ( NamespaceMarkets collections.Namespace = iota + 11 // == 11 because iota starts from 0 NamespaceAmms NamespacePositions NamespaceReserveSnapshots )
Variables ¶
This section is empty.
Functions ¶
func FundingPayment ¶
FundingPayment calculates the funding payment of a position.
args:
- position: the position to calculate funding payment for
- marketLatestCumulativePremiumFraction: the latest cumulative premium fraction of the market
returns:
- fundingPayment: the funding payment of the position, signed
func MarginRatio ¶
func MarginRatio( position types.Position, positionNotional sdk.Dec, marketLatestCumulativePremiumFraction sdk.Dec, ) sdk.Dec
Given a position and it's notional value, returns the margin ratio.
func NewMsgServerImpl ¶
NewMsgServerImpl returns an implementation of the MsgServer interface for the provided Keeper.
func NewQuerier ¶
func NewQuerier(k Keeper) types.QueryServer
func PositionNotionalSpot ¶
func PositionNotionalSpot(amm types.AMM, position types.Position) (positionNotional sdk.Dec, err error)
PositionNotionalSpot returns the position's notional value based on the spot price.
func PrettyLiquidateResponse ¶
func PrettyLiquidateResponse( resps []*types.MsgMultiLiquidateResponse_LiquidationResponse, ) (pretty string, err error)
PrettyLiquidateResponse converts a slice of liquidation responses into a pretty formatted JSON array for each response. This helps with providing descriptive error messages in the case of failed liquidations.
Example outputs:
```json [
{ "success": false, "error": "failed liquidation A", "liquidator_fee": null, "perp_ef_fee": null, "trader": "dummytraderA" }, { "success": true, "error": "", "liquidator_fee": { denom: "unibi", amount: "420"}, "perp_ef_fee": null, "trader": "dummytraderB" }
] ```
Types ¶
type ArgsCreateMarket ¶
type Hooks ¶
type Hooks struct {
// contains filtered or unexported fields
}
Hooks wrapper struct for perps keeper.
func (Hooks) AfterEpochEnd ¶
type Keeper ¶
type Keeper struct { BankKeeper types.BankKeeper AccountKeeper types.AccountKeeper OracleKeeper types.OracleKeeper EpochKeeper types.EpochKeeper Markets collections.Map[asset.Pair, types.Market] AMMs collections.Map[asset.Pair, types.AMM] Positions collections.Map[collections.Pair[asset.Pair, sdk.AccAddress], types.Position] ReserveSnapshots collections.Map[collections.Pair[asset.Pair, time.Time], types.ReserveSnapshot] // contains filtered or unexported fields }
func NewKeeper ¶
func NewKeeper( cdc codec.BinaryCodec, storeKey storetypes.StoreKey, accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper, oracleKeeper types.OracleKeeper, epochKeeper types.EpochKeeper, ) Keeper
NewKeeper Creates a new x/perp Keeper instance.
func (Keeper) AddMargin ¶
func (k Keeper) AddMargin( ctx sdk.Context, pair asset.Pair, traderAddr sdk.AccAddress, marginToAdd sdk.Coin, ) (res *types.MsgAddMarginResponse, err error)
AddMargin adds margin to an existing position, effectively deleveraging it. Adding margin increases the margin ratio of the corresponding position.
args:
- ctx: the cosmos-sdk context
- pair: the asset pair
- traderAddr: the trader's address
- marginToAdd: the amount of margin to add. Must be positive.
ret:
- res: the response
- err: error if any
func (Keeper) Admin ¶
func (k Keeper) Admin() admin
Admin is syntactic sugar to separate admin calls off from the other Keeper methods.
These Admin functions should: 1. Not be wired into the MsgServer or 2. Not be called in other methods in the x/perp module. 3. Only be callable from x/wasm/binding via sudo contracts.
The intention here is to make it more obvious to the developer that an unsafe function is being used when it's called on the Admin() struct.
func (Keeper) AfterEpochEnd ¶
func (Keeper) BeforeEpochStart ¶
func (Keeper) CalcTwap ¶
func (k Keeper) CalcTwap( ctx sdk.Context, pair asset.Pair, twapCalcOption types.TwapCalcOption, direction types.Direction, assetAmt sdk.Dec, lookbackInterval time.Duration, ) (price sdk.Dec, err error)
Gets the time-weighted average price from [ ctx.BlockTime() - interval, ctx.BlockTime() ) Note the open-ended right bracket.
args:
- ctx: cosmos-sdk context
- pair: the token pair
- twapCalcOption: one of SPOT, QUOTE_ASSET_SWAP, or BASE_ASSET_SWAP
- direction: add or remove, only required for QUOTE_ASSET_SWAP or BASE_ASSET_SWAP
- assetAmount: amount of asset to add or remove, only required for QUOTE_ASSET_SWAP or BASE_ASSET_SWAP
- lookbackInterval: how far back to calculate TWAP
ret:
- price: TWAP as sdk.Dec
- err: error
func (Keeper) ChangeMarketEnabledParameter ¶
func (k Keeper) ChangeMarketEnabledParameter(ctx sdk.Context, pair asset.Pair, enabled bool) (err error)
ChangeMarketEnabledParameter change the market enabled parameter
func (Keeper) ClosePosition ¶
func (k Keeper) ClosePosition(ctx sdk.Context, pair asset.Pair, traderAddr sdk.AccAddress) (*types.PositionResp, error)
ClosePosition closes a position entirely and transfers the remaining margin back to the user. Errors if the position has bad debt.
args:
- ctx: the cosmos-sdk context
- pair: the pair of the position
- traderAddr: the address of the trader
returns:
- positionResp: response object containing information about the position change
- err: error if any
func (Keeper) DecrementPrepaidBadDebt ¶
DecrementPrepaidBadDebt decrements the amount of bad debt prepaid by denom.
func (Keeper) EditPriceMultiplier ¶
func (k Keeper) EditPriceMultiplier( ctx sdk.Context, pair asset.Pair, newPriceMultiplier sdk.Dec, ) (err error)
EditPriceMultiplier edits the peg multiplier of an amm pool after making sure there's enough money in the perp EF fund to pay for the repeg. These funds get send to the vault to pay for trader's new net margin.
func (Keeper) EditSwapInvariant ¶
func (k Keeper) EditSwapInvariant(ctx sdk.Context, pair asset.Pair, newSwapInvariant sdk.Dec) (err error)
EditSwapInvariant edits the swap invariant of an amm pool after making sure there's enough money in the perp EF fund to pay for the repeg. These funds get send to the vault to pay for trader's new net margin.
func (Keeper) IncrementPrepaidBadDebt ¶
IncrementPrepaidBadDebt increases the bad debt for the provided denom.
func (Keeper) MarketOrder ¶ added in v0.21.5
func (k Keeper) MarketOrder( ctx sdk.Context, pair asset.Pair, dir types.Direction, traderAddr sdk.AccAddress, quoteAssetAmt sdkmath.Int, leverage sdk.Dec, baseAmtLimit sdk.Dec, ) (positionResp *types.PositionResp, err error)
MarketOrder opens a position on the selected pair.
args:
- ctx: cosmos-sdk context
- pair: pair to open position on
- dir: direction the user is taking
- traderAddr: address of the trader
- quoteAssetAmt: amount of quote asset to open position with
- leverage: leverage to open position with
- baseAmtLimit: minimum base asset amount to open position with
ret:
- positionResp: contains the result of the open position and the new position
- err: error
func (Keeper) MultiLiquidate ¶
func (k Keeper) MultiLiquidate( ctx sdk.Context, liquidator sdk.AccAddress, liquidationRequests []*types.MsgMultiLiquidate_Liquidation, ) ([]*types.MsgMultiLiquidateResponse_LiquidationResponse, error)
func (Keeper) PartialClose ¶ added in v0.21.6
func (Keeper) PositionNotionalTWAP ¶
func (k Keeper) PositionNotionalTWAP(ctx sdk.Context, position types.Position, twapLookbackWindow time.Duration, ) (positionNotional sdk.Dec, err error)
PositionNotionalTWAP returns the position's notional value based on the TWAP price.
func (Keeper) RemoveMargin ¶
func (k Keeper) RemoveMargin( ctx sdk.Context, pair asset.Pair, traderAddr sdk.AccAddress, marginToRemove sdk.Coin, ) (res *types.MsgRemoveMarginResponse, err error)
RemoveMargin further leverages an existing position by directly removing
the margin (collateral) that backs it from the vault. This also decreases the margin ratio of the position.
Fails if the position goes underwater.
args:
- ctx: the cosmos-sdk context
- pair: the asset pair
- traderAddr: the trader's address
- margin: the amount of margin to withdraw. Must be positive.
ret:
- marginOut: the amount of margin removed
- fundingPayment: the funding payment that was applied with this position interaction
- err: error if any
func (Keeper) SwapBaseAsset ¶
func (k Keeper) SwapBaseAsset( ctx sdk.Context, market types.Market, amm types.AMM, dir types.Direction, baseAssetAmt sdk.Dec, quoteAssetLimit sdk.Dec, ) (updatedAMM *types.AMM, quoteAssetDelta sdk.Dec, err error)
SwapBaseAsset trades baseAssets in exchange for quoteAssets. Updates the AMM reserves and persists it to state.
args:
- ctx: cosmos-sdk context
- market: a market like BTC:NUSD
- amm: the reserves of the AMM
- dir: the direction the user takes
- baseAssetAmt: the amount of base assets to swap, must be positive
- quoteAssetLimit: the limit of quote assets to swap
returns:
- updatedAMM: the updated amm
- quoteAssetDelta: the amount of quote assets swapped
- err: error if any
NOTE: the quoteAssetDelta is always positive
func (Keeper) SwapQuoteAsset ¶
func (k Keeper) SwapQuoteAsset( ctx sdk.Context, market types.Market, amm types.AMM, dir types.Direction, quoteAssetAmt sdk.Dec, baseAssetLimit sdk.Dec, ) (updatedAMM *types.AMM, baseAssetDelta sdk.Dec, err error)
SwapQuoteAsset trades quoteAssets in exchange for baseAssets. Updates the AMM reserves and persists it to state.
args:
- ctx: cosmos-sdk context
- market: a market like BTC:NUSD
- amm: the reserves of the AMM
- dir: the direction the user takes
- quoteAssetAmt: the amount of quote assets to swap, must be positive
- baseAssetLimit: the limit of base assets to swap
returns:
- updatedAMM: the updated amm
- baseAssetDelta: the amount of base assets swapped, unsigned
- err: error if any
NOTE: the baseAssetDelta is always positive
func (Keeper) WithdrawFromVault ¶
func (k Keeper) WithdrawFromVault( ctx sdk.Context, market types.Market, receiver sdk.AccAddress, amountToWithdraw sdkmath.Int, ) (err error)
Withdraws coins from the vault to the receiver. If the total amount of coins to withdraw is greater than the vault's amount, then withdraw the shortage from the PerpEF and mark it as prepaid bad debt.
Prepaid bad debt will count towards realized bad debt from negative PnL positions when those are closed/liquidated.
An example of this happening is when a long position has really high PnL and closes their position, realizing their profits. There is a counter party short position with really negative PnL, but their position hasn't been closed/liquidated yet. We must pay the long trader first, which results in funds being taken from the EF. when the short position is closed, it also realizes some bad debt but because we have already withdrawn from the EF, we don't need to withdraw more from the EF.
args: - ctx: context - market: the perp market - receiver: the receiver of the coins - amountToWithdraw: amount of coins to withdraw
returns: - error: error