From 3b8b27c597a93b968f17335f911d35b38e5cf1f6 Mon Sep 17 00:00:00 2001 From: Uday Patil Date: Thu, 20 Jun 2024 09:28:46 -0500 Subject: [PATCH] Add migration to unwind dex state (#1734) * Add migration to unwind dex state * Update message handler * Update tests --- .github/workflows/integration-test.yml | 5 +- aclmapping/dex/mappings_test.go | 9 +- app/app.go | 2 +- app/upgrades.go | 1 + tests/dex_test.go | 210 --------- x/dex/keeper/keeper.go | 2 +- .../msgserver/msg_server_cancel_orders.go | 52 +-- .../msg_server_cancel_orders_test.go | 171 +------ .../msg_server_contract_deposit_rent.go | 48 +- .../msg_server_contract_deposit_rent_test.go | 105 +---- .../msgserver/msg_server_place_orders.go | 81 +--- .../msgserver/msg_server_place_orders_test.go | 291 +----------- .../msgserver/msg_server_register_contract.go | 276 +---------- .../msg_server_register_contract_test.go | 434 +----------------- .../msgserver/msg_server_register_pairs.go | 55 +-- .../msg_server_register_pairs_test.go | 294 +----------- x/dex/keeper/msgserver/msg_server_test.go | 16 - .../msg_server_unregister_contract.go | 29 +- .../msg_server_unregister_contract_test.go | 74 +-- .../msg_server_unsuspend_contract.go | 37 +- .../msg_server_unsuspend_contract_test.go | 52 +-- .../msg_server_update_price_tick_size.go | 27 +- .../msg_server_update_price_tick_size_test.go | 218 +-------- .../msg_server_update_quantity_tick_size.go | 27 +- ...g_server_update_quantity_tick_size_test.go | 217 +-------- x/dex/migrations/v17_to_v18.go | 33 ++ x/dex/migrations/v17_to_v18_test.go | 62 +++ x/dex/module.go | 8 +- 28 files changed, 151 insertions(+), 2685 deletions(-) delete mode 100644 tests/dex_test.go delete mode 100644 x/dex/keeper/msgserver/msg_server_test.go create mode 100644 x/dex/migrations/v17_to_v18.go create mode 100644 x/dex/migrations/v17_to_v18_test.go diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml index a878de5565..406742264b 100644 --- a/.github/workflows/integration-test.yml +++ b/.github/workflows/integration-test.yml @@ -32,11 +32,8 @@ jobs: matrix: test: [ { - name: "Dex & Wasm Module", + name: "Wasm Module", scripts: [ - "docker exec sei-node-0 integration_test/contracts/deploy_dex_contract.sh mars", - "python3 integration_test/scripts/runner.py integration_test/dex_module/place_order_test.yaml", - "python3 integration_test/scripts/runner.py integration_test/dex_module/cancel_order_test.yaml", "docker exec sei-node-0 integration_test/contracts/deploy_timelocked_token_contract.sh", "python3 integration_test/scripts/runner.py integration_test/wasm_module/timelocked_token_delegation_test.yaml", "python3 integration_test/scripts/runner.py integration_test/wasm_module/timelocked_token_admin_test.yaml", diff --git a/aclmapping/dex/mappings_test.go b/aclmapping/dex/mappings_test.go index 68634a319d..5e189ac8d1 100644 --- a/aclmapping/dex/mappings_test.go +++ b/aclmapping/dex/mappings_test.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" sdkacltypes "github.com/cosmos/cosmos-sdk/types/accesscontrol" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" acltypes "github.com/cosmos/cosmos-sdk/x/accesscontrol/types" "github.com/k0kubun/pp/v3" dexacl "github.com/sei-protocol/sei-chain/aclmapping/dex" @@ -135,13 +136,13 @@ func (suite *KeeperTestSuite) TestMsgPlaceOrder() { { name: "default place order", msg: suite.msgPlaceOrders, - expectedError: nil, + expectedError: sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated"), dynamicDep: true, }, { name: "dont check synchronous", msg: suite.msgPlaceOrders, - expectedError: nil, + expectedError: sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated"), dynamicDep: false, }, } @@ -191,13 +192,13 @@ func (suite *KeeperTestSuite) TestMsgCancelOrder() { { name: "default cancel order", msg: suite.msgCancelOrders, - expectedError: nil, + expectedError: sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated"), dynamicDep: true, }, { name: "dont check synchronous", msg: suite.msgCancelOrders, - expectedError: nil, + expectedError: sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated"), dynamicDep: false, }, } diff --git a/app/app.go b/app/app.go index 8b3488093d..e65a1038fe 100644 --- a/app/app.go +++ b/app/app.go @@ -234,7 +234,7 @@ var ( oracletypes.ModuleName: nil, wasm.ModuleName: {authtypes.Burner}, evmtypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - dexmoduletypes.ModuleName: nil, + dexmoduletypes.ModuleName: {authtypes.Burner}, tokenfactorytypes.ModuleName: {authtypes.Minter, authtypes.Burner}, // this line is used by starport scaffolding # stargate/app/maccPerms } diff --git a/app/upgrades.go b/app/upgrades.go index ad6b4798cc..57dd776e21 100644 --- a/app/upgrades.go +++ b/app/upgrades.go @@ -102,6 +102,7 @@ var upgradesList = []string{ "v5.5.1", "v5.5.2", "v5.5.5", + "v5.6.0", } // if there is an override list, use that instead, for integration tests diff --git a/tests/dex_test.go b/tests/dex_test.go deleted file mode 100644 index e564a2395d..0000000000 --- a/tests/dex_test.go +++ /dev/null @@ -1,210 +0,0 @@ -package tests - -import ( - "fmt" - "testing" - - "github.com/cosmos/cosmos-sdk/x/auth/signing" - "github.com/sei-protocol/sei-chain/testutil/processblock" - "github.com/sei-protocol/sei-chain/testutil/processblock/verify" -) - -func TestPlaceOrders(t *testing.T) { - app := processblock.NewTestApp() - p := processblock.DexPreset(app, 3, 2) - p.DoRegisterMarkets(app) - - for _, testCase := range []TestCase{ - { - description: "send a single market buy without counterparty on orderbook", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[0], 10000, p.AllDexMarkets[0].LongMarketOrder(p.SignableAccounts[0], "11", "2")), - }, - verifier: []verify.Verifier{ - verify.DexOrders, - verify.Balance, - }, - expectedCodes: []uint32{0}, - }, - { - description: "send a single market sell without counterparty on orderbook", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[0], 10000, p.AllDexMarkets[0].ShortMarketOrder(p.SignableAccounts[0], "10.5", "4")), - }, - verifier: []verify.Verifier{ - verify.DexOrders, - verify.Balance, - }, - expectedCodes: []uint32{0}, - }, - { - description: "send a single buy limit order", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[0], 10000, p.AllDexMarkets[0].LongLimitOrder(p.SignableAccounts[0], "10.5", "5")), - }, - verifier: []verify.Verifier{ - verify.DexOrders, - verify.Balance, - }, - expectedCodes: []uint32{0}, - }, - { - description: "send a single sell limit order", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[1], 10000, p.AllDexMarkets[0].ShortLimitOrder(p.SignableAccounts[1], "11", "3")), - }, - verifier: []verify.Verifier{ - verify.DexOrders, - verify.Balance, - }, - expectedCodes: []uint32{0}, - }, - { - description: "send a single market buy without exhausting the orderbook", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[2], 10000, p.AllDexMarkets[0].LongMarketOrder(p.SignableAccounts[2], "11", "2")), - }, - verifier: []verify.Verifier{ - verify.DexOrders, - verify.Balance, - }, - expectedCodes: []uint32{0}, - }, - { - description: "send a single market sell without exhausting the orderbook", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[2], 10000, p.AllDexMarkets[0].ShortMarketOrder(p.SignableAccounts[2], "10.5", "4")), - }, - verifier: []verify.Verifier{ - verify.DexOrders, - verify.Balance, - }, - expectedCodes: []uint32{0}, - }, - { - description: "send a single market buy exhausting the orderbook", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[2], 10000, p.AllDexMarkets[0].LongMarketOrder(p.SignableAccounts[2], "12", "2")), - }, - verifier: []verify.Verifier{ - verify.DexOrders, - verify.Balance, - }, - expectedCodes: []uint32{0}, - }, - { - description: "send a single market sell exhausting the orderbook", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[2], 10000, p.AllDexMarkets[0].ShortMarketOrder(p.SignableAccounts[2], "10", "2")), - }, - verifier: []verify.Verifier{ - verify.DexOrders, - verify.Balance, - }, - expectedCodes: []uint32{0}, - }, - } { - testCase.run(t, app) - } -} - -func TestPlaceImposterOrders(t *testing.T) { - app := processblock.NewTestApp() - p := processblock.DexPreset(app, 3, 2) - p.DoRegisterMarkets(app) - - for _, testCase := range []TestCase{ - { - description: "send an order for someone else", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[0], 10000, p.AllDexMarkets[0].LongMarketOrder(p.SignableAccounts[1], "11", "2")), - }, - verifier: []verify.Verifier{}, - expectedCodes: []uint32{8}, - }, - } { - testCase.run(t, app) - } -} - -func TestCancelOrders(t *testing.T) { - app := processblock.NewTestApp() - p := processblock.DexPreset(app, 3, 2) - p.DoRegisterMarkets(app) - - for _, testCase := range []TestCase{ - { - description: "place a limit order", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[0], 10000, p.AllDexMarkets[0].LongLimitOrder(p.SignableAccounts[0], "11", "2")), - }, - verifier: []verify.Verifier{ - verify.DexOrders, - }, - expectedCodes: []uint32{0}, - }, - { - description: "cancel the previosuly placed limit order", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[0], 10000, p.AllDexMarkets[0].CancelLongOrder(p.SignableAccounts[0], "11", 0)), - }, - verifier: []verify.Verifier{ - verify.DexOrders, - }, - expectedCodes: []uint32{0}, - }, - { - description: "place two more limit orders at the same price", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[0], 10000, p.AllDexMarkets[0].LongLimitOrder(p.SignableAccounts[0], "11", "2")), - app.Sign(p.SignableAccounts[1], 10000, p.AllDexMarkets[0].LongLimitOrder(p.SignableAccounts[1], "11", "1")), - }, - verifier: []verify.Verifier{ - verify.DexOrders, - }, - expectedCodes: []uint32{0, 0}, - }, - { - description: "cancel one of the orders on the same price", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[1], 10000, p.AllDexMarkets[0].CancelLongOrder(p.SignableAccounts[1], "11", 2)), - }, - verifier: []verify.Verifier{ - verify.DexOrders, - }, - expectedCodes: []uint32{0}, - }, - { - description: "place two more limit orders at different prices", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[0], 10000, p.AllDexMarkets[0].LongLimitOrder(p.SignableAccounts[0], "11", "2")), - app.Sign(p.SignableAccounts[1], 10000, p.AllDexMarkets[0].LongLimitOrder(p.SignableAccounts[1], "12", "1")), - }, - verifier: []verify.Verifier{ - verify.DexOrders, - }, - expectedCodes: []uint32{0, 0}, - }, - { - description: "cancel one of the orders", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[1], 10000, p.AllDexMarkets[0].CancelLongOrder(p.SignableAccounts[1], "12", 4)), - }, - verifier: []verify.Verifier{ - verify.DexOrders, - }, - expectedCodes: []uint32{0}, - }, - { - description: "cancel nonexistent order", - input: []signing.Tx{ - app.Sign(p.SignableAccounts[1], 10000, p.AllDexMarkets[0].CancelLongOrder(p.SignableAccounts[1], "11", 5)), - }, - verifier: []verify.Verifier{}, // no change to order book - expectedCodes: []uint32{0}, // tx itself would succeed - }, - } { - fmt.Println(testCase.description) - testCase.run(t, app) - } -} diff --git a/x/dex/keeper/keeper.go b/x/dex/keeper/keeper.go index b571a47e7d..f89bf7ded1 100644 --- a/x/dex/keeper/keeper.go +++ b/x/dex/keeper/keeper.go @@ -73,6 +73,6 @@ func (k *Keeper) SetWasmKeeper(wasmKeeper *wasm.Keeper) { } func (k Keeper) CreateModuleAccount(ctx sdk.Context) { - moduleAcc := authtypes.NewEmptyModuleAccount(types.ModuleName) + moduleAcc := authtypes.NewEmptyModuleAccount(types.ModuleName, authtypes.Burner) k.AccountKeeper.SetModuleAccount(ctx, moduleAcc) } diff --git a/x/dex/keeper/msgserver/msg_server_cancel_orders.go b/x/dex/keeper/msgserver/msg_server_cancel_orders.go index 0381e2eaef..8ca3a4a1db 100644 --- a/x/dex/keeper/msgserver/msg_server_cancel_orders.go +++ b/x/dex/keeper/msgserver/msg_server_cancel_orders.go @@ -2,59 +2,11 @@ package msgserver import ( "context" - "errors" - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/sei-protocol/sei-chain/x/dex/types" - "github.com/sei-protocol/sei-chain/x/dex/utils" ) func (k msgServer) CancelOrders(goCtx context.Context, msg *types.MsgCancelOrders) (*types.MsgCancelOrdersResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := msg.ValidateBasic(); err != nil { - ctx.Logger().Error(fmt.Sprintf("request invalid: %s", err)) - return nil, err - } - - events := []sdk.Event{} - for _, cancellation := range msg.GetCancellations() { - var allocation *types.Allocation - var found bool - if cancellation.PositionDirection == types.PositionDirection_LONG { - allocation, found = k.GetLongAllocationForOrderID(ctx, msg.ContractAddr, cancellation.PriceDenom, cancellation.AssetDenom, cancellation.Price, cancellation.Id) - } else { - allocation, found = k.GetShortAllocationForOrderID(ctx, msg.ContractAddr, cancellation.PriceDenom, cancellation.AssetDenom, cancellation.Price, cancellation.Id) - } - if !found { - continue - } - if allocation.Account != msg.Creator { - return nil, errors.New("cannot cancel orders created by others") - } - pair := types.Pair{PriceDenom: cancellation.PriceDenom, AssetDenom: cancellation.AssetDenom} - pairBlockCancellations := utils.GetMemState(ctx.Context()).GetBlockCancels(ctx, types.ContractAddress(msg.GetContractAddr()), pair) - if !pairBlockCancellations.Has(cancellation) { - // only cancel if it's not cancelled in a previous tx in the same block - cancel := types.Cancellation{ - Id: cancellation.Id, - Initiator: types.CancellationInitiator_USER, - Creator: msg.Creator, - ContractAddr: msg.ContractAddr, - Price: cancellation.Price, - AssetDenom: cancellation.AssetDenom, - PriceDenom: cancellation.PriceDenom, - PositionDirection: cancellation.PositionDirection, - } - pairBlockCancellations.Add(&cancel) - events = append(events, sdk.NewEvent( - types.EventTypeCancelOrder, - sdk.NewAttribute(types.AttributeKeyCancellationID, fmt.Sprint(cancellation.Id)), - )) - } - } - ctx.EventManager().EmitEvents(events) - utils.GetMemState(ctx.Context()).SetDownstreamsToProcess(ctx, msg.ContractAddr, k.GetContractWithoutGasCharge) - return &types.MsgCancelOrdersResponse{}, nil + return nil, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated") } diff --git a/x/dex/keeper/msgserver/msg_server_cancel_orders_test.go b/x/dex/keeper/msgserver/msg_server_cancel_orders_test.go index 1735fcfffa..88f88473c2 100644 --- a/x/dex/keeper/msgserver/msg_server_cancel_orders_test.go +++ b/x/dex/keeper/msgserver/msg_server_cancel_orders_test.go @@ -4,32 +4,16 @@ import ( "testing" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" keepertest "github.com/sei-protocol/sei-chain/testutil/keeper" "github.com/sei-protocol/sei-chain/x/dex/keeper/msgserver" "github.com/sei-protocol/sei-chain/x/dex/types" - dexutils "github.com/sei-protocol/sei-chain/x/dex/utils" "github.com/stretchr/testify/require" ) func TestCancelOrder(t *testing.T) { // store a long limit order to the orderbook keeper, ctx := keepertest.DexKeeper(t) - keeper.SetLongBook(ctx, keepertest.TestContract, types.LongBook{ - Price: sdk.OneDec(), - Entry: &types.OrderEntry{ - Price: sdk.OneDec(), - Quantity: sdk.MustNewDecFromStr("2"), - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - Allocations: []*types.Allocation{ - { - Account: keepertest.TestAccount, - OrderId: 1, - Quantity: sdk.MustNewDecFromStr("2"), - }, - }, - }, - }) // cancel order msg := &types.MsgCancelOrders{ @@ -45,159 +29,8 @@ func TestCancelOrder(t *testing.T) { }, }, } - keeper.AddRegisteredPair(ctx, keepertest.TestContract, keepertest.TestPair) - keeper.SetPriceTickSizeForPair(ctx, TestContract, keepertest.TestPair, *keepertest.TestPair.PriceTicksize) - keeper.SetQuantityTickSizeForPair(ctx, TestContract, keepertest.TestPair, *keepertest.TestPair.QuantityTicksize) - wctx := sdk.WrapSDKContext(ctx) - server := msgserver.NewMsgServerImpl(*keeper) - _, err := server.CancelOrders(wctx, msg) - - pairBlockCancellations := dexutils.GetMemState(ctx.Context()).GetBlockCancels(ctx, keepertest.TestContract, keepertest.TestPair) - require.Nil(t, err) - require.Equal(t, 1, len(pairBlockCancellations.Get())) - require.Equal(t, uint64(1), pairBlockCancellations.Get()[0].Id) - require.Equal(t, sdk.OneDec(), pairBlockCancellations.Get()[0].Price) - require.Equal(t, "atom", pairBlockCancellations.Get()[0].AssetDenom) - require.Equal(t, "usdc", pairBlockCancellations.Get()[0].PriceDenom) - require.Equal(t, keepertest.TestAccount, pairBlockCancellations.Get()[0].Creator) - require.Equal(t, keepertest.TestContract, pairBlockCancellations.Get()[0].ContractAddr) -} - -func TestInvalidCancels(t *testing.T) { - // nil cancel price - keeper, ctx := keepertest.DexKeeper(t) - msg := &types.MsgCancelOrders{ - Creator: keepertest.TestAccount, - ContractAddr: keepertest.TestContract, - Cancellations: []*types.Cancellation{ - { - PositionDirection: types.PositionDirection_LONG, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - Id: 1, - }, - }, - } - keeper.AddRegisteredPair(ctx, keepertest.TestContract, keepertest.TestPair) - keeper.SetPriceTickSizeForPair(ctx, TestContract, keepertest.TestPair, *keepertest.TestPair.PriceTicksize) - keeper.SetQuantityTickSizeForPair(ctx, TestContract, keepertest.TestPair, *keepertest.TestPair.QuantityTicksize) wctx := sdk.WrapSDKContext(ctx) server := msgserver.NewMsgServerImpl(*keeper) _, err := server.CancelOrders(wctx, msg) - require.NotNil(t, err) - - // nil creator - msg = &types.MsgCancelOrders{ - ContractAddr: keepertest.TestContract, - Cancellations: []*types.Cancellation{ - { - PositionDirection: types.PositionDirection_LONG, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - Id: 1, - Price: sdk.OneDec(), - }, - }, - } - _, err = server.CancelOrders(wctx, msg) - require.NotNil(t, err) - - // invalid creator address - msg = &types.MsgCancelOrders{ - Creator: "invalid", - ContractAddr: keepertest.TestContract, - Cancellations: []*types.Cancellation{ - { - PositionDirection: types.PositionDirection_LONG, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - Id: 1, - Price: sdk.OneDec(), - }, - }, - } - _, err = server.CancelOrders(wctx, msg) - require.NotNil(t, err) - - // nil contract address - msg = &types.MsgCancelOrders{ - Creator: keepertest.TestAccount, - Cancellations: []*types.Cancellation{ - { - Price: sdk.OneDec(), - PositionDirection: types.PositionDirection_LONG, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - Id: 1, - }, - }, - } - _, err = server.CancelOrders(wctx, msg) - require.NotNil(t, err) - - // invalid contract address - msg = &types.MsgCancelOrders{ - Creator: keepertest.TestAccount, - Cancellations: []*types.Cancellation{ - { - Price: sdk.OneDec(), - PositionDirection: types.PositionDirection_LONG, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - Id: 1, - }, - }, - ContractAddr: "invalid", - } - _, err = server.CancelOrders(wctx, msg) - require.NotNil(t, err) - - // nil price denom - msg = &types.MsgCancelOrders{ - Creator: keepertest.TestAccount, - ContractAddr: keepertest.TestContract, - Cancellations: []*types.Cancellation{ - { - Price: sdk.OneDec(), - PositionDirection: types.PositionDirection_LONG, - AssetDenom: keepertest.TestAssetDenom, - Id: 1, - }, - }, - } - _, err = server.CancelOrders(wctx, msg) - require.NotNil(t, err) - - // nil asset denom - msg = &types.MsgCancelOrders{ - Creator: keepertest.TestAccount, - ContractAddr: keepertest.TestContract, - Cancellations: []*types.Cancellation{ - { - Price: sdk.OneDec(), - PositionDirection: types.PositionDirection_LONG, - PriceDenom: keepertest.TestPriceDenom, - Id: 1, - }, - }, - } - _, err = server.CancelOrders(wctx, msg) - require.NotNil(t, err) - - // negative price - msg = &types.MsgCancelOrders{ - Creator: keepertest.TestAccount, - ContractAddr: keepertest.TestContract, - Cancellations: []*types.Cancellation{ - { - Price: sdk.OneDec().Neg(), - PositionDirection: types.PositionDirection_LONG, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - Id: 1, - }, - }, - } - _, err = server.CancelOrders(wctx, msg) - require.NotNil(t, err) + require.EqualError(t, err, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated").Error()) } diff --git a/x/dex/keeper/msgserver/msg_server_contract_deposit_rent.go b/x/dex/keeper/msgserver/msg_server_contract_deposit_rent.go index 7e83ec045d..d1a4cf3299 100644 --- a/x/dex/keeper/msgserver/msg_server_contract_deposit_rent.go +++ b/x/dex/keeper/msgserver/msg_server_contract_deposit_rent.go @@ -2,55 +2,11 @@ package msgserver import ( "context" - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" - appparams "github.com/sei-protocol/sei-chain/app/params" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/sei-protocol/sei-chain/x/dex/types" ) func (k msgServer) ContractDepositRent(goCtx context.Context, msg *types.MsgContractDepositRent) (*types.MsgContractDepositRentResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := msg.ValidateBasic(); err != nil { - ctx.Logger().Error(fmt.Sprintf("request invalid: %s", err)) - return nil, err - } - - // first check if the deposit itself exceeds the limit - if err := k.ValidateRentBalance(ctx, msg.GetAmount()); err != nil { - return nil, err - } - - contract, err := k.GetContract(ctx, msg.ContractAddr) - if err != nil { - return nil, err - } - - // check if the balance post deposit exceeds the limit. - // not checking the sum because it might overflow. - if k.maxAllowedRentBalance()-msg.GetAmount() < contract.RentBalance { - return nil, fmt.Errorf("rent balance %d will exceed the limit of %d after depositing %d", contract.RentBalance, k.maxAllowedRentBalance(), msg.GetAmount()) - } - - // deposit - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - if err := k.BankKeeper.SendCoins(ctx, senderAddr, k.AccountKeeper.GetModuleAddress(types.ModuleName), sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewIntFromUint64(msg.Amount)))); err != nil { - return nil, err - } - - contract.RentBalance += msg.Amount - if err := k.SetContract(ctx, &contract); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeDepositRent, - sdk.NewAttribute(types.AttributeKeyContractAddress, msg.ContractAddr), - sdk.NewAttribute(types.AttributeKeyRentBalance, fmt.Sprint(contract.RentBalance)), - )) - return &types.MsgContractDepositRentResponse{}, nil + return nil, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated") } diff --git a/x/dex/keeper/msgserver/msg_server_contract_deposit_rent_test.go b/x/dex/keeper/msgserver/msg_server_contract_deposit_rent_test.go index 06d70b21c4..894ba170ee 100644 --- a/x/dex/keeper/msgserver/msg_server_contract_deposit_rent_test.go +++ b/x/dex/keeper/msgserver/msg_server_contract_deposit_rent_test.go @@ -2,132 +2,33 @@ package msgserver_test import ( "context" - "io/ioutil" - "math" "testing" "time" - wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" - wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" keepertest "github.com/sei-protocol/sei-chain/testutil/keeper" "github.com/sei-protocol/sei-chain/x/dex" dexcache "github.com/sei-protocol/sei-chain/x/dex/cache" - "github.com/sei-protocol/sei-chain/x/dex/keeper/msgserver" "github.com/sei-protocol/sei-chain/x/dex/types" dexutils "github.com/sei-protocol/sei-chain/x/dex/utils" - minttypes "github.com/sei-protocol/sei-chain/x/mint/types" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" ) -const ( - GOOD_CONTRACT_INSTANTIATE = `{"whitelist": ["sei1h9yjz89tl0dl6zu65dpxcqnxfhq60wxx8s5kag"], - "use_whitelist":false,"admin":"sei1h9yjz89tl0dl6zu65dpxcqnxfhq60wxx8s5kag", - "limit_order_fee":{"decimal":"0.0001","negative":false}, - "market_order_fee":{"decimal":"0.0001","negative":false}, - "liquidation_order_fee":{"decimal":"0.0001","negative":false}, - "margin_ratio":{"decimal":"0.0625","negative":false}, - "max_leverage":{"decimal":"4","negative":false}, - "default_base":"USDC", - "native_token":"USDC","denoms": ["SEI","ATOM","USDC","SOL","ETH","OSMO","AVAX","BTC"], - "full_denom_mapping": [["usei","SEI","0.000001"],["uatom","ATOM","0.000001"],["uusdc","USDC","0.000001"]], - "funding_payment_lookback":3600,"spot_market_contract":"sei1h9yjz89tl0dl6zu65dpxcqnxfhq60wxx8s5kag", - "supported_collateral_denoms": ["USDC"], - "supported_multicollateral_denoms": ["ATOM"], - "oracle_denom_mapping": [["usei","SEI","1"],["uatom","ATOM","1"],["uusdc","USDC","1"],["ueth","ETH","1"]], - "multicollateral_whitelist": ["sei1h9yjz89tl0dl6zu65dpxcqnxfhq60wxx8s5kag"], - "multicollateral_whitelist_enable": true, - "funding_payment_pairs": [["USDC","ETH"]], - "default_margin_ratios":{ - "initial":"0.3", - "partial":"0.25", - "maintenance":"0.06" - }}` -) - func TestDepositRent(t *testing.T) { testApp := keepertest.TestApp() ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - wctx := sdk.WrapSDKContext(ctx) dexkeeper := testApp.DexKeeper - testAccount, _ := sdk.AccAddressFromBech32("sei1h9yjz89tl0dl6zu65dpxcqnxfhq60wxx8s5kag") depositAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, depositAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddr, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - server := msgserver.NewMsgServerImpl(dexkeeper) - contract := types.ContractInfoV2{ - CodeId: codeId, - ContractAddr: contractAddr.String(), - Creator: testAccount.String(), - RentBalance: types.DefaultParams().MinRentDeposit, - } - _, err = server.RegisterContract(wctx, &types.MsgRegisterContract{ - Creator: testAccount.String(), - Contract: &contract, - }) - require.NoError(t, err) - _, err = dexkeeper.GetContract(ctx, TestContractA) - require.NoError(t, err) - balance := dexkeeper.BankKeeper.GetBalance(ctx, testAccount, "usei") - require.Equal(t, int64(89900000), balance.Amount.Int64()) handler := dex.NewHandler(dexkeeper) - _, err = handler(ctx, &types.MsgContractDepositRent{ + _, err := handler(ctx, &types.MsgContractDepositRent{ Sender: depositAccount.String(), ContractAddr: TestContractA, Amount: types.DefaultParams().MinRentDeposit, }) - require.NoError(t, err) - _, err = dexkeeper.GetContract(ctx, TestContractA) - require.NoError(t, err) - balance = dexkeeper.BankKeeper.GetBalance(ctx, testAccount, "usei") - require.Equal(t, int64(89900000), balance.Amount.Int64()) - balance = dexkeeper.BankKeeper.GetBalance(ctx, depositAccount, "usei") - require.Equal(t, int64(90000000), balance.Amount.Int64()) - - // deposit exceeds limit - _, err = handler(ctx, &types.MsgContractDepositRent{ - Sender: testAccount.String(), - ContractAddr: TestContractA, - Amount: math.MaxUint64, - }) - require.Error(t, err) - // deposit + prev balance exceeds limit - _, err = handler(ctx, &types.MsgContractDepositRent{ - Sender: testAccount.String(), - ContractAddr: TestContractA, - Amount: math.MaxUint64/140000000 - 500000, - }) - require.Error(t, err) - // deposit + prev balance overflows - _, err = handler(ctx, &types.MsgContractDepositRent{ - Sender: testAccount.String(), - ContractAddr: TestContractA, - Amount: math.MaxUint64 - 500000, - }) - require.Error(t, err) + require.EqualError(t, err, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated").Error()) } diff --git a/x/dex/keeper/msgserver/msg_server_place_orders.go b/x/dex/keeper/msgserver/msg_server_place_orders.go index 32f478ec1d..ae7a707001 100644 --- a/x/dex/keeper/msgserver/msg_server_place_orders.go +++ b/x/dex/keeper/msgserver/msg_server_place_orders.go @@ -2,90 +2,11 @@ package msgserver import ( "context" - "errors" - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/sei-protocol/sei-chain/x/dex/types" - "github.com/sei-protocol/sei-chain/x/dex/utils" ) -func (k msgServer) transferFunds(goCtx context.Context, msg *types.MsgPlaceOrders) error { - if len(msg.Funds) == 0 { - return nil - } - - ctx := sdk.UnwrapSDKContext(goCtx) - contractAddr := sdk.MustAccAddressFromBech32(msg.ContractAddr) - if err := k.BankKeeper.IsSendEnabledCoins(ctx, msg.Funds...); err != nil { - return err - } - if k.BankKeeper.BlockedAddr(contractAddr) { - return sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", contractAddr.String()) - } - - sender := sdk.MustAccAddressFromBech32(msg.Creator) - for _, fund := range msg.Funds { - if fund.Amount.IsNil() || fund.IsNegative() { - return errors.New("fund deposits cannot be nil or negative") - } - utils.GetMemState(ctx.Context()).GetDepositInfo(ctx, types.ContractAddress(msg.GetContractAddr())).Add(&types.DepositInfoEntry{ - Creator: msg.Creator, - Denom: fund.Denom, - Amount: sdk.NewDec(fund.Amount.Int64()), - }) - } - if err := k.BankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, msg.Funds); err != nil { - return fmt.Errorf("error sending coins to contract: %s", err) - } - return nil -} - func (k msgServer) PlaceOrders(goCtx context.Context, msg *types.MsgPlaceOrders) (*types.MsgPlaceOrdersResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := msg.ValidateBasic(); err != nil { - ctx.Logger().Error(fmt.Sprintf("request invalid: %s", err)) - return nil, err - } - - if err := k.transferFunds(goCtx, msg); err != nil { - return nil, err - } - events := []sdk.Event{} - nextID := k.GetNextOrderID(ctx, msg.ContractAddr) - idsInResp := []uint64{} - maxOrderPerPrice := k.GetMaxOrderPerPrice(ctx) - for _, order := range msg.GetOrders() { - if k.GetOrderCountState(ctx, msg.GetContractAddr(), order.PriceDenom, order.AssetDenom, order.PositionDirection, order.Price) >= maxOrderPerPrice { - return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "order book already has more than %d orders for %s-%s-%s %s at %s", maxOrderPerPrice, msg.GetContractAddr(), order.PriceDenom, order.AssetDenom, order.PositionDirection, order.Price) - } - priceTicksize, found := k.Keeper.GetPriceTickSizeForPair(ctx, msg.GetContractAddr(), types.Pair{PriceDenom: order.PriceDenom, AssetDenom: order.AssetDenom}) - if !found { - return nil, sdkerrors.Wrapf(sdkerrors.ErrKeyNotFound, "the pair {price:%s,asset:%s} has no price ticksize configured", order.PriceDenom, order.AssetDenom) - } - quantityTicksize, found := k.Keeper.GetQuantityTickSizeForPair(ctx, msg.GetContractAddr(), types.Pair{PriceDenom: order.PriceDenom, AssetDenom: order.AssetDenom}) - if !found { - return nil, sdkerrors.Wrapf(sdkerrors.ErrKeyNotFound, "the pair {price:%s,asset:%s} has no quantity ticksize configured", order.PriceDenom, order.AssetDenom) - } - pair := types.Pair{PriceDenom: order.PriceDenom, AssetDenom: order.AssetDenom, PriceTicksize: &priceTicksize, QuantityTicksize: &quantityTicksize} - order.Id = nextID - order.Account = msg.Creator - order.ContractAddr = msg.GetContractAddr() - utils.GetMemState(ctx.Context()).GetBlockOrders(ctx, types.ContractAddress(msg.GetContractAddr()), pair).Add(order) - idsInResp = append(idsInResp, nextID) - events = append(events, sdk.NewEvent( - types.EventTypePlaceOrder, - sdk.NewAttribute(types.AttributeKeyOrderID, fmt.Sprint(nextID)), - )) - nextID++ - } - k.SetNextOrderID(ctx, msg.ContractAddr, nextID) - ctx.EventManager().EmitEvents(events) - - utils.GetMemState(ctx.Context()).SetDownstreamsToProcess(ctx, msg.ContractAddr, k.GetContractWithoutGasCharge) - return &types.MsgPlaceOrdersResponse{ - OrderIds: idsInResp, - }, nil + return nil, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated") } diff --git a/x/dex/keeper/msgserver/msg_server_place_orders_test.go b/x/dex/keeper/msgserver/msg_server_place_orders_test.go index 2a999fa0e9..d14e3e5329 100644 --- a/x/dex/keeper/msgserver/msg_server_place_orders_test.go +++ b/x/dex/keeper/msgserver/msg_server_place_orders_test.go @@ -1,18 +1,14 @@ package msgserver_test import ( - "context" "testing" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" keepertest "github.com/sei-protocol/sei-chain/testutil/keeper" - dexcache "github.com/sei-protocol/sei-chain/x/dex/cache" "github.com/sei-protocol/sei-chain/x/dex/keeper/msgserver" "github.com/sei-protocol/sei-chain/x/dex/types" - dexutils "github.com/sei-protocol/sei-chain/x/dex/utils" - minttypes "github.com/sei-protocol/sei-chain/x/mint/types" "github.com/stretchr/testify/require" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" ) const ( @@ -46,291 +42,8 @@ func TestPlaceOrder(t *testing.T) { }, } keeper, ctx := keepertest.DexKeeper(t) - keeper.AddRegisteredPair(ctx, TestContract, keepertest.TestPair) - keeper.SetPriceTickSizeForPair(ctx, TestContract, keepertest.TestPair, *keepertest.TestPair.PriceTicksize) - keeper.SetQuantityTickSizeForPair(ctx, TestContract, keepertest.TestPair, *keepertest.TestPair.QuantityTicksize) - wctx := sdk.WrapSDKContext(ctx) - server := msgserver.NewMsgServerImpl(*keeper) - res, err := server.PlaceOrders(wctx, msg) - require.Nil(t, err) - require.Equal(t, 2, len(res.OrderIds)) - require.Equal(t, uint64(0), res.OrderIds[0]) - require.Equal(t, uint64(1), res.OrderIds[1]) - // Ensure that contract addr and account is set in the order - require.Equal(t, msg.Orders[0].ContractAddr, TestContract) - require.Equal(t, msg.Orders[0].Account, TestCreator) -} - -func TestPlaceOrderWithDeposit(t *testing.T) { - msg := &types.MsgPlaceOrders{ - Creator: TestCreator, - ContractAddr: TestContract, - Orders: []*types.Order{ - { - Price: sdk.MustNewDecFromStr("10"), - Quantity: sdk.MustNewDecFromStr("10"), - Data: "", - PositionDirection: types.PositionDirection_LONG, - OrderType: types.OrderType_LIMIT, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - }, - }, - Funds: []sdk.Coin{ - { - Denom: "usei", - Amount: sdk.NewInt(10), - }, - }, - } - testApp := keepertest.TestApp() - ctx := testApp.BaseApp.NewContext(false, tmproto.Header{}) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - bankkeeper := testApp.BankKeeper - testAccount, _ := sdk.AccAddressFromBech32(TestCreator) - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(10))) - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - keeper := testApp.DexKeeper - keeper.CreateModuleAccount(ctx) - keeper.AddRegisteredPair(ctx, TestContract, keepertest.TestPair) - keeper.SetPriceTickSizeForPair(ctx, TestContract, keepertest.TestPair, *keepertest.TestPair.PriceTicksize) - keeper.SetQuantityTickSizeForPair(ctx, TestContract, keepertest.TestPair, *keepertest.TestPair.QuantityTicksize) - wctx := sdk.WrapSDKContext(ctx) - server := msgserver.NewMsgServerImpl(keeper) - res, err := server.PlaceOrders(wctx, msg) - require.Nil(t, err) - require.Equal(t, 1, len(res.OrderIds)) - require.Equal(t, uint64(0), res.OrderIds[0]) - senderBalance := bankkeeper.GetBalance(ctx, testAccount, "usei") - require.Equal(t, sdk.ZeroInt(), senderBalance.Amount) - - // insufficient fund - res, err = server.PlaceOrders(wctx, msg) - require.NotNil(t, err) - senderBalance = bankkeeper.GetBalance(ctx, testAccount, "usei") - require.Equal(t, sdk.ZeroInt(), senderBalance.Amount) -} - -func TestPlaceInvalidOrder(t *testing.T) { - keeper, ctx := keepertest.DexKeeper(t) - keeper.AddRegisteredPair(ctx, TestContract, keepertest.TestPair) - keeper.SetPriceTickSizeForPair(ctx, TestContract, keepertest.TestPair, *keepertest.TestPair.PriceTicksize) - keeper.SetQuantityTickSizeForPair(ctx, TestContract, keepertest.TestPair, *keepertest.TestPair.QuantityTicksize) - wctx := sdk.WrapSDKContext(ctx) - - // Empty quantity - msg := &types.MsgPlaceOrders{ - Creator: TestCreator, - ContractAddr: TestContract, - Orders: []*types.Order{ - { - Price: sdk.MustNewDecFromStr("10"), - Quantity: sdk.Dec{}, - Data: "", - PositionDirection: types.PositionDirection_LONG, - OrderType: types.OrderType_LIMIT, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - }, - }, - } - server := msgserver.NewMsgServerImpl(*keeper) - _, err := server.PlaceOrders(wctx, msg) - require.NotNil(t, err) - - // Empty price - msg = &types.MsgPlaceOrders{ - Creator: TestCreator, - ContractAddr: TestContract, - Orders: []*types.Order{ - { - Price: sdk.Dec{}, - Quantity: sdk.MustNewDecFromStr("10"), - Data: "", - PositionDirection: types.PositionDirection_LONG, - OrderType: types.OrderType_LIMIT, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - }, - }, - } - server = msgserver.NewMsgServerImpl(*keeper) - _, err = server.PlaceOrders(wctx, msg) - require.NotNil(t, err) - - // Negative quantity - msg = &types.MsgPlaceOrders{ - Creator: TestCreator, - ContractAddr: TestContract, - Orders: []*types.Order{ - { - Price: sdk.MustNewDecFromStr("10"), - Quantity: sdk.MustNewDecFromStr("-1"), - Data: "", - PositionDirection: types.PositionDirection_LONG, - OrderType: types.OrderType_LIMIT, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - }, - }, - } - server = msgserver.NewMsgServerImpl(*keeper) - _, err = server.PlaceOrders(wctx, msg) - require.NotNil(t, err) - - // Negative price - msg = &types.MsgPlaceOrders{ - Creator: TestCreator, - ContractAddr: TestContract, - Orders: []*types.Order{ - { - Price: sdk.MustNewDecFromStr("-1"), - Quantity: sdk.MustNewDecFromStr("10"), - Data: "", - PositionDirection: types.PositionDirection_LONG, - OrderType: types.OrderType_LIMIT, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - ContractAddr: TestContract, - Account: "testaccount", - }, - }, - } - server = msgserver.NewMsgServerImpl(*keeper) - _, err = server.PlaceOrders(wctx, msg) - require.NotNil(t, err) - - // Missing contract - msg = &types.MsgPlaceOrders{ - Creator: TestCreator, - ContractAddr: TestContract, - Orders: []*types.Order{ - { - Price: sdk.MustNewDecFromStr("-1"), - Quantity: sdk.MustNewDecFromStr("10"), - Data: "", - PositionDirection: types.PositionDirection_LONG, - OrderType: types.OrderType_LIMIT, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - }, - }, - } - server = msgserver.NewMsgServerImpl(*keeper) - _, err = server.PlaceOrders(wctx, msg) - require.NotNil(t, err) - - // Missing account - msg = &types.MsgPlaceOrders{ - Creator: TestCreator, - ContractAddr: TestContract, - Orders: []*types.Order{ - { - Price: sdk.MustNewDecFromStr("-1"), - Quantity: sdk.MustNewDecFromStr("10"), - Data: "", - PositionDirection: types.PositionDirection_LONG, - OrderType: types.OrderType_LIMIT, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - }, - }, - } - server = msgserver.NewMsgServerImpl(*keeper) - _, err = server.PlaceOrders(wctx, msg) - require.NotNil(t, err) - - // Nil Fund Amount - msg = &types.MsgPlaceOrders{ - Creator: TestCreator, - ContractAddr: TestContract, - Orders: []*types.Order{ - { - Price: sdk.MustNewDecFromStr("10"), - Quantity: sdk.MustNewDecFromStr("10"), - Data: "", - PositionDirection: types.PositionDirection_LONG, - OrderType: types.OrderType_LIMIT, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - }, - }, - Funds: sdk.Coins{ - sdk.Coin{ - Denom: "TEST", - }, - }, - } - server = msgserver.NewMsgServerImpl(*keeper) - _, err = server.PlaceOrders(wctx, msg) - require.NotNil(t, err) - - // Negative Fund Amount - msg = &types.MsgPlaceOrders{ - Creator: TestCreator, - ContractAddr: TestContract, - Orders: []*types.Order{ - { - Price: sdk.MustNewDecFromStr("10"), - Quantity: sdk.MustNewDecFromStr("10"), - Data: "", - PositionDirection: types.PositionDirection_LONG, - OrderType: types.OrderType_LIMIT, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - }, - }, - Funds: sdk.Coins{ - sdk.Coin{ - Denom: "TEST", - Amount: sdk.NewInt(-10), - }, - }, - } - server = msgserver.NewMsgServerImpl(*keeper) - _, err = server.PlaceOrders(wctx, msg) - require.NotNil(t, err) -} - -func TestPlaceNoOrder(t *testing.T) { - msg := &types.MsgPlaceOrders{ - Creator: TestCreator, - ContractAddr: TestContract, - Orders: []*types.Order{}, - } - keeper, ctx := keepertest.DexKeeper(t) - wctx := sdk.WrapSDKContext(ctx) - server := msgserver.NewMsgServerImpl(*keeper) - _, err := server.PlaceOrders(wctx, msg) - require.NotNil(t, err) -} - -func TestPlaceOrderExceedingLimit(t *testing.T) { - msg := &types.MsgPlaceOrders{ - Creator: TestCreator, - ContractAddr: TestContract, - Orders: []*types.Order{ - { - Price: sdk.MustNewDecFromStr("10"), - Quantity: sdk.MustNewDecFromStr("10"), - Data: "", - PositionDirection: types.PositionDirection_LONG, - OrderType: types.OrderType_LIMIT, - PriceDenom: keepertest.TestPriceDenom, - AssetDenom: keepertest.TestAssetDenom, - }, - }, - } - keeper, ctx := keepertest.DexKeeper(t) - params := keeper.GetParams(ctx) - params.MaxOrderPerPrice = 0 - keeper.SetParams(ctx, params) - keeper.AddRegisteredPair(ctx, TestContract, keepertest.TestPair) - keeper.SetPriceTickSizeForPair(ctx, TestContract, keepertest.TestPair, *keepertest.TestPair.PriceTicksize) - keeper.SetQuantityTickSizeForPair(ctx, TestContract, keepertest.TestPair, *keepertest.TestPair.QuantityTicksize) wctx := sdk.WrapSDKContext(ctx) server := msgserver.NewMsgServerImpl(*keeper) _, err := server.PlaceOrders(wctx, msg) - require.NotNil(t, err) + require.EqualError(t, err, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated").Error()) } diff --git a/x/dex/keeper/msgserver/msg_server_register_contract.go b/x/dex/keeper/msgserver/msg_server_register_contract.go index f1fb3c3895..77bec2bd47 100644 --- a/x/dex/keeper/msgserver/msg_server_register_contract.go +++ b/x/dex/keeper/msgserver/msg_server_register_contract.go @@ -2,285 +2,11 @@ package msgserver import ( "context" - "errors" - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - appparams "github.com/sei-protocol/sei-chain/app/params" - "github.com/sei-protocol/sei-chain/utils" - "github.com/sei-protocol/sei-chain/utils/datastructures" - "github.com/sei-protocol/sei-chain/x/dex/contract" "github.com/sei-protocol/sei-chain/x/dex/types" - dexutils "github.com/sei-protocol/sei-chain/x/dex/utils" ) func (k msgServer) RegisterContract(goCtx context.Context, msg *types.MsgRegisterContract) (*types.MsgRegisterContractResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := msg.ValidateBasic(); err != nil { - ctx.Logger().Error(fmt.Sprintf("request invalid: %s", err)) - return nil, err - } - - // Validation such that only the user who instantiated the contract can register contract - contractAddr, _ := sdk.AccAddressFromBech32(msg.Contract.ContractAddr) - contractInfo := k.Keeper.WasmKeeper.GetContractInfo(ctx, contractAddr) - - // TODO: Add wasm fixture to write unit tests to verify this behavior - if contractInfo.Creator != msg.Creator { - return nil, sdkerrors.ErrUnauthorized - } - - if err := k.ValidateSuspension(ctx, msg.GetContract().GetContractAddr()); err != nil { - ctx.Logger().Error("suspended contract") - return &types.MsgRegisterContractResponse{}, err - } - if err := k.ValidateRentBalance(ctx, msg.GetContract().GetRentBalance()); err != nil { - ctx.Logger().Error("invalid rent balance") - return &types.MsgRegisterContractResponse{}, err - } - if err := k.ValidateUniqueDependencies(msg); err != nil { - ctx.Logger().Error(fmt.Sprintf("dependencies of contract %s are not unique", msg.Contract.ContractAddr)) - return &types.MsgRegisterContractResponse{}, err - } - if err := k.RemoveExistingDependencies(ctx, msg); err != nil { - ctx.Logger().Error("failed to remove existing dependencies") - return &types.MsgRegisterContractResponse{}, err - } - if err := k.UpdateOldSiblings(ctx, msg); err != nil { - ctx.Logger().Error("failed to update old siblings") - return &types.MsgRegisterContractResponse{}, err - } - if err := k.UpdateNewDependencies(ctx, msg); err != nil { - ctx.Logger().Error("failed to update new dependencies") - return &types.MsgRegisterContractResponse{}, err - } - if err := k.HandleDepositOrRefund(ctx, msg); err != nil { - ctx.Logger().Error("failed to deposit/refund during contract registration") - return &types.MsgRegisterContractResponse{}, err - } - allContractInfo, err := k.SetNewContract(ctx, msg) - if err != nil { - ctx.Logger().Error("failed to set new contract") - return &types.MsgRegisterContractResponse{}, err - } - if _, err := contract.TopologicalSortContractInfo(allContractInfo); err != nil { - ctx.Logger().Error("contract caused a circular dependency") - return &types.MsgRegisterContractResponse{}, err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeRegisterContract, - sdk.NewAttribute(types.AttributeKeyContractAddress, msg.Contract.ContractAddr), - )) - - dexutils.GetMemState(ctx.Context()).ClearContractToDependencies(ctx) - return &types.MsgRegisterContractResponse{}, nil -} - -func (k msgServer) ValidateUniqueDependencies(msg *types.MsgRegisterContract) error { - if msg.Contract.Dependencies == nil { - return nil - } - dependencySet := datastructures.NewSyncSet(utils.Map( - msg.Contract.Dependencies, func(c *types.ContractDependencyInfo) string { return c.Dependency }, - )) - if dependencySet.Size() < len(msg.Contract.Dependencies) { - return errors.New("duplicated contract dependencies") - } - return nil -} - -func (k msgServer) RemoveExistingDependencies(ctx sdk.Context, msg *types.MsgRegisterContract) error { - contractInfo, err := k.GetContract(ctx, msg.Contract.ContractAddr) - if err != nil { - // contract is being added for the first time - ctx.Logger().Info(fmt.Sprintf("adding contract %s for the first time", msg.Contract.ContractAddr)) - return nil - } - if contractInfo.Dependencies == nil { - ctx.Logger().Info(fmt.Sprintf("existing contract %s has no dependency", msg.Contract.ContractAddr)) - return nil - } - // update old dependency's NumIncomingPaths - for _, oldDependency := range contractInfo.Dependencies { - dependencyInfo, err := k.GetContract(ctx, oldDependency.Dependency) - if err != nil { - if err == types.ErrContractNotExists { - // old dependency doesn't exist. Do nothing. - ctx.Logger().Info(fmt.Sprintf("existing contract %s old dependency %s does not exist", msg.Contract.ContractAddr, oldDependency.Dependency)) - continue - } - return err - } - dependencyInfo.NumIncomingDependencies-- - if err := k.SetContract(ctx, &dependencyInfo); err != nil { - return err - } - } - return nil -} - -func (k msgServer) UpdateOldSiblings(ctx sdk.Context, msg *types.MsgRegisterContract) error { - contractInfo, err := k.GetContract(ctx, msg.Contract.ContractAddr) - if err != nil { - if err == types.ErrContractNotExists { - return nil - } - return err - } - // update siblings for old dependencies - for _, oldDependency := range contractInfo.Dependencies { - elder := oldDependency.ImmediateElderSibling - younger := oldDependency.ImmediateYoungerSibling - if younger != "" { - ctx.Logger().Info(fmt.Sprintf("update younger sibling %s of %s for dependency %s", younger, msg.Contract.ContractAddr, oldDependency.Dependency)) - youngContract, err := k.GetContract(ctx, younger) - if err != nil { - return err - } - for _, youngDependency := range youngContract.Dependencies { - if youngDependency.Dependency != oldDependency.Dependency { - continue - } - youngDependency.ImmediateElderSibling = elder - if err := k.SetContract(ctx, &youngContract); err != nil { - return err - } - break - } - } - if elder != "" { - ctx.Logger().Info(fmt.Sprintf("update elder sibling %s of %s for dependency %s", elder, msg.Contract.ContractAddr, oldDependency.Dependency)) - elderContract, err := k.GetContract(ctx, elder) - if err != nil { - return err - } - for _, elderDependency := range elderContract.Dependencies { - if elderDependency.Dependency != oldDependency.Dependency { - continue - } - elderDependency.ImmediateYoungerSibling = younger - if err := k.SetContract(ctx, &elderContract); err != nil { - return err - } - break - } - } - } - return nil -} - -func (k msgServer) UpdateNewDependencies(ctx sdk.Context, msg *types.MsgRegisterContract) error { - if msg.Contract.Dependencies == nil { - return nil - } - - for _, dependency := range msg.Contract.Dependencies { - contractInfo, err := k.GetContract(ctx, dependency.Dependency) - if err != nil { - // validate that all dependency contracts exist - return err - } - // update incoming paths for dependency contracts - contractInfo.NumIncomingDependencies++ - if err := k.SetContract(ctx, &contractInfo); err != nil { - return err - } - } - return nil -} - -func (k msgServer) HandleDepositOrRefund(ctx sdk.Context, msg *types.MsgRegisterContract) error { - creatorAddr, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - return err - } - if existingContract, err := k.GetContract(ctx, msg.Contract.ContractAddr); err != nil { - // brand new contract - if msg.Contract.RentBalance > 0 { - if err := k.BankKeeper.SendCoins(ctx, creatorAddr, k.AccountKeeper.GetModuleAddress(types.ModuleName), sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewIntFromUint64(msg.Contract.RentBalance)))); err != nil { - return err - } - } - } else { - if msg.Creator != existingContract.Creator { - return sdkerrors.ErrUnauthorized - } - if msg.Contract.RentBalance < existingContract.RentBalance { - // refund - refundAmount := existingContract.RentBalance - msg.Contract.RentBalance - if err := k.BankKeeper.SendCoins(ctx, k.AccountKeeper.GetModuleAddress(types.ModuleName), creatorAddr, sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewIntFromUint64(refundAmount)))); err != nil { - return err - } - } else if msg.Contract.RentBalance > existingContract.RentBalance { - // deposit - depositAmount := msg.Contract.RentBalance - existingContract.RentBalance - if err := k.BankKeeper.SendCoins(ctx, creatorAddr, k.AccountKeeper.GetModuleAddress(types.ModuleName), sdk.NewCoins(sdk.NewCoin(appparams.BaseCoinUnit, sdk.NewIntFromUint64(depositAmount)))); err != nil { - return err - } - } - } - return nil -} - -func (k msgServer) SetNewContract(ctx sdk.Context, msg *types.MsgRegisterContract) ([]types.ContractInfoV2, error) { - // set incoming paths for new contract - newContract := msg.Contract - newContract.Creator = msg.Creator - newContract.NumIncomingDependencies = 0 - allContractInfo := k.GetAllContractInfo(ctx) - for _, contractInfo := range allContractInfo { - if contractInfo.Dependencies == nil { - continue - } - dependencySet := datastructures.NewSyncSet(utils.Map( - contractInfo.Dependencies, func(c *types.ContractDependencyInfo) string { return c.Dependency }, - )) - if dependencySet.Contains(msg.Contract.ContractAddr) { - newContract.NumIncomingDependencies++ - } - } - - // set immediate siblings - for _, dependency := range newContract.Dependencies { - // a newly added/updated contract is always the youngest among its siblings - dependency.ImmediateYoungerSibling = "" - found := false - for _, contractInfo := range allContractInfo { - if contractInfo.ContractAddr == newContract.ContractAddr { - continue - } - for _, otherDependency := range contractInfo.Dependencies { - if otherDependency.ImmediateYoungerSibling != "" { - continue - } - if otherDependency.Dependency != dependency.Dependency { - continue - } - dependency.ImmediateElderSibling = contractInfo.ContractAddr - otherDependency.ImmediateYoungerSibling = newContract.ContractAddr - contractInfo := contractInfo - if err := k.SetContract(ctx, &contractInfo); err != nil { - return []types.ContractInfoV2{}, err - } - found = true - break - } - if found { - break - } - } - if !found { - dependency.ImmediateElderSibling = "" - } - } - - // always override contract info so that it can be updated - if err := k.SetContract(ctx, newContract); err != nil { - return []types.ContractInfoV2{}, err - } - allContractInfo = append(allContractInfo, *newContract) - return allContractInfo, nil + return nil, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated") } diff --git a/x/dex/keeper/msgserver/msg_server_register_contract_test.go b/x/dex/keeper/msgserver/msg_server_register_contract_test.go index 9b989ed790..c4bcc6e1cd 100644 --- a/x/dex/keeper/msgserver/msg_server_register_contract_test.go +++ b/x/dex/keeper/msgserver/msg_server_register_contract_test.go @@ -2,32 +2,22 @@ package msgserver_test import ( "context" - "io/ioutil" - "math" "testing" "time" - wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" - wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" keepertest "github.com/sei-protocol/sei-chain/testutil/keeper" - "github.com/sei-protocol/sei-chain/utils" dexcache "github.com/sei-protocol/sei-chain/x/dex/cache" "github.com/sei-protocol/sei-chain/x/dex/keeper/msgserver" "github.com/sei-protocol/sei-chain/x/dex/types" dexutils "github.com/sei-protocol/sei-chain/x/dex/utils" - minttypes "github.com/sei-protocol/sei-chain/x/mint/types" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" ) const ( TestContractA = "sei1hrpna9v7vs3stzyd4z3xf00676kf78zpe2u5ksvljswn2vnjp3yslucc3n" - TestContractB = "sei1nc5tatafv6eyq7llkr2gv50ff9e22mnf70qgjlv737ktmt4eswrqms7u8a" - TestContractC = "sei1xr3rq8yvd7qplsw5yx90ftsr2zdhg4e9z60h5duusgxpv72hud3shh3qfl" - TestContractD = "sei1up07dctjqud4fns75cnpejr4frmjtddzsmwgcktlyxd4zekhwecqghxqcp" - TestContractX = "sei1hw5n2l4v5vz8lk4sj69j7pwdaut0kkn90mw09snlkdd3f7ckld0smdtvee" - TestContractY = "sei12pwnhtv7yat2s30xuf4gdk9qm85v4j3e6p44let47pdffpklcxlqh8ag0z" ) func TestRegisterContract(t *testing.T) { @@ -38,425 +28,7 @@ func TestRegisterContract(t *testing.T) { wctx := sdk.WrapSDKContext(ctx) keeper := testApp.DexKeeper - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddr, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - server := msgserver.NewMsgServerImpl(keeper) - err = RegisterContractUtil(server, wctx, contractAddr.String(), nil) - require.NoError(t, err) - storedContracts := keeper.GetAllContractInfo(ctx) - require.Equal(t, 1, len(storedContracts)) - require.Nil(t, storedContracts[0].Dependencies) - - // dependency doesn't exist - err = RegisterContractUtil(server, wctx, contractAddr.String(), []string{TestContractY}) - require.NotNil(t, err) - storedContracts = keeper.GetAllContractInfo(ctx) - require.Equal(t, 1, len(storedContracts)) -} - -func TestRegisterContractCircularDependency(t *testing.T) { - // Instantiate and get contract address - testApp := keepertest.TestApp() - ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - wctx := sdk.WrapSDKContext(ctx) - keeper := testApp.DexKeeper - - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddrFirst, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - contractAddrSecond, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - server := msgserver.NewMsgServerImpl(keeper) - RegisterContractUtil(server, wctx, contractAddrFirst.String(), nil) - storedContracts := keeper.GetAllContractInfo(ctx) - require.Equal(t, 1, len(storedContracts)) - - RegisterContractUtil(server, wctx, contractAddrSecond.String(), []string{contractAddrFirst.String()}) - storedContracts = keeper.GetAllContractInfo(ctx) - require.Equal(t, 2, len(storedContracts)) - - // This contract should fail to be registered because it causes a - // circular dependency - err = RegisterContractUtil(server, wctx, contractAddrFirst.String(), []string{contractAddrFirst.String()}) - require.NotNil(t, err) -} - -func TestRegisterContractDuplicateDependency(t *testing.T) { - // Instantiate and get contract address - testApp := keepertest.TestApp() - ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - wctx := sdk.WrapSDKContext(ctx) - keeper := testApp.DexKeeper - - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddr, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - server := msgserver.NewMsgServerImpl(keeper) - err = RegisterContractUtil(server, wctx, contractAddr.String(), []string{contractAddr.String(), contractAddr.String()}) - require.NotNil(t, err) - storedContracts := keeper.GetAllContractInfo(ctx) - require.Equal(t, 0, len(storedContracts)) -} - -func TestRegisterContractNumIncomingPaths(t *testing.T) { - // Instantiate and get contract address - testApp := keepertest.TestApp() - ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - wctx := sdk.WrapSDKContext(ctx) - keeper := testApp.DexKeeper - - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddrFirst, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - contractAddrSecond, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - server := msgserver.NewMsgServerImpl(keeper) - err = RegisterContractUtil(server, wctx, contractAddrFirst.String(), nil) - require.Nil(t, err) - storedContract, err := keeper.GetContract(ctx, contractAddrFirst.String()) - require.Nil(t, err) - require.Equal(t, int64(0), storedContract.NumIncomingDependencies) - - RegisterContractUtil(server, wctx, contractAddrSecond.String(), []string{contractAddrFirst.String()}) - storedContract, err = keeper.GetContract(ctx, contractAddrFirst.String()) - require.Nil(t, err) - require.Equal(t, int64(1), storedContract.NumIncomingDependencies) - storedContract, err = keeper.GetContract(ctx, contractAddrSecond.String()) - require.Nil(t, err) - require.Equal(t, int64(0), storedContract.NumIncomingDependencies) - - RegisterContractUtil(server, wctx, contractAddrSecond.String(), nil) - storedContract, err = keeper.GetContract(ctx, contractAddrFirst.String()) - require.Nil(t, err) - require.Equal(t, int64(0), storedContract.NumIncomingDependencies) - storedContract, err = keeper.GetContract(ctx, contractAddrFirst.String()) - require.Nil(t, err) - require.Equal(t, int64(0), storedContract.NumIncomingDependencies) -} - -func TestRegisterContractSetSiblings(t *testing.T) { - // Instantiate and get contract address - testApp := keepertest.TestApp() - ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - wctx := sdk.WrapSDKContext(ctx) - keeper := testApp.DexKeeper - - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - - contractAddrA, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - contractAddrB, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - contractAddrC, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - contractAddrD, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - contractAddrX, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - contractAddrY, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - // A -> X, B -> X, C -> Y - server := msgserver.NewMsgServerImpl(keeper) - err = RegisterContractUtil(server, wctx, contractAddrX.String(), nil) - if err != nil { - panic(err) - } - err = RegisterContractUtil(server, wctx, contractAddrY.String(), nil) - if err != nil { - panic(err) - } - err = RegisterContractUtil(server, wctx, contractAddrA.String(), []string{contractAddrX.String()}) - if err != nil { - panic(err) - } - err = RegisterContractUtil(server, wctx, contractAddrB.String(), []string{contractAddrX.String()}) - if err != nil { - panic(err) - } - err = RegisterContractUtil(server, wctx, contractAddrC.String(), []string{contractAddrY.String()}) - if err != nil { - panic(err) - } - // add D -> X, D -> Y - err = RegisterContractUtil(server, wctx, contractAddrD.String(), []string{contractAddrX.String(), contractAddrY.String()}) - if err != nil { - panic(err) - } - contract, _ := keeper.GetContract(ctx, contractAddrA.String()) - require.Equal(t, "", contract.Dependencies[0].ImmediateElderSibling) - require.Equal(t, contractAddrB.String(), contract.Dependencies[0].ImmediateYoungerSibling) - contract, _ = keeper.GetContract(ctx, contractAddrB.String()) - require.Equal(t, contractAddrA.String(), contract.Dependencies[0].ImmediateElderSibling) - require.Equal(t, contractAddrD.String(), contract.Dependencies[0].ImmediateYoungerSibling) - contract, _ = keeper.GetContract(ctx, contractAddrC.String()) - require.Equal(t, "", contract.Dependencies[0].ImmediateElderSibling) - require.Equal(t, contractAddrD.String(), contract.Dependencies[0].ImmediateYoungerSibling) - contract, _ = keeper.GetContract(ctx, contractAddrD.String()) - require.Equal(t, contractAddrB.String(), contract.Dependencies[0].ImmediateElderSibling) - require.Equal(t, "", contract.Dependencies[0].ImmediateYoungerSibling) - require.Equal(t, contractAddrC.String(), contract.Dependencies[1].ImmediateElderSibling) - require.Equal(t, "", contract.Dependencies[1].ImmediateYoungerSibling) - // update D -> X only - err = RegisterContractUtil(server, wctx, contractAddrD.String(), []string{contractAddrX.String()}) - if err != nil { - panic(err) - } - contract, _ = keeper.GetContract(ctx, contractAddrD.String()) - require.Equal(t, 1, len(contract.Dependencies)) - require.Equal(t, contractAddrB.String(), contract.Dependencies[0].ImmediateElderSibling) - require.Equal(t, "", contract.Dependencies[0].ImmediateYoungerSibling) - contract, _ = keeper.GetContract(ctx, contractAddrA.String()) - require.Equal(t, "", contract.Dependencies[0].ImmediateElderSibling) - require.Equal(t, contractAddrB.String(), contract.Dependencies[0].ImmediateYoungerSibling) - contract, _ = keeper.GetContract(ctx, contractAddrB.String()) - require.Equal(t, contractAddrA.String(), contract.Dependencies[0].ImmediateElderSibling) - require.Equal(t, contractAddrD.String(), contract.Dependencies[0].ImmediateYoungerSibling) - contract, _ = keeper.GetContract(ctx, contractAddrC.String()) - require.Equal(t, "", contract.Dependencies[0].ImmediateElderSibling) - require.Equal(t, "", contract.Dependencies[0].ImmediateYoungerSibling) -} - -func TestRegisterContractWithInvalidRentBalance(t *testing.T) { - // Instantiate and get contract address - testApp := keepertest.TestApp() - ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - wctx := sdk.WrapSDKContext(ctx) - keeper := testApp.DexKeeper - - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddr, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - server := msgserver.NewMsgServerImpl(keeper) - contract := types.ContractInfoV2{ - CodeId: 1, - ContractAddr: contractAddr.String(), - RentBalance: math.MaxUint64, - } - _, err = server.RegisterContract(wctx, &types.MsgRegisterContract{ - Creator: keepertest.TestAccount, - Contract: &contract, - }) - require.Error(t, err) -} - -func TestRegisterContractInvalidRentBalance(t *testing.T) { - // Instantiate and get contract address - testApp := keepertest.TestApp() - ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - wctx := sdk.WrapSDKContext(ctx) - keeper := testApp.DexKeeper - - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - - contractAddrX, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - // register with rent balance amount more than allowed - server := msgserver.NewMsgServerImpl(keeper) - rentBalance := uint64(math.MaxUint64)/wasmkeeper.DefaultGasMultiplier + 1 - contract := types.ContractInfoV2{ - CodeId: 1, - ContractAddr: contractAddrX.String(), - RentBalance: rentBalance, - } - - _, err = server.RegisterContract(wctx, &types.MsgRegisterContract{ - Creator: keepertest.TestAccount, - Contract: &contract, - }) - require.Error(t, err) - - // register with rent balance less than allowed - rentBalance = keeper.GetParams(ctx).MinRentDeposit - 1 - contract = types.ContractInfoV2{ - CodeId: 1, - ContractAddr: contractAddrX.String(), - RentBalance: rentBalance, - } - - _, err = server.RegisterContract(wctx, &types.MsgRegisterContract{ - Creator: keepertest.TestAccount, - Contract: &contract, - }) - require.Error(t, err) -} - -func RegisterContractUtil(server types.MsgServer, ctx context.Context, contractAddr string, dependencies []string) error { - contract := types.ContractInfoV2{ - CodeId: 1, - ContractAddr: contractAddr, - RentBalance: types.DefaultMinRentDeposit, - } - if dependencies != nil { - contract.Dependencies = utils.Map(dependencies, func(addr string) *types.ContractDependencyInfo { - return &types.ContractDependencyInfo{ - Dependency: addr, - } - }) - } - _, err := server.RegisterContract(ctx, &types.MsgRegisterContract{ - Creator: keepertest.TestAccount, - Contract: &contract, - }) - return err + _, err := server.RegisterContract(wctx, &types.MsgRegisterContract{}) + require.EqualError(t, err, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated").Error()) } diff --git a/x/dex/keeper/msgserver/msg_server_register_pairs.go b/x/dex/keeper/msgserver/msg_server_register_pairs.go index e63a4a4e63..582521dd5d 100644 --- a/x/dex/keeper/msgserver/msg_server_register_pairs.go +++ b/x/dex/keeper/msgserver/msg_server_register_pairs.go @@ -2,64 +2,11 @@ package msgserver import ( "context" - "strings" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/sei-protocol/sei-chain/x/dex/types" ) func (k msgServer) RegisterPairs(goCtx context.Context, msg *types.MsgRegisterPairs) (*types.MsgRegisterPairsResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - - maxPairsPerContract := k.GetMaxPairsPerContract(ctx) - events := []sdk.Event{} - // Validation such that only the user who stored the code can register pairs - for _, batchPair := range msg.Batchcontractpair { - contractAddr := batchPair.ContractAddr - existingPairCount := uint64(len(k.GetAllRegisteredPairs(ctx, contractAddr))) - if existingPairCount >= maxPairsPerContract { - return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "contract %s already has %d pairs registered", contractAddr, existingPairCount) - } - contractInfo, err := k.GetContract(ctx, contractAddr) - if err != nil { - return nil, err - } - - if msg.Creator != contractInfo.Creator { - return nil, sdkerrors.ErrUnauthorized - } - - // Loop through each batch contract pair an individual contract pair, token pair - // tuple and register them individually - for _, pair := range batchPair.Pairs { - if !isValidDenom(pair.PriceDenom) || !isValidDenom(pair.AssetDenom) { - return nil, sdkerrors.ErrInvalidRequest - } - added := k.AddRegisteredPair(ctx, contractAddr, *pair) - - if !added { - // If its already added then no event is emitted - continue - } - events = append(events, sdk.NewEvent( - types.EventTypeRegisterPair, - sdk.NewAttribute(types.AttributeKeyContractAddress, contractAddr), - sdk.NewAttribute(types.AttributeKeyPriceDenom, pair.PriceDenom), - sdk.NewAttribute(types.AttributeKeyAssetDenom, pair.AssetDenom), - )) - } - } - - ctx.EventManager().EmitEvents(events) - - return &types.MsgRegisterPairsResponse{}, nil -} - -func isValidDenom(denom string) bool { - return denom != "" && !strings.Contains(denom, types.PairDelim) + return nil, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated") } diff --git a/x/dex/keeper/msgserver/msg_server_register_pairs_test.go b/x/dex/keeper/msgserver/msg_server_register_pairs_test.go index 9451c1fbe4..bc4dc91983 100644 --- a/x/dex/keeper/msgserver/msg_server_register_pairs_test.go +++ b/x/dex/keeper/msgserver/msg_server_register_pairs_test.go @@ -2,19 +2,16 @@ package msgserver_test import ( "context" - "io/ioutil" "testing" "time" - wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" - wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" keepertest "github.com/sei-protocol/sei-chain/testutil/keeper" dexcache "github.com/sei-protocol/sei-chain/x/dex/cache" "github.com/sei-protocol/sei-chain/x/dex/keeper/msgserver" "github.com/sei-protocol/sei-chain/x/dex/types" dexutils "github.com/sei-protocol/sei-chain/x/dex/utils" - minttypes "github.com/sei-protocol/sei-chain/x/mint/types" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" ) @@ -26,299 +23,16 @@ func TestRegisterPairs(t *testing.T) { wctx := sdk.WrapSDKContext(ctx) keeper := testApp.DexKeeper - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddrA, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - contractAddrB, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - server := msgserver.NewMsgServerImpl(keeper) - err = RegisterContractUtil(server, wctx, contractAddrA.String(), nil) - require.NoError(t, err) - - batchContractPairs := []types.BatchContractPair{} - batchContractPairs = append(batchContractPairs, types.BatchContractPair{ - ContractAddr: contractAddrA.String(), - Pairs: []*types.Pair{&keepertest.TestPair}, - }) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: keepertest.TestAccount, - Batchcontractpair: batchContractPairs, - }) - - require.NoError(t, err) - storedRegisteredPairs := keeper.GetAllRegisteredPairs(ctx, contractAddrA.String()) - require.Equal(t, 1, len(storedRegisteredPairs)) - require.Equal(t, keepertest.TestPair, storedRegisteredPairs[0]) - - // Test multiple pairs registered at once - err = RegisterContractUtil(server, wctx, contractAddrB.String(), nil) - require.NoError(t, err) - multiplePairs := []types.BatchContractPair{} - secondTestPair := types.Pair{ - PriceDenom: "sei", - AssetDenom: "osmo", - PriceTicksize: &keepertest.TestTicksize, - QuantityTicksize: &keepertest.TestTicksize, - } - multiplePairs = append(multiplePairs, types.BatchContractPair{ - ContractAddr: contractAddrB.String(), - Pairs: []*types.Pair{&keepertest.TestPair, &secondTestPair}, - }) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: keepertest.TestAccount, - Batchcontractpair: multiplePairs, - }) - - require.NoError(t, err) - storedRegisteredPairs = keeper.GetAllRegisteredPairs(ctx, contractAddrB.String()) - require.Equal(t, 2, len(storedRegisteredPairs)) - require.Equal(t, secondTestPair, storedRegisteredPairs[0]) - require.Equal(t, keepertest.TestPair, storedRegisteredPairs[1]) -} - -func TestRegisterPairsInvalidMsg(t *testing.T) { - testApp := keepertest.TestApp() - ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - wctx := sdk.WrapSDKContext(ctx) - keeper := testApp.DexKeeper - - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddrA, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - server := msgserver.NewMsgServerImpl(keeper) - err = RegisterContractUtil(server, wctx, contractAddrA.String(), nil) - require.NoError(t, err) - batchContractPairs := []types.BatchContractPair{} - batchContractPairs = append(batchContractPairs, types.BatchContractPair{ - ContractAddr: contractAddrA.String(), - Pairs: []*types.Pair{&keepertest.TestPair}, - }) - - // Test with empty creator address - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: "", - Batchcontractpair: batchContractPairs, - }) - require.NotNil(t, err) - - // Test with empty msg - batchContractPairs = []types.BatchContractPair{} - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: keepertest.TestAccount, - Batchcontractpair: batchContractPairs, - }) - require.NotNil(t, err) - - // Test with invalid Creator address - batchContractPairs = []types.BatchContractPair{} - batchContractPairs = append(batchContractPairs, types.BatchContractPair{ - ContractAddr: contractAddrA.String(), - Pairs: []*types.Pair{&keepertest.TestPair}, - }) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: "invalidAddress", - Batchcontractpair: batchContractPairs, - }) - require.NotNil(t, err) - - // Test with empty contract address - batchContractPairs = []types.BatchContractPair{} - batchContractPairs = append(batchContractPairs, types.BatchContractPair{ - ContractAddr: "", - Pairs: []*types.Pair{&keepertest.TestPair}, - }) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: keepertest.TestAccount, - Batchcontractpair: batchContractPairs, - }) - require.NotNil(t, err) - - // Test with empty pairs list - batchContractPairs = []types.BatchContractPair{} - batchContractPairs = append(batchContractPairs, types.BatchContractPair{ - ContractAddr: contractAddrA.String(), - Pairs: []*types.Pair{}, - }) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: keepertest.TestAccount, - Batchcontractpair: batchContractPairs, - }) - require.NotNil(t, err) - - // Test with nil pair - batchContractPairs = []types.BatchContractPair{} - batchContractPairs = append(batchContractPairs, types.BatchContractPair{ - ContractAddr: contractAddrA.String(), - Pairs: []*types.Pair{nil}, - }) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: keepertest.TestAccount, - Batchcontractpair: batchContractPairs, - }) - require.NotNil(t, err) -} - -// Test only contract creator can update registered pairs for contract -func TestInvalidRegisterPairCreator(t *testing.T) { - testApp := keepertest.TestApp() - ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - eventManger := ctx.EventManager() - wctx := sdk.WrapSDKContext(ctx) - keeper := testApp.DexKeeper - - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddrA, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - server := msgserver.NewMsgServerImpl(keeper) - err = RegisterContractUtil(server, wctx, contractAddrA.String(), nil) - require.NoError(t, err) - - // Expect error when registering pair with an address not contract creator - batchContractPairs := []types.BatchContractPair{} - - initalEventSize := len(eventManger.Events()) - batchContractPairs = append(batchContractPairs, types.BatchContractPair{ - ContractAddr: contractAddrA.String(), - Pairs: []*types.Pair{&keepertest.TestPair}, - }) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: "sei18rrckuelmacz4fv4v2hl9t3kaw7mm4wpe8v36m", - Batchcontractpair: batchContractPairs, - }) - // Nothing emitted when creator != address - require.Equal(t, len(eventManger.Events()), initalEventSize) - require.NotNil(t, err) - - // Works when creator = address - initalEventSize = len(eventManger.Events()) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: keepertest.TestAccount, - Batchcontractpair: batchContractPairs, - }) - // One pair emitted - require.Greater(t, len(eventManger.Events()), initalEventSize) - require.NoError(t, err) - - // Remit the process the same pairs again - initalEventSize = len(eventManger.Events()) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: keepertest.TestAccount, - Batchcontractpair: batchContractPairs, - }) - // No event change this time - require.Equal(t, len(eventManger.Events()), initalEventSize) - require.NoError(t, err) - -} - -func TestRegisterPairsExceedingLimit(t *testing.T) { - testApp := keepertest.TestApp() - ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - wctx := sdk.WrapSDKContext(ctx) - keeper := testApp.DexKeeper - - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddrA, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - params := keeper.GetParams(ctx) - params.MaxPairsPerContract = 0 - keeper.SetParams(ctx, params) server := msgserver.NewMsgServerImpl(keeper) - err = RegisterContractUtil(server, wctx, contractAddrA.String(), nil) - require.NoError(t, err) batchContractPairs := []types.BatchContractPair{} batchContractPairs = append(batchContractPairs, types.BatchContractPair{ - ContractAddr: contractAddrA.String(), + ContractAddr: TestContractA, Pairs: []*types.Pair{&keepertest.TestPair}, }) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ + _, err := server.RegisterPairs(wctx, &types.MsgRegisterPairs{ Creator: keepertest.TestAccount, Batchcontractpair: batchContractPairs, }) - - require.NotNil(t, err) + require.EqualError(t, err, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated").Error()) } diff --git a/x/dex/keeper/msgserver/msg_server_test.go b/x/dex/keeper/msgserver/msg_server_test.go deleted file mode 100644 index 817e1af9d5..0000000000 --- a/x/dex/keeper/msgserver/msg_server_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package msgserver_test - -import ( - "context" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - keepertest "github.com/sei-protocol/sei-chain/testutil/keeper" - "github.com/sei-protocol/sei-chain/x/dex/keeper/msgserver" - "github.com/sei-protocol/sei-chain/x/dex/types" -) - -func setupMsgServer(t testing.TB) (types.MsgServer, context.Context) { - k, ctx := keepertest.DexKeeper(t) - return msgserver.NewMsgServerImpl(*k), sdk.WrapSDKContext(ctx) -} diff --git a/x/dex/keeper/msgserver/msg_server_unregister_contract.go b/x/dex/keeper/msgserver/msg_server_unregister_contract.go index b6f382a19f..c12650b854 100644 --- a/x/dex/keeper/msgserver/msg_server_unregister_contract.go +++ b/x/dex/keeper/msgserver/msg_server_unregister_contract.go @@ -2,38 +2,11 @@ package msgserver import ( "context" - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/sei-protocol/sei-chain/x/dex/types" - dexutils "github.com/sei-protocol/sei-chain/x/dex/utils" ) func (k msgServer) UnregisterContract(goCtx context.Context, msg *types.MsgUnregisterContract) (*types.MsgUnregisterContractResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := msg.ValidateBasic(); err != nil { - ctx.Logger().Error(fmt.Sprintf("request invalid: %s", err)) - return nil, err - } - - contract, err := k.GetContract(ctx, msg.ContractAddr) - if err != nil { - return nil, err - } - if contract.Creator != msg.Creator { - return nil, sdkerrors.ErrUnauthorized - } - if err := k.DoUnregisterContractWithRefund(ctx, contract); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeUnregisterContract, - sdk.NewAttribute(types.AttributeKeyContractAddress, msg.ContractAddr), - )) - - dexutils.GetMemState(ctx.Context()).ClearContractToDependencies(ctx) - return &types.MsgUnregisterContractResponse{}, nil + return nil, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated") } diff --git a/x/dex/keeper/msgserver/msg_server_unregister_contract_test.go b/x/dex/keeper/msgserver/msg_server_unregister_contract_test.go index 66904a822a..2d91979a76 100644 --- a/x/dex/keeper/msgserver/msg_server_unregister_contract_test.go +++ b/x/dex/keeper/msgserver/msg_server_unregister_contract_test.go @@ -2,20 +2,16 @@ package msgserver_test import ( "context" - "io/ioutil" "testing" "time" - wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" - wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" keepertest "github.com/sei-protocol/sei-chain/testutil/keeper" "github.com/sei-protocol/sei-chain/x/dex" dexcache "github.com/sei-protocol/sei-chain/x/dex/cache" - "github.com/sei-protocol/sei-chain/x/dex/keeper/msgserver" "github.com/sei-protocol/sei-chain/x/dex/types" dexutils "github.com/sei-protocol/sei-chain/x/dex/utils" - minttypes "github.com/sei-protocol/sei-chain/x/mint/types" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" ) @@ -24,77 +20,15 @@ func TestUnregisterContractSetSiblings(t *testing.T) { testApp := keepertest.TestApp() ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - wctx := sdk.WrapSDKContext(ctx) keeper := testApp.DexKeeper testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddr, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - server := msgserver.NewMsgServerImpl(keeper) - contract := types.ContractInfoV2{ - CodeId: 1, - ContractAddr: contractAddr.String(), - Creator: testAccount.String(), - RentBalance: types.DefaultParams().MinRentDeposit, - } - _, err = server.RegisterContract(wctx, &types.MsgRegisterContract{ - Creator: testAccount.String(), - Contract: &contract, - }) - require.NoError(t, err) - _, err = keeper.GetContract(ctx, contractAddr.String()) - require.NoError(t, err) - balance := keeper.BankKeeper.GetBalance(ctx, testAccount, "usei") - require.Equal(t, int64(89900000), balance.Amount.Int64()) handler := dex.NewHandler(keeper) - tickSize := sdk.OneDec() - _, err = handler(ctx, &types.MsgRegisterPairs{ - Creator: testAccount.String(), - Batchcontractpair: []types.BatchContractPair{ - { - ContractAddr: contractAddr.String(), - Pairs: []*types.Pair{ - { - PriceDenom: "usei", - AssetDenom: "uatom", - PriceTicksize: &tickSize, - QuantityTicksize: &tickSize, - }, - }, - }, - }, - }) - require.NoError(t, err) - _, err = handler(ctx, &types.MsgUnregisterContract{ + _, err := handler(ctx, &types.MsgUnregisterContract{ Creator: testAccount.String(), - ContractAddr: contractAddr.String(), + ContractAddr: TestContractA, }) - require.NoError(t, err) - _, err = keeper.GetContract(ctx, contractAddr.String()) - require.Error(t, err) - balance = keeper.BankKeeper.GetBalance(ctx, testAccount, "usei") - require.Equal(t, int64(99900000), balance.Amount.Int64()) - pairs := keeper.GetAllRegisteredPairs(ctx, contractAddr.String()) - require.Empty(t, pairs) + require.EqualError(t, err, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated").Error()) } diff --git a/x/dex/keeper/msgserver/msg_server_unsuspend_contract.go b/x/dex/keeper/msgserver/msg_server_unsuspend_contract.go index c45775e2e2..d1da8c2c58 100644 --- a/x/dex/keeper/msgserver/msg_server_unsuspend_contract.go +++ b/x/dex/keeper/msgserver/msg_server_unsuspend_contract.go @@ -2,44 +2,11 @@ package msgserver import ( "context" - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/sei-protocol/sei-chain/x/dex/types" - dexutils "github.com/sei-protocol/sei-chain/x/dex/utils" ) func (k msgServer) UnsuspendContract(goCtx context.Context, msg *types.MsgUnsuspendContract) (*types.MsgUnsuspendContractResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := msg.ValidateBasic(); err != nil { - ctx.Logger().Error(fmt.Sprintf("request invalid: %s", err)) - return nil, err - } - - contract, err := k.GetContract(ctx, msg.ContractAddr) - if err != nil { - return &types.MsgUnsuspendContractResponse{}, err - } - - if !contract.Suspended { - return &types.MsgUnsuspendContractResponse{}, types.ErrContractNotSuspended - } - - cost := k.GetContractUnsuspendCost(ctx) - if contract.RentBalance < cost { - return &types.MsgUnsuspendContractResponse{}, types.ErrInsufficientRent - } - - contract.Suspended = false - contract.SuspensionReason = "" - contract.RentBalance -= cost - if err := k.SetContract(ctx, &contract); err != nil { - return &types.MsgUnsuspendContractResponse{}, err - } - - // suspension changes will also affect dependency traversal since suspended contracts are skipped - dexutils.GetMemState(ctx.Context()).ClearContractToDependencies(ctx) - - return &types.MsgUnsuspendContractResponse{}, nil + return nil, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated") } diff --git a/x/dex/keeper/msgserver/msg_server_unsuspend_contract_test.go b/x/dex/keeper/msgserver/msg_server_unsuspend_contract_test.go index bbfe124009..a2ac0f3ace 100644 --- a/x/dex/keeper/msgserver/msg_server_unsuspend_contract_test.go +++ b/x/dex/keeper/msgserver/msg_server_unsuspend_contract_test.go @@ -4,6 +4,7 @@ import ( "testing" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" keepertest "github.com/sei-protocol/sei-chain/testutil/keeper" "github.com/sei-protocol/sei-chain/x/dex/keeper/msgserver" "github.com/sei-protocol/sei-chain/x/dex/types" @@ -13,59 +14,10 @@ import ( func TestUnsuspendContract(t *testing.T) { keeper, ctx := keepertest.DexKeeper(t) wctx := sdk.WrapSDKContext(ctx) - keeper.SetParams(ctx, types.DefaultParams()) - keeper.SetContract(ctx, &types.ContractInfoV2{ - ContractAddr: keepertest.TestContract, - Creator: keepertest.TestAccount, - RentBalance: types.DefaultContractUnsuspendCost, - Suspended: true, - SuspensionReason: "bad", - }) - server := msgserver.NewMsgServerImpl(*keeper) - _, err := server.UnsuspendContract(wctx, &types.MsgUnsuspendContract{ - Creator: keepertest.TestAccount, - ContractAddr: keepertest.TestContract, - }) - require.Nil(t, err) - contract, err := keeper.GetContract(ctx, keepertest.TestContract) - require.Nil(t, err) - require.Equal(t, types.ContractInfoV2{ - ContractAddr: keepertest.TestContract, - Creator: keepertest.TestAccount, - }, contract) -} - -func TestUnsuspendContractInvalid(t *testing.T) { - keeper, ctx := keepertest.DexKeeper(t) - wctx := sdk.WrapSDKContext(ctx) - contract := types.ContractInfoV2{ - ContractAddr: keepertest.TestContract, - Creator: keepertest.TestAccount, - RentBalance: types.DefaultContractUnsuspendCost - 1, - Suspended: true, - SuspensionReason: "bad", - } - keeper.SetParams(ctx, types.DefaultParams()) server := msgserver.NewMsgServerImpl(*keeper) - keeper.SetContract(ctx, &contract) _, err := server.UnsuspendContract(wctx, &types.MsgUnsuspendContract{ Creator: keepertest.TestAccount, ContractAddr: keepertest.TestContract, }) - require.NotNil(t, err) - gotContract, err := keeper.GetContract(ctx, keepertest.TestContract) - require.Nil(t, err) - require.Equal(t, contract, gotContract) - - contract.RentBalance += 1 - contract.Suspended = false - keeper.SetContract(ctx, &contract) - _, err = server.UnsuspendContract(wctx, &types.MsgUnsuspendContract{ - Creator: keepertest.TestAccount, - ContractAddr: keepertest.TestContract, - }) - require.NotNil(t, err) - gotContract, err = keeper.GetContract(ctx, keepertest.TestContract) - require.Nil(t, err) - require.Equal(t, contract, gotContract) + require.EqualError(t, err, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated").Error()) } diff --git a/x/dex/keeper/msgserver/msg_server_update_price_tick_size.go b/x/dex/keeper/msgserver/msg_server_update_price_tick_size.go index ea6b05865d..6a09e1dc79 100644 --- a/x/dex/keeper/msgserver/msg_server_update_price_tick_size.go +++ b/x/dex/keeper/msgserver/msg_server_update_price_tick_size.go @@ -3,35 +3,10 @@ package msgserver import ( "context" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/sei-protocol/sei-chain/x/dex/types" ) func (k msgServer) UpdatePriceTickSize(goCtx context.Context, msg *types.MsgUpdatePriceTickSize) (*types.MsgUpdateTickSizeResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - - // Validation such that only the user who stored the code can update tick size - for _, tickSize := range msg.TickSizeList { - contractAddr := tickSize.ContractAddr - contractInfo, err := k.GetContract(ctx, contractAddr) - if err != nil { - return nil, err - } - - if msg.Creator != contractInfo.Creator { - return nil, sdkerrors.ErrUnauthorized - } - - err = k.SetPriceTickSizeForPair(ctx, tickSize.ContractAddr, *tickSize.Pair, tickSize.Ticksize) - if err != nil { - return nil, err - } - } - - return &types.MsgUpdateTickSizeResponse{}, nil + return nil, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated") } diff --git a/x/dex/keeper/msgserver/msg_server_update_price_tick_size_test.go b/x/dex/keeper/msgserver/msg_server_update_price_tick_size_test.go index 46da14c7ec..77ab54fae1 100644 --- a/x/dex/keeper/msgserver/msg_server_update_price_tick_size_test.go +++ b/x/dex/keeper/msgserver/msg_server_update_price_tick_size_test.go @@ -2,19 +2,16 @@ package msgserver_test import ( "context" - "io/ioutil" "testing" "time" - wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" - wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" keepertest "github.com/sei-protocol/sei-chain/testutil/keeper" dexcache "github.com/sei-protocol/sei-chain/x/dex/cache" "github.com/sei-protocol/sei-chain/x/dex/keeper/msgserver" "github.com/sei-protocol/sei-chain/x/dex/types" dexutils "github.com/sei-protocol/sei-chain/x/dex/utils" - minttypes "github.com/sei-protocol/sei-chain/x/mint/types" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" ) @@ -26,225 +23,18 @@ func TestUpdatePriceTickSize(t *testing.T) { ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) wctx := sdk.WrapSDKContext(ctx) keeper := testApp.DexKeeper - - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddr, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - server := msgserver.NewMsgServerImpl(keeper) - err = RegisterContractUtil(server, wctx, contractAddr.String(), nil) - require.NoError(t, err) - - // First register pair - batchContractPairs := []types.BatchContractPair{} - batchContractPairs = append(batchContractPairs, types.BatchContractPair{ - ContractAddr: contractAddr.String(), - Pairs: []*types.Pair{&keepertest.TestPair}, - }) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: keepertest.TestAccount, - Batchcontractpair: batchContractPairs, - }) - require.NoError(t, err) // Test updated tick size tickUpdates := []types.TickSize{} tickUpdates = append(tickUpdates, types.TickSize{ - ContractAddr: contractAddr.String(), - Pair: &keepertest.TestPair, - Ticksize: sdk.MustNewDecFromStr("0.1"), - }) - _, err = server.UpdatePriceTickSize(wctx, &types.MsgUpdatePriceTickSize{ - Creator: keepertest.TestAccount, - TickSizeList: tickUpdates, - }) - require.NoError(t, err) - - storedTickSize, _ := keeper.GetPriceTickSizeForPair(ctx, contractAddr.String(), keepertest.TestPair) - require.Equal(t, sdk.MustNewDecFromStr("0.1"), storedTickSize) -} - -func TestUpdatePriceTickSizeInvalidMsg(t *testing.T) { - // Instantiate and get contract address - testApp := keepertest.TestApp() - ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - wctx := sdk.WrapSDKContext(ctx) - keeper := testApp.DexKeeper - - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddr, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - server := msgserver.NewMsgServerImpl(keeper) - err = RegisterContractUtil(server, wctx, contractAddr.String(), nil) - require.NoError(t, err) - // First register pair - batchContractPairs := []types.BatchContractPair{} - batchContractPairs = append(batchContractPairs, types.BatchContractPair{ - ContractAddr: contractAddr.String(), - Pairs: []*types.Pair{&keepertest.TestPair}, - }) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: keepertest.TestAccount, - Batchcontractpair: batchContractPairs, - }) - require.NoError(t, err) - - // Test with empty creator address - tickUpdates := []types.TickSize{} - tickUpdates = append(tickUpdates, types.TickSize{ - ContractAddr: contractAddr.String(), + ContractAddr: TestContractA, Pair: &keepertest.TestPair, Ticksize: sdk.MustNewDecFromStr("0.1"), }) - _, err = server.UpdatePriceTickSize(wctx, &types.MsgUpdatePriceTickSize{ - Creator: "", - TickSizeList: tickUpdates, - }) - require.NotNil(t, err) - - // Test with empty msg - tickUpdates = []types.TickSize{} - _, err = server.UpdatePriceTickSize(wctx, &types.MsgUpdatePriceTickSize{ + _, err := server.UpdatePriceTickSize(wctx, &types.MsgUpdatePriceTickSize{ Creator: keepertest.TestAccount, TickSizeList: tickUpdates, }) - require.NotNil(t, err) - - // Test with invalid Creator address - tickUpdates = []types.TickSize{} - tickUpdates = append(tickUpdates, types.TickSize{ - ContractAddr: contractAddr.String(), - Pair: &keepertest.TestPair, - Ticksize: sdk.MustNewDecFromStr("0.1"), - }) - _, err = server.UpdatePriceTickSize(wctx, &types.MsgUpdatePriceTickSize{ - Creator: "invalidAddress", - TickSizeList: tickUpdates, - }) - require.NotNil(t, err) - - // Test with empty contract address - tickUpdates = []types.TickSize{} - tickUpdates = append(tickUpdates, types.TickSize{ - ContractAddr: "", - Pair: &keepertest.TestPair, - Ticksize: sdk.MustNewDecFromStr("0.1"), - }) - _, err = server.UpdatePriceTickSize(wctx, &types.MsgUpdatePriceTickSize{ - Creator: keepertest.TestAccount, - TickSizeList: tickUpdates, - }) - require.NotNil(t, err) - - // Test with nil pair - tickUpdates = []types.TickSize{} - tickUpdates = append(tickUpdates, types.TickSize{ - ContractAddr: "", - Pair: nil, - Ticksize: sdk.MustNewDecFromStr("0.1"), - }) - _, err = server.UpdatePriceTickSize(wctx, &types.MsgUpdatePriceTickSize{ - Creator: keepertest.TestAccount, - TickSizeList: tickUpdates, - }) - require.NotNil(t, err) -} - -// Test only contract creator can update tick size for contract -func TestInvalidUpdatePriceTickSizeCreator(t *testing.T) { - // Instantiate and get contract address - testApp := keepertest.TestApp() - ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - wctx := sdk.WrapSDKContext(ctx) - keeper := testApp.DexKeeper - - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddr, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - server := msgserver.NewMsgServerImpl(keeper) - err = RegisterContractUtil(server, wctx, contractAddr.String(), nil) - require.NoError(t, err) - - // First register pair - batchContractPairs := []types.BatchContractPair{} - batchContractPairs = append(batchContractPairs, types.BatchContractPair{ - ContractAddr: contractAddr.String(), - Pairs: []*types.Pair{&keepertest.TestPair}, - }) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: keepertest.TestAccount, - Batchcontractpair: batchContractPairs, - }) - require.NoError(t, err) - - // Test invalid tx creator - tickUpdates := []types.TickSize{} - tickUpdates = append(tickUpdates, types.TickSize{ - ContractAddr: contractAddr.String(), - Pair: &keepertest.TestPair, - Ticksize: sdk.MustNewDecFromStr("0.1"), - }) - _, err = server.UpdatePriceTickSize(wctx, &types.MsgUpdatePriceTickSize{ - Creator: "sei18rrckuelmacz4fv4v2hl9t3kaw7mm4wpe8v36m", - TickSizeList: tickUpdates, - }) - require.NotNil(t, err) + require.EqualError(t, err, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated").Error()) } diff --git a/x/dex/keeper/msgserver/msg_server_update_quantity_tick_size.go b/x/dex/keeper/msgserver/msg_server_update_quantity_tick_size.go index 29cee17d0d..f4e948a54d 100644 --- a/x/dex/keeper/msgserver/msg_server_update_quantity_tick_size.go +++ b/x/dex/keeper/msgserver/msg_server_update_quantity_tick_size.go @@ -3,35 +3,10 @@ package msgserver import ( "context" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/sei-protocol/sei-chain/x/dex/types" ) func (k msgServer) UpdateQuantityTickSize(goCtx context.Context, msg *types.MsgUpdateQuantityTickSize) (*types.MsgUpdateTickSizeResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - - // Validation such that only the user who stored the code can update tick size - for _, tickSize := range msg.TickSizeList { - contractAddr := tickSize.ContractAddr - contractInfo, err := k.GetContract(ctx, contractAddr) - if err != nil { - return nil, err - } - - if msg.Creator != contractInfo.Creator { - return nil, sdkerrors.ErrUnauthorized - } - - err = k.SetQuantityTickSizeForPair(ctx, tickSize.ContractAddr, *tickSize.Pair, tickSize.Ticksize) - if err != nil { - return nil, err - } - } - - return &types.MsgUpdateTickSizeResponse{}, nil + return nil, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated") } diff --git a/x/dex/keeper/msgserver/msg_server_update_quantity_tick_size_test.go b/x/dex/keeper/msgserver/msg_server_update_quantity_tick_size_test.go index 35bcfb6dee..eccbf9e454 100644 --- a/x/dex/keeper/msgserver/msg_server_update_quantity_tick_size_test.go +++ b/x/dex/keeper/msgserver/msg_server_update_quantity_tick_size_test.go @@ -2,19 +2,16 @@ package msgserver_test import ( "context" - "io/ioutil" "testing" "time" - wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" - wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" keepertest "github.com/sei-protocol/sei-chain/testutil/keeper" dexcache "github.com/sei-protocol/sei-chain/x/dex/cache" "github.com/sei-protocol/sei-chain/x/dex/keeper/msgserver" "github.com/sei-protocol/sei-chain/x/dex/types" dexutils "github.com/sei-protocol/sei-chain/x/dex/utils" - minttypes "github.com/sei-protocol/sei-chain/x/mint/types" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" ) @@ -27,224 +24,18 @@ func TestUpdateQuantityTickSize(t *testing.T) { wctx := sdk.WrapSDKContext(ctx) keeper := testApp.DexKeeper - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddr, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - server := msgserver.NewMsgServerImpl(keeper) - err = RegisterContractUtil(server, wctx, contractAddr.String(), nil) - require.NoError(t, err) - - // First register pair - batchContractPairs := []types.BatchContractPair{} - batchContractPairs = append(batchContractPairs, types.BatchContractPair{ - ContractAddr: contractAddr.String(), - Pairs: []*types.Pair{&keepertest.TestPair}, - }) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: keepertest.TestAccount, - Batchcontractpair: batchContractPairs, - }) - require.NoError(t, err) // Test updated tick size tickUpdates := []types.TickSize{} tickUpdates = append(tickUpdates, types.TickSize{ - ContractAddr: contractAddr.String(), - Pair: &keepertest.TestPair, - Ticksize: sdk.MustNewDecFromStr("0.1"), - }) - _, err = server.UpdateQuantityTickSize(wctx, &types.MsgUpdateQuantityTickSize{ - Creator: keepertest.TestAccount, - TickSizeList: tickUpdates, - }) - require.NoError(t, err) - - storedTickSize, _ := keeper.GetQuantityTickSizeForPair(ctx, contractAddr.String(), keepertest.TestPair) - require.Equal(t, sdk.MustNewDecFromStr("0.1"), storedTickSize) -} - -func TestUpdateQuantityTickSizeInvalidMsg(t *testing.T) { - // Instantiate and get contract address - testApp := keepertest.TestApp() - ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - wctx := sdk.WrapSDKContext(ctx) - keeper := testApp.DexKeeper - - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddr, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - server := msgserver.NewMsgServerImpl(keeper) - err = RegisterContractUtil(server, wctx, contractAddr.String(), nil) - require.NoError(t, err) - // First register pair - batchContractPairs := []types.BatchContractPair{} - batchContractPairs = append(batchContractPairs, types.BatchContractPair{ - ContractAddr: contractAddr.String(), - Pairs: []*types.Pair{&keepertest.TestPair}, - }) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: keepertest.TestAccount, - Batchcontractpair: batchContractPairs, - }) - require.NoError(t, err) - - // Test with empty creator address - tickUpdates := []types.TickSize{} - tickUpdates = append(tickUpdates, types.TickSize{ - ContractAddr: contractAddr.String(), - Pair: &keepertest.TestPair, - Ticksize: sdk.MustNewDecFromStr("0.1"), - }) - _, err = server.UpdateQuantityTickSize(wctx, &types.MsgUpdateQuantityTickSize{ - Creator: "", - TickSizeList: tickUpdates, - }) - require.NotNil(t, err) - - // Test with empty msg - tickUpdates = []types.TickSize{} - _, err = server.UpdateQuantityTickSize(wctx, &types.MsgUpdateQuantityTickSize{ - Creator: keepertest.TestAccount, - TickSizeList: tickUpdates, - }) - require.NotNil(t, err) - - // Test with invalid Creator address - tickUpdates = []types.TickSize{} - tickUpdates = append(tickUpdates, types.TickSize{ - ContractAddr: contractAddr.String(), - Pair: &keepertest.TestPair, - Ticksize: sdk.MustNewDecFromStr("0.1"), - }) - _, err = server.UpdateQuantityTickSize(wctx, &types.MsgUpdateQuantityTickSize{ - Creator: "invalidAddress", - TickSizeList: tickUpdates, - }) - require.NotNil(t, err) - - // Test with empty contract address - tickUpdates = []types.TickSize{} - tickUpdates = append(tickUpdates, types.TickSize{ - ContractAddr: "", + ContractAddr: TestContractA, Pair: &keepertest.TestPair, Ticksize: sdk.MustNewDecFromStr("0.1"), }) - _, err = server.UpdateQuantityTickSize(wctx, &types.MsgUpdateQuantityTickSize{ + _, err := server.UpdateQuantityTickSize(wctx, &types.MsgUpdateQuantityTickSize{ Creator: keepertest.TestAccount, TickSizeList: tickUpdates, }) - require.NotNil(t, err) - - // Test with nil pair - tickUpdates = []types.TickSize{} - tickUpdates = append(tickUpdates, types.TickSize{ - ContractAddr: "", - Pair: nil, - Ticksize: sdk.MustNewDecFromStr("0.1"), - }) - _, err = server.UpdateQuantityTickSize(wctx, &types.MsgUpdateQuantityTickSize{ - Creator: keepertest.TestAccount, - TickSizeList: tickUpdates, - }) - require.NotNil(t, err) -} - -// Test only contract creator can update tick size for contract -func TestInvalidUpdateQuantityTickSizeCreator(t *testing.T) { - // Instantiate and get contract address - testApp := keepertest.TestApp() - ctx := testApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - ctx = ctx.WithContext(context.WithValue(ctx.Context(), dexutils.DexMemStateContextKey, dexcache.NewMemState(testApp.GetMemKey(types.MemStoreKey)))) - wctx := sdk.WrapSDKContext(ctx) - keeper := testApp.DexKeeper - - testAccount, _ := sdk.AccAddressFromBech32("sei1yezq49upxhunjjhudql2fnj5dgvcwjj87pn2wx") - amounts := sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000000)), sdk.NewCoin("uusdc", sdk.NewInt(100000000))) - bankkeeper := testApp.BankKeeper - bankkeeper.MintCoins(ctx, minttypes.ModuleName, amounts) - bankkeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, testAccount, amounts) - wasm, err := ioutil.ReadFile("../../testdata/mars.wasm") - if err != nil { - panic(err) - } - wasmKeeper := testApp.WasmKeeper - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(&wasmKeeper) - var perm *wasmtypes.AccessConfig - codeId, err := contractKeeper.Create(ctx, testAccount, wasm, perm) - if err != nil { - panic(err) - } - contractAddr, _, err := contractKeeper.Instantiate(ctx, codeId, testAccount, testAccount, []byte(GOOD_CONTRACT_INSTANTIATE), "test", - sdk.NewCoins(sdk.NewCoin("usei", sdk.NewInt(100000)))) - if err != nil { - panic(err) - } - - server := msgserver.NewMsgServerImpl(keeper) - err = RegisterContractUtil(server, wctx, contractAddr.String(), nil) - require.NoError(t, err) - - // First register pair - batchContractPairs := []types.BatchContractPair{} - batchContractPairs = append(batchContractPairs, types.BatchContractPair{ - ContractAddr: contractAddr.String(), - Pairs: []*types.Pair{&keepertest.TestPair}, - }) - _, err = server.RegisterPairs(wctx, &types.MsgRegisterPairs{ - Creator: keepertest.TestAccount, - Batchcontractpair: batchContractPairs, - }) - require.NoError(t, err) - - // Test invalid tx creator - tickUpdates := []types.TickSize{} - tickUpdates = append(tickUpdates, types.TickSize{ - ContractAddr: contractAddr.String(), - Pair: &keepertest.TestPair, - Ticksize: sdk.MustNewDecFromStr("0.1"), - }) - _, err = server.UpdateQuantityTickSize(wctx, &types.MsgUpdateQuantityTickSize{ - Creator: "sei18rrckuelmacz4fv4v2hl9t3kaw7mm4wpe8v36m", - TickSizeList: tickUpdates, - }) - require.NotNil(t, err) + require.EqualError(t, err, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "deprecated").Error()) } diff --git a/x/dex/migrations/v17_to_v18.go b/x/dex/migrations/v17_to_v18.go new file mode 100644 index 0000000000..7e6448bac9 --- /dev/null +++ b/x/dex/migrations/v17_to_v18.go @@ -0,0 +1,33 @@ +package migrations + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/sei-protocol/sei-chain/x/dex/keeper" + dextypes "github.com/sei-protocol/sei-chain/x/dex/types" +) + +func V17ToV18(ctx sdk.Context, dexkeeper keeper.Keeper) error { + // iterate over all contracts and unregister them + for _, c := range dexkeeper.GetAllContractInfo(ctx) { + if err := dexkeeper.DoUnregisterContractWithRefund(ctx, c); err != nil { + return err + } + } + // get module address + dexAddr := dexkeeper.AccountKeeper.GetModuleAddress(dextypes.ModuleName) + // send usei to the feecollector + useiCoins := dexkeeper.BankKeeper.GetBalance(ctx, dexAddr, sdk.MustGetBaseDenom()) + if err := dexkeeper.BankKeeper.SendCoinsFromModuleToModule(ctx, dextypes.ModuleName, authtypes.FeeCollectorName, sdk.NewCoins(useiCoins)); err != nil { + return err + } + // get bank balances remaining for module + balances := dexkeeper.BankKeeper.GetAllBalances(ctx, dexAddr) + // update accountkeeper to give dex burner perms + dexkeeper.CreateModuleAccount(ctx) + // burn all remaining module balances - need burner perms + if err := dexkeeper.BankKeeper.BurnCoins(ctx, dextypes.ModuleName, balances); err != nil { + return err + } + return nil +} diff --git a/x/dex/migrations/v17_to_v18_test.go b/x/dex/migrations/v17_to_v18_test.go new file mode 100644 index 0000000000..cec6d67bb5 --- /dev/null +++ b/x/dex/migrations/v17_to_v18_test.go @@ -0,0 +1,62 @@ +package migrations_test + +import ( + "testing" + "time" + + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/sei-protocol/sei-chain/app" + keepertest "github.com/sei-protocol/sei-chain/testutil/keeper" + "github.com/sei-protocol/sei-chain/x/dex/migrations" + "github.com/sei-protocol/sei-chain/x/dex/types" + "github.com/stretchr/testify/require" +) + +func TestMigrate17to18(t *testing.T) { + tm := time.Now().UTC() + valPub := secp256k1.GenPrivKey().PubKey() + + testWrapper := app.NewTestWrapper(t, tm, valPub, false) + + testAddr := sdk.MustAccAddressFromBech32(keepertest.TestAccount) + + testWrapper.FundAcc(testAddr, sdk.NewCoins(sdk.NewCoin(sdk.MustGetBaseDenom(), sdk.NewInt(100000)))) + testWrapper.FundAcc(testAddr, sdk.NewCoins(sdk.NewCoin("ueth", sdk.NewInt(100)))) + + dexkeeper, ctx := testWrapper.App.DexKeeper, testWrapper.Ctx + bal := dexkeeper.BankKeeper.GetBalance(ctx, testAddr, sdk.MustGetBaseDenom()) + require.Equal(t, int64(100000), bal.Amount.Int64()) + // add contract rent + rentAmt := int64(10000) + err := dexkeeper.BankKeeper.SendCoins(ctx, testAddr, dexkeeper.AccountKeeper.GetModuleAddress(types.ModuleName), sdk.NewCoins(sdk.NewCoin(sdk.MustGetBaseDenom(), sdk.NewInt(rentAmt)))) + require.NoError(t, err) + + contract := &types.ContractInfoV2{ContractAddr: keepertest.TestContract, Creator: keepertest.TestAccount, RentBalance: uint64(rentAmt)} + err = dexkeeper.SetContract(ctx, contract) + require.NoError(t, err) + // add some balance to the module just bc + err = dexkeeper.BankKeeper.SendCoins(ctx, testAddr, dexkeeper.AccountKeeper.GetModuleAddress(types.ModuleName), sdk.NewCoins(sdk.NewCoin("ueth", sdk.NewInt(10)), sdk.NewCoin(sdk.MustGetBaseDenom(), sdk.NewInt(1000)))) + require.NoError(t, err) + + supplyUseiInitial := dexkeeper.BankKeeper.GetSupply(ctx, sdk.MustGetBaseDenom()) + + // do migration + err = migrations.V17ToV18(ctx, dexkeeper) + require.NoError(t, err) + + // user refunded rent now has 99000usei and 90ueth + bals := dexkeeper.BankKeeper.GetAllBalances(ctx, testAddr) + require.Equal(t, sdk.NewCoins(sdk.NewCoin("ueth", sdk.NewInt(90)), sdk.NewCoin(sdk.MustGetBaseDenom(), sdk.NewInt(99000))), bals) + // feecollector gets 1000usei + bals = dexkeeper.BankKeeper.GetAllBalances(ctx, dexkeeper.AccountKeeper.GetModuleAddress(authtypes.FeeCollectorName)) + require.Equal(t, sdk.NewCoins(sdk.NewCoin(sdk.MustGetBaseDenom(), sdk.NewInt(1000))), bals) + // ueth supply decreased due to burn + supply := dexkeeper.BankKeeper.GetSupply(ctx, "ueth") + require.Equal(t, sdk.NewInt(90), supply.Amount) + // usei supply unchanged + supplyUseiFinal := dexkeeper.BankKeeper.GetSupply(ctx, sdk.MustGetBaseDenom()) + require.Equal(t, supplyUseiInitial, supplyUseiFinal) + +} diff --git a/x/dex/module.go b/x/dex/module.go index 175125c7bb..966699406e 100644 --- a/x/dex/module.go +++ b/x/dex/module.go @@ -209,6 +209,12 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { _ = cfg.RegisterMigration(types.ModuleName, 15, func(ctx sdk.Context) error { return migrations.V15ToV16(ctx, am.keeper) }) + _ = cfg.RegisterMigration(types.ModuleName, 16, func(ctx sdk.Context) error { + return nil + }) + _ = cfg.RegisterMigration(types.ModuleName, 17, func(ctx sdk.Context) error { + return migrations.V17ToV18(ctx, am.keeper) + }) } // RegisterInvariants registers the capability module's invariants. @@ -233,7 +239,7 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw } // ConsensusVersion implements ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return 16 } +func (AppModule) ConsensusVersion() uint64 { return 18 } // BeginBlock executes all ABCI BeginBlock logic respective to the capability module. func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) {