Skip to content

Commit

Permalink
slight refactor in apis
Browse files Browse the repository at this point in the history
Signed-off-by: Shrenuj Bansal <shrenuj@dydx.exchange>
  • Loading branch information
shrenujb committed Mar 6, 2024
1 parent 8f36ca0 commit 7dfad36
Showing 1 changed file with 8 additions and 32 deletions.
40 changes: 8 additions & 32 deletions protocol/x/subaccounts/keeper/subaccount.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,17 @@ func (k Keeper) GetCollateralPoolForSubaccount(ctx sdk.Context, subaccountId typ
sdk.AccAddress,
error,
) {
poolName, err := k.GetCollateralPoolNameForSubaccount(ctx, subaccountId)
if err != nil {
return nil, err
// Use the default collateral pool if the subaccount has no perpetual positions.
subaccount := k.GetSubaccount(ctx, subaccountId)
if len(subaccount.PerpetualPositions) == 0 {
return types.ModuleAddress, nil
}
return authtypes.NewModuleAddress(poolName), nil

return k.GetCollateralPoolFromPerpetualId(ctx, subaccount.PerpetualPositions[0].PerpetualId)
}

// GetCollateralPoolForSubaccountWithPerpetuals returns the collateral pool address based on the
// perpetual passes in as an argument.
func (k Keeper) GetCollateralPoolFromPerpetualId(ctx sdk.Context, perpetualId uint32) (sdk.AccAddress, error) {
perpetual, err := k.perpetualsKeeper.GetPerpetual(ctx, perpetualId)
if err != nil {
Expand All @@ -82,34 +86,6 @@ func (k Keeper) GetCollateralPoolFromPerpetualId(ctx sdk.Context, perpetualId ui
return authtypes.NewModuleAddress(types.ModuleName), nil
}

func (k Keeper) GetCollateralPoolNameForSubaccount(ctx sdk.Context, subaccountId types.SubaccountId) (string, error) {
subaccount := k.GetSubaccount(ctx, subaccountId)
if len(subaccount.PerpetualPositions) == 0 {
return types.ModuleName, nil
}

// Get the first perpetual position and return the collateral pool name.
perpetual, err := k.perpetualsKeeper.GetPerpetual(ctx, subaccount.PerpetualPositions[0].PerpetualId)
if err != nil {
panic(fmt.Sprintf("GetCollateralPoolNameForSubaccount: %v", err))
}

if perpetual.Params.MarketType == perptypes.PerpetualMarketType_PERPETUAL_MARKET_TYPE_ISOLATED {
return types.ModuleName + ":" + lib.UintToString(perpetual.GetId()), nil
}

return types.ModuleName, nil
}

// IsIsolatedMarketSubaccount returns whether a subaccount is isolated to a specific market.
func (k Keeper) IsIsolatedMarketSubaccount(ctx sdk.Context, subaccountId types.SubaccountId) (bool, error) {
poolName, err := k.GetCollateralPoolNameForSubaccount(ctx, subaccountId)
if err != nil {
panic(fmt.Sprintf("IsIsolatedMarketSubaccount: %v", err))
}
return poolName != types.ModuleName, nil
}

// GetSubaccount returns a subaccount from its index.
//
// Note that this function is getting called very frequently; metrics in this function
Expand Down

0 comments on commit 7dfad36

Please sign in to comment.