Skip to content

Commit

Permalink
fix tests
Browse files Browse the repository at this point in the history
Signed-off-by: Shrenuj Bansal <[email protected]>
  • Loading branch information
shrenujb committed Mar 2, 2024
1 parent 931a8e8 commit 40eb007
Show file tree
Hide file tree
Showing 11 changed files with 148 additions and 7 deletions.
4 changes: 3 additions & 1 deletion protocol/daemons/liquidation/client/grpc_helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package client_test

import (
"context"
"cosmossdk.io/log"
"errors"
"testing"

"cosmossdk.io/log"

"github.com/cosmos/cosmos-sdk/types/query"
"github.com/dydxprotocol/v4-chain/protocol/daemons/flags"
"github.com/dydxprotocol/v4-chain/protocol/daemons/liquidation/api"
Expand Down Expand Up @@ -409,6 +410,7 @@ func TestGetAllMarketPrices(t *testing.T) {
response2 := &pricestypes.QueryAllMarketPricesResponse{
MarketPrices: []pricestypes.MarketPrice{
constants.TestMarketPrices[2],
constants.TestMarketPrices[3],
},
}
mck.On("AllMarketPrices", mock.Anything, req2).Return(response2, nil)
Expand Down
2 changes: 1 addition & 1 deletion protocol/testing/e2e/gov/perpetuals_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (

var (
TEST_PERPETUAL_PARAMS = perptypes.PerpetualParams{
Id: 765,
Id: 0,
Ticker: "BTC-ADV4TNT",
MarketId: 123,
AtomicResolution: -8,
Expand Down
51 changes: 51 additions & 0 deletions protocol/testutil/constants/perpetuals.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,57 @@ var (
}
)

var TestMarketPerpetuals = []perptypes.Perpetual{
{
Params: perptypes.PerpetualParams{
Id: 0,
Ticker: "BTC-USD",
MarketId: uint32(0),
AtomicResolution: int32(-10),
DefaultFundingPpm: int32(0),
LiquidityTier: uint32(0),
MarketType: perptypes.PerpetualMarketType_PERPETUAL_MARKET_TYPE_CROSS,
},
FundingIndex: dtypes.ZeroInt(),
},
{
Params: perptypes.PerpetualParams{
Id: 1,
Ticker: "ETH-USD",
MarketId: uint32(1),
AtomicResolution: int32(-9),
DefaultFundingPpm: int32(0),
LiquidityTier: uint32(0),
MarketType: perptypes.PerpetualMarketType_PERPETUAL_MARKET_TYPE_CROSS,
},
FundingIndex: dtypes.ZeroInt(),
},
{
Params: perptypes.PerpetualParams{
Id: 2,
Ticker: "SOL-USD",
MarketId: uint32(2),
AtomicResolution: int32(-9),
DefaultFundingPpm: int32(0),
LiquidityTier: uint32(3),
MarketType: perptypes.PerpetualMarketType_PERPETUAL_MARKET_TYPE_CROSS,
},
FundingIndex: dtypes.ZeroInt(),
},
{
Params: perptypes.PerpetualParams{
Id: 3,
Ticker: "ISO-USD",
MarketId: uint32(3),
AtomicResolution: int32(-9),
DefaultFundingPpm: int32(0),
LiquidityTier: uint32(3),
MarketType: perptypes.PerpetualMarketType_PERPETUAL_MARKET_TYPE_ISOLATED,
},
FundingIndex: dtypes.ZeroInt(),
},
}

// AddPremiumVotes messages.
var (
TestAddPremiumVotesMsg = &perptypes.MsgAddPremiumVotes{
Expand Down
1 change: 1 addition & 0 deletions protocol/testutil/constants/pricefeed.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ var (
MarketId0 = uint32(0)
MarketId1 = uint32(1)
MarketId2 = uint32(2)
MarketId3 = uint32(3)

MarketId7 = uint32(7)
MarketId8 = uint32(8)
Expand Down
1 change: 1 addition & 0 deletions protocol/testutil/constants/prices.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ var (
types.NewMarketPriceUpdate(MarketId0, Price5),
types.NewMarketPriceUpdate(MarketId1, Price6),
types.NewMarketPriceUpdate(MarketId2, Price7),
types.NewMarketPriceUpdate(MarketId3, Price4),
}

// `MsgUpdateMarketPrices`.
Expand Down
16 changes: 16 additions & 0 deletions protocol/testutil/keeper/perpetuals.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,22 @@ func PopulateTestPremiumStore(
}
}

func CreateTestPerpetuals(t *testing.T, ctx sdk.Context, k *keeper.Keeper) {
for _, p := range constants.TestMarketPerpetuals {
_, err := k.CreatePerpetual(
ctx,
p.Params.Id,
p.Params.Ticker,
p.Params.MarketId,
p.Params.AtomicResolution,
p.Params.DefaultFundingPpm,
p.Params.LiquidityTier,
p.Params.MarketType,
)
require.NoError(t, err)
}
}

func CreateTestLiquidityTiers(t *testing.T, ctx sdk.Context, k *keeper.Keeper) {
for _, l := range constants.LiquidityTiers {
_, err := k.SetLiquidityTier(
Expand Down
2 changes: 1 addition & 1 deletion protocol/x/clob/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ func EndBlocker(
// Emit relevant metrics at the end of every block.
metrics.SetGauge(
metrics.InsuranceFundBalance,
metrics.GetMetricValueFromBigInt(keeper.GetInsuranceFundBalance(ctx, 0)),
metrics.GetMetricValueFromBigInt(keeper.GetCrossInsuranceFundBalance(ctx)),
)
}

Expand Down
17 changes: 17 additions & 0 deletions protocol/x/clob/keeper/deleveraging.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"math/big"
"time"

perptypes "github.com/dydxprotocol/v4-chain/protocol/x/perpetuals/types"

errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/telemetry"

Expand Down Expand Up @@ -149,6 +151,21 @@ func (k Keeper) GetInsuranceFundBalance(ctx sdk.Context, perpetualId uint32) (ba
return insuranceFundBalance.Amount.BigInt()
}

func (k Keeper) GetCrossInsuranceFundBalance(ctx sdk.Context) (balance *big.Int) {
usdcAsset, exists := k.assetsKeeper.GetAsset(ctx, assettypes.AssetUsdc.Id)
if !exists {
panic("GetInsuranceFundBalance: Usdc asset not found in state")
}
insuranceFundBalance := k.bankKeeper.GetBalance(
ctx,
perptypes.InsuranceFundModuleAddress,
usdcAsset.Denom,
)

// Return as big.Int.
return insuranceFundBalance.Amount.BigInt()
}

// CanDeleverageSubaccount returns true if a subaccount can be deleveraged.
// This function returns two booleans, shouldDeleverageAtBankruptcyPrice and shouldDeleverageAtOraclePrice.
// - shouldDeleverageAtBankruptcyPrice is true if the subaccount has negative TNC.
Expand Down
47 changes: 44 additions & 3 deletions protocol/x/clob/keeper/deleveraging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ func TestGetInsuranceFundBalance(t *testing.T) {
// Setup
assets []assettypes.Asset
insuranceFundBalance *big.Int
perpetualId uint32
perpetual *perptypes.Perpetual

// Expectations.
expectedInsuranceFundBalance *big.Int
Expand All @@ -43,20 +45,23 @@ func TestGetInsuranceFundBalance(t *testing.T) {
assets: []assettypes.Asset{
*constants.Usdc,
},
perpetualId: 0,
insuranceFundBalance: new(big.Int),
expectedInsuranceFundBalance: big.NewInt(0),
},
"can get positive balance": {
assets: []assettypes.Asset{
*constants.Usdc,
},
perpetualId: 0,
insuranceFundBalance: big.NewInt(100),
expectedInsuranceFundBalance: big.NewInt(100),
},
"can get greater than MaxUint64 balance": {
assets: []assettypes.Asset{
*constants.Usdc,
},
perpetualId: 0,
insuranceFundBalance: new(big.Int).Add(
new(big.Int).SetUint64(math.MaxUint64),
new(big.Int).SetUint64(math.MaxUint64),
Expand All @@ -66,8 +71,25 @@ func TestGetInsuranceFundBalance(t *testing.T) {
new(big.Int).SetUint64(math.MaxUint64),
),
},
"can get zero balance - isolated market": {
assets: []assettypes.Asset{
*constants.Usdc,
},
perpetualId: 3, // Isolated market.
insuranceFundBalance: new(big.Int),
expectedInsuranceFundBalance: big.NewInt(0),
},
"can get positive balance - isolated market": {
assets: []assettypes.Asset{
*constants.Usdc,
},
perpetualId: 3, // Isolated market.
insuranceFundBalance: big.NewInt(100),
expectedInsuranceFundBalance: big.NewInt(100),
},
"panics when asset not found in state": {
assets: []assettypes.Asset{},
perpetualId: 0,
expectedError: errors.New("GetInsuranceFundBalance: Usdc asset not found in state"),
},
}
Expand All @@ -79,6 +101,15 @@ func TestGetInsuranceFundBalance(t *testing.T) {
bankMock := &mocks.BankKeeper{}
ks := keepertest.NewClobKeepersTestContext(t, memClob, bankMock, &mocks.IndexerEventManager{})

ctx := ks.Ctx.WithIsCheckTx(true)
// Create the default markets.
keepertest.CreateTestMarkets(t, ctx, ks.PricesKeeper)

// Create liquidity tiers.
keepertest.CreateTestLiquidityTiers(t, ctx, ks.PerpetualsKeeper)

keepertest.CreateTestPerpetuals(t, ctx, ks.PerpetualsKeeper)

for _, a := range tc.assets {
_, err := ks.AssetsKeeper.CreateAsset(
ks.Ctx,
Expand All @@ -93,11 +124,13 @@ func TestGetInsuranceFundBalance(t *testing.T) {
require.NoError(t, err)
}

insuranceFundAddr, err := ks.PerpetualsKeeper.GetInsuranceFundModuleAddress(ks.Ctx, tc.perpetualId)
require.NoError(t, err)
if tc.insuranceFundBalance != nil {
bankMock.On(
"GetBalance",
mock.Anything,
perptypes.InsuranceFundModuleAddress,
insuranceFundAddr,
constants.Usdc.Denom,
).Return(
sdk.NewCoin(constants.Usdc.Denom, sdkmath.NewIntFromBigInt(tc.insuranceFundBalance)),
Expand All @@ -109,14 +142,14 @@ func TestGetInsuranceFundBalance(t *testing.T) {
t,
tc.expectedError.Error(),
func() {
ks.ClobKeeper.GetInsuranceFundBalance(ks.Ctx, 0)
ks.ClobKeeper.GetInsuranceFundBalance(ks.Ctx, tc.perpetualId)
},
)
} else {
require.Equal(
t,
tc.expectedInsuranceFundBalance,
ks.ClobKeeper.GetInsuranceFundBalance(ks.Ctx, 0),
ks.ClobKeeper.GetInsuranceFundBalance(ks.Ctx, tc.perpetualId),
)
}
})
Expand Down Expand Up @@ -192,6 +225,14 @@ func TestIsValidInsuranceFundDelta(t *testing.T) {
err := keepertest.CreateUsdcAsset(ks.Ctx, ks.AssetsKeeper)
require.NoError(t, err)

ctx := ks.Ctx.WithIsCheckTx(true)
keepertest.CreateTestMarkets(t, ctx, ks.PricesKeeper)

// Create liquidity tiers.
keepertest.CreateTestLiquidityTiers(t, ctx, ks.PerpetualsKeeper)

keepertest.CreateTestPerpetuals(t, ctx, ks.PerpetualsKeeper)

bankMock.On(
"GetBalance",
mock.Anything,
Expand Down
4 changes: 4 additions & 0 deletions protocol/x/perpetuals/keeper/perpetual.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ import (
gometrics "github.com/hashicorp/go-metrics"
)

// GetInsuranceFundName returns the name of the insurance fund account for a given perpetual.
// For isolated markets, the name is "insurance-fund:<perpetualId>".
// For cross markets, the name is "insurance-fund".
func (k Keeper) GetInsuranceFundName(ctx sdk.Context, perpetualId uint32) (string, error) {
perpetual, err := k.GetPerpetual(ctx, perpetualId)
if err != nil {
Expand All @@ -46,6 +49,7 @@ func (k Keeper) GetInsuranceFundName(ctx sdk.Context, perpetualId uint32) (strin
panic(fmt.Sprintf("invalid market type %v for perpetual %d", perpetual.Params.MarketType, perpetualId))
}

// GetInsuranceFundModuleAddress returns the address of the insurance fund account for a given perpetual.
func (k Keeper) GetInsuranceFundModuleAddress(ctx sdk.Context, perpetualId uint32) (sdk.AccAddress, error) {
insuranceFundName, err := k.GetInsuranceFundName(ctx, perpetualId)
if err != nil {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package keeper_test

import (
errorsmod "cosmossdk.io/errors"
"errors"
"testing"

errorsmod "cosmossdk.io/errors"

"cosmossdk.io/log"
"github.com/dydxprotocol/v4-chain/protocol/daemons/pricefeed/api"
"github.com/dydxprotocol/v4-chain/protocol/lib"
Expand Down Expand Up @@ -46,6 +47,7 @@ func TestUpdateMarketPrices_Valid(t *testing.T) {
constants.MarketId0: constants.FiveBillion, // no change
constants.MarketId1: constants.ThreeBillion, // no change
constants.MarketId2: constants.FiveBillion, // no change
constants.MarketId3: constants.FiveBillion, // no change
},
},
"Multiple updates": {
Expand All @@ -55,6 +57,7 @@ func TestUpdateMarketPrices_Valid(t *testing.T) {
constants.MarketId0: constants.Price5,
constants.MarketId1: constants.Price6,
constants.MarketId2: constants.Price7,
constants.MarketId3: constants.Price4,
},
},
"Towards index price = true (current < update < index price)": {
Expand All @@ -77,6 +80,7 @@ func TestUpdateMarketPrices_Valid(t *testing.T) {
constants.MarketId0: price_5_005_000_000,
constants.MarketId1: constants.ThreeBillion, // no change
constants.MarketId2: constants.FiveBillion, // no change
constants.MarketId3: constants.FiveBillion, // no change
},
},
"Index price crossing = true (price increase), old_ticks > 1, new_ticks <= sqrt(old_ticks) = true": {
Expand All @@ -99,6 +103,7 @@ func TestUpdateMarketPrices_Valid(t *testing.T) {
constants.MarketId0: price_5_005_000_000,
constants.MarketId1: constants.ThreeBillion, // no change
constants.MarketId2: constants.FiveBillion, // no change
constants.MarketId3: constants.FiveBillion, // no change
},
},
"Index price crossing = true (price decrease), old_ticks > 1, new_ticks <= sqrt(old_ticks) = true": {
Expand All @@ -121,6 +126,7 @@ func TestUpdateMarketPrices_Valid(t *testing.T) {
constants.MarketId0: price_4_995_000_000,
constants.MarketId1: constants.ThreeBillion, // no change
constants.MarketId2: constants.FiveBillion, // no change
constants.MarketId3: constants.FiveBillion, // no change
},
},
"Index price crossing = true (price increase), old_ticks <= 1, new_ticks <= old_ticks = true": {
Expand All @@ -143,6 +149,7 @@ func TestUpdateMarketPrices_Valid(t *testing.T) {
constants.MarketId0: price_5_000_500_000,
constants.MarketId1: constants.ThreeBillion, // no change
constants.MarketId2: constants.FiveBillion, // no change
constants.MarketId3: constants.FiveBillion, // no change
},
},
"Index price crossing = true (price decrease), old_ticks <= 1, new_ticks <= old_ticks = true": {
Expand All @@ -165,6 +172,7 @@ func TestUpdateMarketPrices_Valid(t *testing.T) {
constants.MarketId0: price_4_999_500_000,
constants.MarketId1: constants.ThreeBillion, // no change
constants.MarketId2: constants.FiveBillion, // no change
constants.MarketId3: constants.FiveBillion, // no change
},
},
}
Expand Down

0 comments on commit 40eb007

Please sign in to comment.