diff --git a/CHANGELOG.md b/CHANGELOG.md index c8e64af8c34..940c70f6376 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,6 +88,8 @@ Ref: https://keepachangelog.com/en/1.0.0/ The information can now be accessed using the BankKeeper. Setting can be done using MsgSetSendEnabled as a governance proposal. A SendEnabled query has been added to both GRPC and CLI. +* (appModule) Remove `Route`, `QuerierRoute` and `LegacyQuerierHandler` from AppModule Interface. +* (x/modules) Remove all LegacyQueries and related code from modules ### CLI Breaking Changes diff --git a/UPGRADING.md b/UPGRADING.md index b299ccd4f30..2af7041ee49 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -4,6 +4,12 @@ This guide provides instructions for upgrading to specific versions of Cosmos SD ## [Unreleased] +### AppModule Interface + +Remove `Querier`, `Route` and `LegacyQuerier` from the app module interface. This removes and fully deprecates all legacy queriers. All modules no longer support the REST API previously known as the LCD, and the `sdk.Msg#Route` method won't be used anymore. + + + ### SimApp SimApp's `app.go` is using App Wiring, the dependency injection framework of the Cosmos SDK. diff --git a/simapp/app.go b/simapp/app.go index 407449b302e..3196951407c 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -274,7 +274,6 @@ func NewSimApp( // app.ModuleManager.SetOrderMigrations(custom order) app.ModuleManager.RegisterInvariants(app.CrisisKeeper) - app.ModuleManager.RegisterRoutes(app.Router(), app.QueryRouter(), app.legacyAmino) // RegisterUpgradeHandlers is used for registering any on-chain upgrades. // Make sure it's called after `app.ModuleManager` and `app.configurator` are set. diff --git a/simapp/app_legacy.go b/simapp/app_legacy.go index 2a8318363be..7a41c6812cf 100644 --- a/simapp/app_legacy.go +++ b/simapp/app_legacy.go @@ -419,7 +419,6 @@ func NewSimApp( // app.ModuleManager.SetOrderMigrations(custom order) app.ModuleManager.RegisterInvariants(app.CrisisKeeper) - app.ModuleManager.RegisterRoutes(app.Router(), app.QueryRouter(), encodingConfig.Amino) app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter()) app.ModuleManager.RegisterServices(app.configurator) diff --git a/types/module/module.go b/types/module/module.go index bbf4abcadba..da4719fb7fa 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -152,15 +152,6 @@ type AppModule interface { // registers RegisterInvariants(sdk.InvariantRegistry) - // Deprecated: use RegisterServices - Route() sdk.Route - - // Deprecated: use RegisterServices - QuerierRoute() string - - // Deprecated: use RegisterServices - LegacyQuerierHandler(*codec.LegacyAmino) sdk.Querier - // RegisterServices allows a module to register services RegisterServices(Configurator) @@ -288,18 +279,6 @@ func (m *Manager) RegisterInvariants(ir sdk.InvariantRegistry) { } } -// RegisterRoutes registers all module routes and module querier routes -func (m *Manager) RegisterRoutes(router sdk.Router, queryRouter sdk.QueryRouter, legacyQuerierCdc *codec.LegacyAmino) { - for _, module := range m.Modules { - if r := module.Route(); !r.Empty() { - router.AddRoute(r) - } - if r := module.QuerierRoute(); r != "" { - queryRouter.AddRoute(r, module.LegacyQuerierHandler(legacyQuerierCdc)) - } - } -} - // RegisterServices registers all module services func (m *Manager) RegisterServices(cfg Configurator) { for _, module := range m.Modules { diff --git a/types/module/module_test.go b/types/module/module_test.go index 926a4a4ab3f..2f52b0dbbc0 100644 --- a/types/module/module_test.go +++ b/types/module/module_test.go @@ -73,10 +73,6 @@ func TestGenesisOnlyAppModule(t *testing.T) { mockInvariantRegistry := mocks.NewMockInvariantRegistry(mockCtrl) goam := module.NewGenesisOnlyAppModule(mockModule) - require.True(t, goam.Route().Empty()) - require.Empty(t, goam.QuerierRoute()) - require.Nil(t, goam.LegacyQuerierHandler(nil)) - // no-op goam.RegisterInvariants(mockInvariantRegistry) } @@ -129,37 +125,6 @@ func TestManager_RegisterInvariants(t *testing.T) { mm.RegisterInvariants(mockInvariantRegistry) } -func TestManager_RegisterRoutes(t *testing.T) { - mockCtrl := gomock.NewController(t) - t.Cleanup(mockCtrl.Finish) - - mockAppModule1 := mocks.NewMockAppModule(mockCtrl) - mockAppModule2 := mocks.NewMockAppModule(mockCtrl) - mockAppModule1.EXPECT().Name().Times(2).Return("module1") - mockAppModule2.EXPECT().Name().Times(2).Return("module2") - mm := module.NewManager(mockAppModule1, mockAppModule2) - require.NotNil(t, mm) - require.Equal(t, 2, len(mm.Modules)) - - router := mocks.NewMockRouter(mockCtrl) - noopHandler := sdk.Handler(func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { return nil, nil }) - route1 := sdk.NewRoute("route1", noopHandler) - route2 := sdk.NewRoute("", noopHandler) - mockAppModule1.EXPECT().Route().Times(1).Return(route1) - mockAppModule2.EXPECT().Route().Times(1).Return(route2) - router.EXPECT().AddRoute(gomock.Any()).Times(1) // Use of Any due to limitations to compare Functions as the sdk.Handler - - queryRouter := mocks.NewMockQueryRouter(mockCtrl) - mockAppModule1.EXPECT().QuerierRoute().Times(1).Return("querierRoute1") - mockAppModule2.EXPECT().QuerierRoute().Times(1).Return("") - handler3 := sdk.Querier(nil) - amino := codec.NewLegacyAmino() - mockAppModule1.EXPECT().LegacyQuerierHandler(amino).Times(1).Return(handler3) - queryRouter.EXPECT().AddRoute(gomock.Eq("querierRoute1"), gomock.Eq(handler3)).Times(1) - - mm.RegisterRoutes(router, queryRouter, amino) -} - func TestManager_RegisterQueryServices(t *testing.T) { mockCtrl := gomock.NewController(t) t.Cleanup(mockCtrl.Finish) diff --git a/x/auth/keeper/querier.go b/x/auth/keeper/querier.go deleted file mode 100644 index 130aaacda9e..00000000000 --- a/x/auth/keeper/querier.go +++ /dev/null @@ -1,61 +0,0 @@ -package keeper - -import ( - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// NewQuerier creates a querier for auth REST endpoints -func NewQuerier(k AccountKeeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - switch path[0] { - case types.QueryAccount: - return queryAccount(ctx, req, k, legacyQuerierCdc) - - case types.QueryParams: - return queryParams(ctx, k, legacyQuerierCdc) - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown query path: %s", path[0]) - } - } -} - -func queryAccount(ctx sdk.Context, req abci.RequestQuery, k AccountKeeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryAccountRequest - if err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - addr, err := sdk.AccAddressFromBech32(params.Address) - if err != nil { - return nil, err - } - - account := k.GetAccount(ctx, addr) - if account == nil { - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", params.Address) - } - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, account) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryParams(ctx sdk.Context, k AccountKeeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - params := k.GetParams(ctx) - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, params) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} diff --git a/x/auth/keeper/querier_test.go b/x/auth/keeper/querier_test.go deleted file mode 100644 index 7239d18df98..00000000000 --- a/x/auth/keeper/querier_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package keeper_test - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/codec" - - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/testutil/testdata" - keep "github.com/cosmos/cosmos-sdk/x/auth/keeper" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -func (suite *KeeperTestSuite) TestQueryAccount() { - ctx := suite.ctx - legacyQuerierCdc := codec.NewAminoCodec(suite.encCfg.Amino) - - req := abci.RequestQuery{ - Path: "", - Data: []byte{}, - } - - path := []string{types.QueryAccount} - querier := keep.NewQuerier(suite.accountKeeper, legacyQuerierCdc.LegacyAmino) - - bz, err := querier(ctx, []string{"other"}, req) - suite.Require().Error(err) - suite.Require().Nil(bz) - - req = abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAccount), - Data: []byte{}, - } - res, err := querier(ctx, path, req) - suite.Require().Error(err) - suite.Require().Nil(res) - - req.Data = legacyQuerierCdc.MustMarshalJSON(&types.QueryAccountRequest{Address: ""}) - res, err = querier(ctx, path, req) - suite.Require().Error(err) - suite.Require().Nil(res) - - _, _, addr := testdata.KeyTestPubAddr() - req.Data = legacyQuerierCdc.MustMarshalJSON(&types.QueryAccountRequest{Address: addr.String()}) - res, err = querier(ctx, path, req) - suite.Require().Error(err) - suite.Require().Nil(res) - - suite.accountKeeper.SetAccount(ctx, suite.accountKeeper.NewAccountWithAddress(ctx, addr)) - res, err = querier(ctx, path, req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - - res, err = querier(ctx, path, req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - - var account types.AccountI - err2 := legacyQuerierCdc.LegacyAmino.UnmarshalJSON(res, &account) - suite.Require().Nil(err2) -} diff --git a/x/auth/module.go b/x/auth/module.go index 52052b362a8..2505e44bbc6 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -118,21 +118,6 @@ func (AppModule) Name() string { // RegisterInvariants performs a no-op. func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// Deprecated: Route returns the message routing key for the auth module. -func (AppModule) Route() sdk.Route { - return sdk.Route{} -} - -// QuerierRoute returns the auth module's querier route name. -func (AppModule) QuerierRoute() string { - return types.QuerierRoute -} - -// LegacyQuerierHandler returns the auth module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return keeper.NewQuerier(am.accountKeeper, legacyQuerierCdc) -} - // RegisterServices registers a GRPC query service to respond to the // module-specific GRPC queries. func (am AppModule) RegisterServices(cfg module.Configurator) { diff --git a/x/auth/types/keys.go b/x/auth/types/keys.go index 0a3582ca294..7dc4903ba34 100644 --- a/x/auth/types/keys.go +++ b/x/auth/types/keys.go @@ -13,9 +13,6 @@ const ( // FeeCollectorName the root string for the fee collector account address FeeCollectorName = "fee_collector" - - // QuerierRoute is the querier route for auth - QuerierRoute = ModuleName ) var ( diff --git a/x/auth/vesting/module.go b/x/auth/vesting/module.go index b893e160c6f..0fb256467c7 100644 --- a/x/auth/vesting/module.go +++ b/x/auth/vesting/module.go @@ -92,25 +92,11 @@ func NewAppModule(ak keeper.AccountKeeper, bk types.BankKeeper) AppModule { // RegisterInvariants performs a no-op; there are no invariants to enforce. func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// Deprecated: Route returns the module's message router and handler. -func (am AppModule) Route() sdk.Route { - return sdk.Route{} -} - -// QuerierRoute returns an empty string as the module contains no query -// functionality. -func (AppModule) QuerierRoute() string { return "" } - // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), NewMsgServerImpl(am.accountKeeper, am.bankKeeper)) } -// LegacyQuerierHandler performs a no-op. -func (am AppModule) LegacyQuerierHandler(_ *codec.LegacyAmino) sdk.Querier { - return nil -} - // InitGenesis performs a no-op. func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} diff --git a/x/authz/module/module.go b/x/authz/module/module.go index 29c12c7a5bc..bced6e7a891 100644 --- a/x/authz/module/module.go +++ b/x/authz/module/module.go @@ -128,23 +128,10 @@ func (AppModule) Name() string { // RegisterInvariants does nothing, there are no invariants to enforce func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// Deprecated: Route returns the message routing key for the authz module. -func (am AppModule) Route() sdk.Route { - return sdk.Route{} -} - func (am AppModule) NewHandler() sdk.Handler { return nil } -// QuerierRoute returns the route we respond to for abci queries -func (AppModule) QuerierRoute() string { return "" } - -// LegacyQuerierHandler returns the authz module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return nil -} - // InitGenesis performs genesis initialization for the authz module. It returns // no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { diff --git a/x/bank/keeper/querier.go b/x/bank/keeper/querier.go deleted file mode 100644 index e64321b6c0a..00000000000 --- a/x/bank/keeper/querier.go +++ /dev/null @@ -1,121 +0,0 @@ -package keeper - -import ( - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// NewQuerier returns a new sdk.Keeper instance. -func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - switch path[0] { - case types.QueryBalance: - return queryBalance(ctx, req, k, legacyQuerierCdc) - - case types.QueryAllBalances: - return queryAllBalance(ctx, req, k, legacyQuerierCdc) - - case types.QueryTotalSupply: - return queryTotalSupply(ctx, req, k, legacyQuerierCdc) - - case types.QuerySupplyOf: - return querySupplyOf(ctx, req, k, legacyQuerierCdc) - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint: %s", types.ModuleName, path[0]) - } - } -} - -func queryBalance(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryBalanceRequest - - if err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - address, err := sdk.AccAddressFromBech32(params.Address) - if err != nil { - return nil, err - } - - balance := k.GetBalance(ctx, address, params.Denom) - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, balance) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryAllBalance(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryAllBalancesRequest - - if err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - address, err := sdk.AccAddressFromBech32(params.Address) - if err != nil { - return nil, err - } - - balances := k.GetAllBalances(ctx, address) - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, balances) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryTotalSupply(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryTotalSupplyRequest - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - totalSupply, pageRes, err := k.GetPaginatedTotalSupply(ctx, params.Pagination) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - supplyRes := &types.QueryTotalSupplyResponse{ - Supply: totalSupply, - Pagination: pageRes, - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, supplyRes) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func querySupplyOf(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QuerySupplyOfParams - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - amount := k.GetSupply(ctx, params.Denom) - supply := sdk.NewCoin(params.Denom, amount.Amount) - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, supply) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} diff --git a/x/bank/keeper/querier_test.go b/x/bank/keeper/querier_test.go deleted file mode 100644 index 4ae12f22b14..00000000000 --- a/x/bank/keeper/querier_test.go +++ /dev/null @@ -1,167 +0,0 @@ -package keeper_test - -import ( - "fmt" - - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - "github.com/cosmos/cosmos-sdk/x/bank/keeper" - "github.com/cosmos/cosmos-sdk/x/bank/testutil" - "github.com/cosmos/cosmos-sdk/x/bank/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" -) - -func (suite *KeeperTestSuite) TestQuerier_QueryBalance() { - ctx, legacyAmino := suite.ctx, suite.encCfg.Amino - _, _, addr := testdata.KeyTestPubAddr() - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QueryBalance), - Data: []byte{}, - } - - querier := keeper.NewQuerier(suite.bankKeeper, legacyAmino) - - res, err := querier(ctx, []string{types.QueryBalance}, req) - suite.Require().NotNil(err) - suite.Require().Nil(res) - - req.Data = legacyAmino.MustMarshalJSON(types.NewQueryBalanceRequest(addr, fooDenom)) - res, err = querier(ctx, []string{types.QueryBalance}, req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - - var balance sdk.Coin - suite.Require().NoError(legacyAmino.UnmarshalJSON(res, &balance)) - suite.True(balance.IsZero()) - - origCoins := sdk.NewCoins(newFooCoin(50), newBarCoin(30)) - - suite.mockFundAccount(addr) - suite.Require().NoError(testutil.FundAccount(suite.bankKeeper, ctx, addr, origCoins)) - - res, err = querier(ctx, []string{types.QueryBalance}, req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.Require().NoError(legacyAmino.UnmarshalJSON(res, &balance)) - suite.True(balance.IsEqual(newFooCoin(50))) -} - -func (suite *KeeperTestSuite) TestQuerier_QueryAllBalances() { - ctx, legacyAmino := suite.ctx, suite.encCfg.Amino - _, _, addr := testdata.KeyTestPubAddr() - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QueryAllBalances), - Data: []byte{}, - } - - querier := keeper.NewQuerier(suite.bankKeeper, legacyAmino) - - res, err := querier(ctx, []string{types.QueryAllBalances}, req) - suite.Require().NotNil(err) - suite.Require().Nil(res) - - req.Data = legacyAmino.MustMarshalJSON(types.NewQueryAllBalancesRequest(addr, nil)) - res, err = querier(ctx, []string{types.QueryAllBalances}, req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - - var balances sdk.Coins - suite.Require().NoError(legacyAmino.UnmarshalJSON(res, &balances)) - suite.True(balances.IsZero()) - - origCoins := sdk.NewCoins(newFooCoin(50), newBarCoin(30)) - - suite.mockFundAccount(addr) - suite.Require().NoError(testutil.FundAccount(suite.bankKeeper, ctx, addr, origCoins)) - res, err = querier(ctx, []string{types.QueryAllBalances}, req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.Require().NoError(legacyAmino.UnmarshalJSON(res, &balances)) - suite.True(balances.IsEqual(origCoins)) -} - -func (suite *KeeperTestSuite) TestQuerier_QueryTotalSupply() { - ctx, legacyAmino := suite.ctx, suite.encCfg.Amino - - genesisSupply, _, err := suite.bankKeeper.GetPaginatedTotalSupply(suite.ctx, &query.PageRequest{Limit: query.MaxLimit}) - suite.Require().NoError(err) - - testCoins := sdk.NewCoins(sdk.NewInt64Coin("test", 400000000)) - - suite.mockMintCoins(mintAcc) - suite. - Require(). - NoError(suite.bankKeeper.MintCoins(ctx, minttypes.ModuleName, testCoins)) - - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QueryTotalSupply), - Data: []byte{}, - } - - querier := keeper.NewQuerier(suite.bankKeeper, legacyAmino) - - res, err := querier(ctx, []string{types.QueryTotalSupply}, req) - suite.Require().NotNil(err) - suite.Require().Nil(res) - - req.Data = legacyAmino.MustMarshalJSON(types.QueryTotalSupplyRequest{Pagination: &query.PageRequest{ - Limit: 100, - }}) - res, err = querier(ctx, []string{types.QueryTotalSupply}, req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - - var resp types.QueryTotalSupplyResponse - suite.Require().NoError(legacyAmino.UnmarshalJSON(res, &resp)) - - expectedTotalSupply := genesisSupply.Add(testCoins...) - suite.Require().Equal(expectedTotalSupply, resp.Supply) -} - -func (suite *KeeperTestSuite) TestQuerier_QueryTotalSupplyOf() { - ctx, legacyAmino := suite.ctx, suite.encCfg.Amino - test1Supply := sdk.NewInt64Coin("test1", 4000000) - test2Supply := sdk.NewInt64Coin("test2", 700000000) - expectedTotalSupply := sdk.NewCoins(test1Supply, test2Supply) - - suite.mockMintCoins(mintAcc) - suite. - Require(). - NoError(suite.bankKeeper.MintCoins(ctx, minttypes.ModuleName, expectedTotalSupply)) - - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QuerySupplyOf), - Data: []byte{}, - } - - querier := keeper.NewQuerier(suite.bankKeeper, legacyAmino) - - res, err := querier(ctx, []string{types.QuerySupplyOf}, req) - suite.Require().NotNil(err) - suite.Require().Nil(res) - - req.Data = legacyAmino.MustMarshalJSON(types.NewQuerySupplyOfParams(test1Supply.Denom)) - res, err = querier(ctx, []string{types.QuerySupplyOf}, req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - - var resp sdk.Coin - suite.Require().NoError(legacyAmino.UnmarshalJSON(res, &resp)) - suite.Require().Equal(test1Supply, resp) -} - -func (suite *KeeperTestSuite) TestQuerierRouteNotFound() { - ctx := suite.ctx - legacyAmino := suite.encCfg.Amino - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/invalid", types.ModuleName), - Data: []byte{}, - } - - querier := keeper.NewQuerier(suite.bankKeeper, legacyAmino) - _, err := querier(ctx, []string{"invalid"}, req) - suite.Error(err) -} diff --git a/x/bank/module.go b/x/bank/module.go index a25dcfbb32f..0ca4e015ebb 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -146,19 +146,9 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { keeper.RegisterInvariants(ir, am.keeper) } -// Deprecated: Route returns the message routing key for the bank module. -func (am AppModule) Route() sdk.Route { - return sdk.Route{} -} - // QuerierRoute returns the bank module's querier route name. func (AppModule) QuerierRoute() string { return types.RouterKey } -// LegacyQuerierHandler returns the bank module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return keeper.NewQuerier(am.keeper, legacyQuerierCdc) -} - // InitGenesis performs genesis initialization for the bank module. It returns // no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { diff --git a/x/bank/types/keys.go b/x/bank/types/keys.go index 09938efc927..86033a51f3e 100644 --- a/x/bank/types/keys.go +++ b/x/bank/types/keys.go @@ -16,9 +16,6 @@ const ( // RouterKey defines the module's message routing key RouterKey = ModuleName - // QuerierRoute defines the module's query routing key - QuerierRoute = ModuleName - // ModuleQueryPath defines the ABCI query path of the module ModuleQueryPath = "store/bank/key" ) diff --git a/x/capability/module.go b/x/capability/module.go index 959df84dfc3..23ecad8e7cd 100644 --- a/x/capability/module.go +++ b/x/capability/module.go @@ -108,17 +108,6 @@ func (am AppModule) Name() string { return am.AppModuleBasic.Name() } -// Deprecated: Route returns the capability module's message routing key. -func (AppModule) Route() sdk.Route { - return sdk.Route{} -} - -// QuerierRoute returns the capability module's query routing key. -func (AppModule) QuerierRoute() string { return "" } - -// LegacyQuerierHandler returns the capability module's Querier. -func (am AppModule) LegacyQuerierHandler(*codec.LegacyAmino) sdk.Querier { return nil } - // RegisterServices registers a GRPC query service to respond to the // module-specific GRPC queries. func (am AppModule) RegisterServices(module.Configurator) {} diff --git a/x/crisis/module.go b/x/crisis/module.go index 0bf0e49bbcf..0a0c2fe5582 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -132,17 +132,6 @@ func (AppModule) Name() string { // RegisterInvariants performs a no-op. func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// Deprecated: Route returns the message routing key for the crisis module. -func (am AppModule) Route() sdk.Route { - return sdk.Route{} -} - -// QuerierRoute returns no querier route. -func (AppModule) QuerierRoute() string { return "" } - -// LegacyQuerierHandler returns no sdk.Querier. -func (AppModule) LegacyQuerierHandler(*codec.LegacyAmino) sdk.Querier { return nil } - // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), am.keeper) diff --git a/x/distribution/client/common/common.go b/x/distribution/client/common/common.go index a2d5fceda0b..b8b363aea07 100644 --- a/x/distribution/client/common/common.go +++ b/x/distribution/client/common/common.go @@ -27,70 +27,6 @@ func QueryDelegationRewards(clientCtx client.Context, delAddr, valAddr string) ( return nil, 0, fmt.Errorf("failed to marshal params: %w", err) } - route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegationRewards) + route := fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QueryDelegationRewards) return clientCtx.QueryWithData(route, bz) } - -// QueryDelegatorValidators returns delegator's list of validators -// it submitted delegations to. -func QueryDelegatorValidators(clientCtx client.Context, delegatorAddr sdk.AccAddress) ([]byte, error) { - res, _, err := clientCtx.QueryWithData( - fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegatorValidators), - clientCtx.LegacyAmino.MustMarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)), - ) - return res, err -} - -// QueryValidatorCommission returns a validator's commission. -func QueryValidatorCommission(clientCtx client.Context, validatorAddr sdk.ValAddress) ([]byte, error) { - res, _, err := clientCtx.QueryWithData( - fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryValidatorCommission), - clientCtx.LegacyAmino.MustMarshalJSON(types.NewQueryValidatorCommissionParams(validatorAddr)), - ) - return res, err -} - -// WithdrawAllDelegatorRewards builds a multi-message slice to be used -// to withdraw all delegations rewards for the given delegator. -func WithdrawAllDelegatorRewards(clientCtx client.Context, delegatorAddr sdk.AccAddress) ([]sdk.Msg, error) { - // retrieve the comprehensive list of all validators which the - // delegator had submitted delegations to - bz, err := QueryDelegatorValidators(clientCtx, delegatorAddr) - if err != nil { - return nil, err - } - - var validators []sdk.ValAddress - if err := clientCtx.LegacyAmino.UnmarshalJSON(bz, &validators); err != nil { - return nil, err - } - - // build multi-message transaction - msgs := make([]sdk.Msg, 0, len(validators)) - for _, valAddr := range validators { - msg := types.NewMsgWithdrawDelegatorReward(delegatorAddr, valAddr) - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - msgs = append(msgs, msg) - } - - return msgs, nil -} - -// WithdrawValidatorRewardsAndCommission builds a two-message message slice to be -// used to withdraw both validation's commission and self-delegation reward. -func WithdrawValidatorRewardsAndCommission(validatorAddr sdk.ValAddress) ([]sdk.Msg, error) { - commissionMsg := types.NewMsgWithdrawValidatorCommission(validatorAddr) - if err := commissionMsg.ValidateBasic(); err != nil { - return nil, err - } - - // build and validate MsgWithdrawDelegatorReward - rewardMsg := types.NewMsgWithdrawDelegatorReward(sdk.AccAddress(validatorAddr.Bytes()), validatorAddr) - if err := rewardMsg.ValidateBasic(); err != nil { - return nil, err - } - - return []sdk.Msg{commissionMsg, rewardMsg}, nil -} diff --git a/x/distribution/keeper/querier.go b/x/distribution/keeper/querier.go deleted file mode 100644 index 71370e24ba5..00000000000 --- a/x/distribution/keeper/querier.go +++ /dev/null @@ -1,256 +0,0 @@ -package keeper - -import ( - "encoding/json" - - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/distribution/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - switch path[0] { - case types.QueryParams: - return queryParams(ctx, path[1:], req, k, legacyQuerierCdc) - - case types.QueryValidatorOutstandingRewards: - return queryValidatorOutstandingRewards(ctx, path[1:], req, k, legacyQuerierCdc) - - case types.QueryValidatorCommission: - return queryValidatorCommission(ctx, path[1:], req, k, legacyQuerierCdc) - - case types.QueryValidatorSlashes: - return queryValidatorSlashes(ctx, path[1:], req, k, legacyQuerierCdc) - - case types.QueryDelegationRewards: - return queryDelegationRewards(ctx, path[1:], req, k, legacyQuerierCdc) - - case types.QueryDelegatorTotalRewards: - return queryDelegatorTotalRewards(ctx, path[1:], req, k, legacyQuerierCdc) - - case types.QueryDelegatorValidators: - return queryDelegatorValidators(ctx, path[1:], req, k, legacyQuerierCdc) - - case types.QueryWithdrawAddr: - return queryDelegatorWithdrawAddress(ctx, path[1:], req, k, legacyQuerierCdc) - - case types.QueryCommunityPool: - return queryCommunityPool(ctx, path[1:], req, k, legacyQuerierCdc) - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown query path: %s", path[0]) - } - } -} - -func queryParams(ctx sdk.Context, _ []string, _ abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - params := k.GetParams(ctx) - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, params) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryValidatorOutstandingRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryValidatorOutstandingRewardsParams - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - rewards := k.GetValidatorOutstandingRewards(ctx, params.ValidatorAddress) - if rewards.GetRewards() == nil { - rewards.Rewards = sdk.DecCoins{} - } - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, rewards) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryValidatorCommission(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryValidatorCommissionParams - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - commission := k.GetValidatorAccumulatedCommission(ctx, params.ValidatorAddress) - if commission.Commission == nil { - commission.Commission = sdk.DecCoins{} - } - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, commission) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryValidatorSlashes(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryValidatorSlashesParams - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - events := make([]types.ValidatorSlashEvent, 0) - k.IterateValidatorSlashEventsBetween(ctx, params.ValidatorAddress, params.StartingHeight, params.EndingHeight, - func(height uint64, event types.ValidatorSlashEvent) (stop bool) { - events = append(events, event) - return false - }, - ) - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, events) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryDelegationRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryDelegationRewardsParams - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - // branch the context to isolate state changes - ctx, _ = ctx.CacheContext() - - val := k.stakingKeeper.Validator(ctx, params.ValidatorAddress) - if val == nil { - return nil, sdkerrors.Wrap(types.ErrNoValidatorExists, params.ValidatorAddress.String()) - } - - del := k.stakingKeeper.Delegation(ctx, params.DelegatorAddress, params.ValidatorAddress) - if del == nil { - return nil, types.ErrNoDelegationExists - } - - endingPeriod := k.IncrementValidatorPeriod(ctx, val) - rewards := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) - if rewards == nil { - rewards = sdk.DecCoins{} - } - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, rewards) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryDelegatorTotalRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryDelegatorParams - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - // branch the context to isolate state changes - ctx, _ = ctx.CacheContext() - - total := sdk.DecCoins{} - - var delRewards []types.DelegationDelegatorReward - - k.stakingKeeper.IterateDelegations( - ctx, params.DelegatorAddress, - func(_ int64, del stakingtypes.DelegationI) (stop bool) { - valAddr := del.GetValidatorAddr() - val := k.stakingKeeper.Validator(ctx, valAddr) - endingPeriod := k.IncrementValidatorPeriod(ctx, val) - delReward := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - delRewards = append(delRewards, types.NewDelegationDelegatorReward(valAddr, delReward)) - total = total.Add(delReward...) - return false - }, - ) - - totalRewards := types.NewQueryDelegatorTotalRewardsResponse(delRewards, total) - - bz, err := json.Marshal(totalRewards) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryDelegatorValidators(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryDelegatorParams - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - // branch the context to isolate state changes - ctx, _ = ctx.CacheContext() - - var validators []sdk.ValAddress - - k.stakingKeeper.IterateDelegations( - ctx, params.DelegatorAddress, - func(_ int64, del stakingtypes.DelegationI) (stop bool) { - validators = append(validators, del.GetValidatorAddr()) - return false - }, - ) - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, validators) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryDelegatorWithdrawAddress(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryDelegatorWithdrawAddrParams - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - // branch the context to isolate state changes - ctx, _ = ctx.CacheContext() - withdrawAddr := k.GetDelegatorWithdrawAddr(ctx, params.DelegatorAddress) - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, withdrawAddr) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryCommunityPool(ctx sdk.Context, _ []string, _ abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - pool := k.GetFeePoolCommunityCoins(ctx) - if pool == nil { - pool = sdk.DecCoins{} - } - - bz, err := legacyQuerierCdc.MarshalJSON(pool) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} diff --git a/x/distribution/keeper/querier_test.go b/x/distribution/keeper/querier_test.go deleted file mode 100644 index cc739bd6cf9..00000000000 --- a/x/distribution/keeper/querier_test.go +++ /dev/null @@ -1,218 +0,0 @@ -package keeper_test - -import ( - "strings" - "testing" - - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - - "github.com/cosmos/cosmos-sdk/codec" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - "github.com/cosmos/cosmos-sdk/x/distribution/testutil" - "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - "github.com/cosmos/cosmos-sdk/x/staking/teststaking" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -const custom = "custom" - -func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier) types.Params { - var params types.Params - - bz, err := querier(ctx, []string{types.QueryParams}, abci.RequestQuery{}) - require.Nil(t, err) - require.Nil(t, cdc.UnmarshalJSON(bz, ¶ms)) - - return params -} - -func getQueriedValidatorOutstandingRewards(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, validatorAddr sdk.ValAddress) sdk.DecCoins { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryValidatorOutstandingRewards}, "/"), - Data: cdc.MustMarshalJSON(types.NewQueryValidatorOutstandingRewardsParams(validatorAddr)), - } - - bz, err := querier(ctx, []string{types.QueryValidatorOutstandingRewards}, query) - require.Nil(t, err) - outstandingRewards := types.ValidatorOutstandingRewards{} - require.Nil(t, cdc.UnmarshalJSON(bz, &outstandingRewards)) - - return outstandingRewards.GetRewards() -} - -func getQueriedValidatorCommission(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, validatorAddr sdk.ValAddress) sdk.DecCoins { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryValidatorCommission}, "/"), - Data: cdc.MustMarshalJSON(types.NewQueryValidatorCommissionParams(validatorAddr)), - } - - bz, err := querier(ctx, []string{types.QueryValidatorCommission}, query) - require.Nil(t, err) - validatorCommission := types.ValidatorAccumulatedCommission{} - require.Nil(t, cdc.UnmarshalJSON(bz, &validatorCommission)) - - return validatorCommission.GetCommission() -} - -func getQueriedValidatorSlashes(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, validatorAddr sdk.ValAddress, startHeight uint64, endHeight uint64) (slashes []types.ValidatorSlashEvent) { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryValidatorSlashes}, "/"), - Data: cdc.MustMarshalJSON(types.NewQueryValidatorSlashesParams(validatorAddr, startHeight, endHeight)), - } - - bz, err := querier(ctx, []string{types.QueryValidatorSlashes}, query) - require.Nil(t, err) - require.Nil(t, cdc.UnmarshalJSON(bz, &slashes)) - - return -} - -func getQueriedDelegationRewards(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) (rewards sdk.DecCoins) { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDelegationRewards}, "/"), - Data: cdc.MustMarshalJSON(types.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr)), - } - - bz, err := querier(ctx, []string{types.QueryDelegationRewards}, query) - require.Nil(t, err) - require.Nil(t, cdc.UnmarshalJSON(bz, &rewards)) - - return -} - -func getQueriedDelegatorTotalRewards(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, delegatorAddr sdk.AccAddress) (response types.QueryDelegatorTotalRewardsResponse) { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDelegatorTotalRewards}, "/"), - Data: cdc.MustMarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)), - } - - bz, err := querier(ctx, []string{types.QueryDelegatorTotalRewards}, query) - require.Nil(t, err) - require.Nil(t, cdc.UnmarshalJSON(bz, &response)) - - return -} - -func getQueriedCommunityPool(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier) (ptr []byte) { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryCommunityPool}, ""), - Data: []byte{}, - } - - cp, err := querier(ctx, []string{types.QueryCommunityPool}, query) - require.Nil(t, err) - require.Nil(t, cdc.UnmarshalJSON(cp, &ptr)) - - return -} - -func TestQueries(t *testing.T) { - var ( - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - ) - - app, err := simtestutil.Setup(testutil.AppConfig, - &bankKeeper, - &distrKeeper, - &stakingKeeper, - ) - require.NoError(t, err) - - cdc := codec.NewLegacyAmino() - types.RegisterLegacyAminoCodec(cdc) - banktypes.RegisterLegacyAminoCodec(cdc) - - ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - - // reset fee pool - distrKeeper.SetFeePool(ctx, types.InitialFeePool()) - - addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 1, sdk.NewInt(1000000000)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addr) - valOpAddr1 := valAddrs[0] - - querier := keeper.NewQuerier(distrKeeper, cdc) - - // test param queries - params := types.Params{ - CommunityTax: sdk.NewDecWithPrec(3, 1), - BaseProposerReward: sdk.NewDecWithPrec(2, 1), - BonusProposerReward: sdk.NewDecWithPrec(1, 1), - WithdrawAddrEnabled: true, - } - - require.NoError(t, distrKeeper.SetParams(ctx, params)) - - paramsRes := getQueriedParams(t, ctx, cdc, querier) - require.Equal(t, params.CommunityTax, paramsRes.CommunityTax) - require.Equal(t, params.BaseProposerReward, paramsRes.BaseProposerReward) - require.Equal(t, params.BonusProposerReward, paramsRes.BonusProposerReward) - require.Equal(t, params.WithdrawAddrEnabled, paramsRes.WithdrawAddrEnabled) - - // test outstanding rewards query - outstandingRewards := sdk.DecCoins{{Denom: "mytoken", Amount: sdk.NewDec(3)}, {Denom: "myothertoken", Amount: sdk.NewDecWithPrec(3, 7)}} - distrKeeper.SetValidatorOutstandingRewards(ctx, valOpAddr1, types.ValidatorOutstandingRewards{Rewards: outstandingRewards}) - retOutstandingRewards := getQueriedValidatorOutstandingRewards(t, ctx, cdc, querier, valOpAddr1) - require.Equal(t, outstandingRewards, retOutstandingRewards) - - // test validator commission query - commission := sdk.DecCoins{{Denom: "token1", Amount: sdk.NewDec(4)}, {Denom: "token2", Amount: sdk.NewDec(2)}} - distrKeeper.SetValidatorAccumulatedCommission(ctx, valOpAddr1, types.ValidatorAccumulatedCommission{Commission: commission}) - retCommission := getQueriedValidatorCommission(t, ctx, cdc, querier, valOpAddr1) - require.Equal(t, commission, retCommission) - - // test delegator's total rewards query - delRewards := getQueriedDelegatorTotalRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1)) - require.Equal(t, types.QueryDelegatorTotalRewardsResponse{}, delRewards) - - // test validator slashes query with height range - slashOne := types.NewValidatorSlashEvent(3, sdk.NewDecWithPrec(5, 1)) - slashTwo := types.NewValidatorSlashEvent(7, sdk.NewDecWithPrec(6, 1)) - distrKeeper.SetValidatorSlashEvent(ctx, valOpAddr1, 3, 0, slashOne) - distrKeeper.SetValidatorSlashEvent(ctx, valOpAddr1, 7, 0, slashTwo) - slashes := getQueriedValidatorSlashes(t, ctx, cdc, querier, valOpAddr1, 0, 2) - require.Equal(t, 0, len(slashes)) - slashes = getQueriedValidatorSlashes(t, ctx, cdc, querier, valOpAddr1, 0, 5) - require.Equal(t, []types.ValidatorSlashEvent{slashOne}, slashes) - slashes = getQueriedValidatorSlashes(t, ctx, cdc, querier, valOpAddr1, 0, 10) - require.Equal(t, []types.ValidatorSlashEvent{slashOne, slashTwo}, slashes) - - // test delegation rewards query - tstaking := teststaking.NewHelper(t, ctx, stakingKeeper) - tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - tstaking.CreateValidator(valOpAddr1, valConsPk1, sdk.NewInt(100), true) - - staking.EndBlocker(ctx, stakingKeeper) - - val := stakingKeeper.Validator(ctx, valOpAddr1) - rewards := getQueriedDelegationRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1), valOpAddr1) - require.True(t, rewards.IsZero()) - initial := int64(10) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - rewards = getQueriedDelegationRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1), valOpAddr1) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, rewards) - - // test delegator's total rewards query - delRewards = getQueriedDelegatorTotalRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1)) - expectedDelReward := types.NewDelegationDelegatorReward(valOpAddr1, - sdk.DecCoins{sdk.NewInt64DecCoin("stake", 5)}) - wantDelRewards := types.NewQueryDelegatorTotalRewardsResponse( - []types.DelegationDelegatorReward{expectedDelReward}, expectedDelReward.Reward) - require.Equal(t, wantDelRewards, delRewards) - - // currently community pool hold nothing so we should return null - communityPool := getQueriedCommunityPool(t, ctx, cdc, querier) - require.Nil(t, communityPool) -} diff --git a/x/distribution/module.go b/x/distribution/module.go index 5b5eb0ac02e..26372bd876c 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -132,21 +132,6 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { keeper.RegisterInvariants(ir, am.keeper) } -// Deprecated: Route returns the message routing key for the distribution module. -func (am AppModule) Route() sdk.Route { - return sdk.Route{} -} - -// QuerierRoute returns the distribution module's querier route name. -func (AppModule) QuerierRoute() string { - return types.QuerierRoute -} - -// LegacyQuerierHandler returns the distribution module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return keeper.NewQuerier(am.keeper, legacyQuerierCdc) -} - // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) diff --git a/x/distribution/types/keys.go b/x/distribution/types/keys.go index e5e182f5ac8..07fb3d6e280 100644 --- a/x/distribution/types/keys.go +++ b/x/distribution/types/keys.go @@ -17,9 +17,6 @@ const ( // RouterKey is the message route for distribution RouterKey = ModuleName - - // QuerierRoute is the querier route for distribution - QuerierRoute = ModuleName ) // Keys for distribution store diff --git a/x/evidence/keeper/keeper_test.go b/x/evidence/keeper/keeper_test.go index a05bdbf66d0..aac0825a280 100644 --- a/x/evidence/keeper/keeper_test.go +++ b/x/evidence/keeper/keeper_test.go @@ -10,7 +10,6 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -95,12 +94,10 @@ type KeeperTestSuite struct { func (suite *KeeperTestSuite) SetupTest() { var ( - legacyAmino *codec.LegacyAmino evidenceKeeper keeper.Keeper ) app, err := simtestutil.Setup(testutil.AppConfig, - &legacyAmino, &evidenceKeeper, &suite.interfaceRegistry, &suite.accountKeeper, @@ -115,7 +112,6 @@ func (suite *KeeperTestSuite) SetupTest() { evidenceKeeper.SetRouter(router) suite.ctx = app.BaseApp.NewContext(false, tmproto.Header{Height: 1}) - suite.querier = keeper.NewQuerier(evidenceKeeper, legacyAmino) suite.app = app for i, addr := range valAddresses { diff --git a/x/evidence/keeper/querier.go b/x/evidence/keeper/querier.go deleted file mode 100644 index c1ae20d4d9c..00000000000 --- a/x/evidence/keeper/querier.go +++ /dev/null @@ -1,80 +0,0 @@ -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/evidence/exported" - "github.com/cosmos/cosmos-sdk/x/evidence/types" - - abci "github.com/tendermint/tendermint/abci/types" -) - -func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - var ( - res []byte - err error - ) - - switch path[0] { - case types.QueryEvidence: - res, err = queryEvidence(ctx, req, k, legacyQuerierCdc) - - case types.QueryAllEvidence: - res, err = queryAllEvidence(ctx, req, k, legacyQuerierCdc) - - default: - err = sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint: %s", types.ModuleName, path[0]) - } - - return res, err - } -} - -func queryEvidence(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryEvidenceRequest - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - evidence, ok := k.GetEvidence(ctx, params.EvidenceHash) - if !ok { - return nil, sdkerrors.Wrap(types.ErrNoEvidenceExists, params.EvidenceHash.String()) - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, evidence) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryAllEvidence(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryAllEvidenceParams - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - evidence := k.GetAllEvidence(ctx) - - start, end := client.Paginate(len(evidence), params.Page, params.Limit, 100) - if start < 0 || end < 0 { - evidence = []exported.Evidence{} - } else { - evidence = evidence[start:end] - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, evidence) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} diff --git a/x/evidence/keeper/querier_test.go b/x/evidence/keeper/querier_test.go deleted file mode 100644 index e15412ba2b0..00000000000 --- a/x/evidence/keeper/querier_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package keeper_test - -import ( - "strings" - - "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/x/evidence/exported" - "github.com/cosmos/cosmos-sdk/x/evidence/testutil" - "github.com/cosmos/cosmos-sdk/x/evidence/types" - - abci "github.com/tendermint/tendermint/abci/types" -) - -const ( - custom = "custom" -) - -func (suite *KeeperTestSuite) TestQuerier_QueryEvidence_Existing() { - ctx := suite.ctx.WithIsCheckTx(false) - numEvidence := 100 - - var legacyAmino *codec.LegacyAmino - err := depinject.Inject(testutil.AppConfig, &legacyAmino) - require.NoError(suite.T(), err) - - evidence := suite.populateEvidence(ctx, numEvidence) - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryEvidence}, "/"), - Data: legacyAmino.MustMarshalJSON(types.NewQueryEvidenceRequest(evidence[0].Hash())), - } - - bz, err := suite.querier(ctx, []string{types.QueryEvidence}, query) - suite.Nil(err) - suite.NotNil(bz) - - var e exported.Evidence - suite.Nil(legacyAmino.UnmarshalJSON(bz, &e)) - suite.Equal(evidence[0], e) -} - -func (suite *KeeperTestSuite) TestQuerier_QueryEvidence_NonExisting() { - ctx := suite.ctx.WithIsCheckTx(false) - numEvidence := 100 - - var cdc codec.Codec - err := depinject.Inject(testutil.AppConfig, &cdc) - require.NoError(suite.T(), err) - - suite.populateEvidence(ctx, numEvidence) - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryEvidence}, "/"), - Data: cdc.MustMarshalJSON(types.NewQueryEvidenceRequest([]byte("0000000000000000000000000000000000000000000000000000000000000000"))), - } - - bz, err := suite.querier(ctx, []string{types.QueryEvidence}, query) - suite.NotNil(err) - suite.Nil(bz) -} - -func (suite *KeeperTestSuite) TestQuerier_QueryAllEvidence() { - ctx := suite.ctx.WithIsCheckTx(false) - numEvidence := 100 - - var legacyAmino *codec.LegacyAmino - err := depinject.Inject(testutil.AppConfig, &legacyAmino) - require.NoError(suite.T(), err) - - suite.populateEvidence(ctx, numEvidence) - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryAllEvidence}, "/"), - Data: legacyAmino.MustMarshalJSON(types.NewQueryAllEvidenceParams(1, numEvidence)), - } - - bz, err := suite.querier(ctx, []string{types.QueryAllEvidence}, query) - suite.Nil(err) - suite.NotNil(bz) - - var e []exported.Evidence - suite.Nil(legacyAmino.UnmarshalJSON(bz, &e)) - suite.Len(e, numEvidence) -} - -func (suite *KeeperTestSuite) TestQuerier_QueryAllEvidence_InvalidPagination() { - ctx := suite.ctx.WithIsCheckTx(false) - numEvidence := 100 - - var legacyAmino *codec.LegacyAmino - err := depinject.Inject(testutil.AppConfig, &legacyAmino) - require.NoError(suite.T(), err) - - suite.populateEvidence(ctx, numEvidence) - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryAllEvidence}, "/"), - Data: legacyAmino.MustMarshalJSON(types.NewQueryAllEvidenceParams(0, numEvidence)), - } - - bz, err := suite.querier(ctx, []string{types.QueryAllEvidence}, query) - suite.Nil(err) - suite.NotNil(bz) - - var e []exported.Evidence - suite.Nil(legacyAmino.UnmarshalJSON(bz, &e)) - suite.Len(e, 0) -} diff --git a/x/evidence/module.go b/x/evidence/module.go index 009807e8816..03c9135a500 100644 --- a/x/evidence/module.go +++ b/x/evidence/module.go @@ -126,21 +126,6 @@ func (am AppModule) Name() string { return am.AppModuleBasic.Name() } -// Deprecated: Route returns the evidence module's message routing key. -func (am AppModule) Route() sdk.Route { - return sdk.Route{} -} - -// QuerierRoute returns the evidence module's query routing key. -func (AppModule) QuerierRoute() string { - return types.QuerierRoute -} - -// LegacyQuerierHandler returns the evidence module's Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return keeper.NewQuerier(am.keeper, legacyQuerierCdc) -} - // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) diff --git a/x/evidence/types/keys.go b/x/evidence/types/keys.go index 775fa2c021a..fb8a5fddbaf 100644 --- a/x/evidence/types/keys.go +++ b/x/evidence/types/keys.go @@ -9,9 +9,6 @@ const ( // RouterKey defines the module's message routing key RouterKey = ModuleName - - // QuerierRoute defines the module's query routing key - QuerierRoute = ModuleName ) // KVStore key prefixes diff --git a/x/feegrant/module/module.go b/x/feegrant/module/module.go index d2b50f410d7..402dc449e52 100644 --- a/x/feegrant/module/module.go +++ b/x/feegrant/module/module.go @@ -140,21 +140,6 @@ func (AppModule) Name() string { // RegisterInvariants registers the feegrant module invariants. func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) {} -// Deprecated: Route returns the message routing key for the feegrant module. -func (am AppModule) Route() sdk.Route { - return sdk.Route{} -} - -// NewHandler returns an sdk.Handler for the feegrant module. -func (am AppModule) NewHandler() sdk.Handler { - return nil -} - -// QuerierRoute returns the feegrant module's querier route name. -func (AppModule) QuerierRoute() string { - return "" -} - // InitGenesis performs genesis initialization for the feegrant module. It returns // no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, bz json.RawMessage) []abci.ValidatorUpdate { diff --git a/x/gov/keeper/querier.go b/x/gov/keeper/querier.go deleted file mode 100644 index e5aacbfb446..00000000000 --- a/x/gov/keeper/querier.go +++ /dev/null @@ -1,231 +0,0 @@ -package keeper - -// DONTCOVER - -import ( - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/gov/types" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" -) - -// NewQuerier creates a new gov Querier instance -func NewQuerier(keeper *Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - switch path[0] { - case v1.QueryParams: - return queryParams(ctx, path[1:], req, keeper, legacyQuerierCdc) - - case v1.QueryProposals: - return queryProposals(ctx, path[1:], req, keeper, legacyQuerierCdc) - - case v1.QueryProposal: - return queryProposal(ctx, path[1:], req, keeper, legacyQuerierCdc) - - case v1.QueryDeposits: - return queryDeposits(ctx, path[1:], req, keeper, legacyQuerierCdc) - - case v1.QueryDeposit: - return queryDeposit(ctx, path[1:], req, keeper, legacyQuerierCdc) - - case v1.QueryVotes: - return queryVotes(ctx, path[1:], req, keeper, legacyQuerierCdc) - - case v1.QueryVote: - return queryVote(ctx, path[1:], req, keeper, legacyQuerierCdc) - - case v1.QueryTally: - return queryTally(ctx, path[1:], req, keeper, legacyQuerierCdc) - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown query path: %s", path[0]) - } - } -} - -func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, keeper *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - switch path[0] { - case v1.ParamDeposit: - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, keeper.GetDepositParams(ctx)) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil - - case v1.ParamVoting: - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, keeper.GetVotingParams(ctx)) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil - - case v1.ParamTallying: - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, keeper.GetTallyParams(ctx)) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "%s is not a valid query request path", req.Path) - } -} - -func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params v1.QueryProposalParams - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - proposal, ok := keeper.GetProposal(ctx, params.ProposalID) - if !ok { - return nil, sdkerrors.Wrapf(types.ErrUnknownProposal, "%d", params.ProposalID) - } - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, proposal) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params v1.QueryDepositParams - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - deposit, _ := keeper.GetDeposit(ctx, params.ProposalID, params.Depositor) - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, deposit) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params v1.QueryVoteParams - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - vote, _ := keeper.GetVote(ctx, params.ProposalID, params.Voter) - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, vote) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params v1.QueryProposalParams - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - deposits := keeper.GetDeposits(ctx, params.ProposalID) - if deposits == nil { - deposits = v1.Deposits{} - } - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, deposits) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params v1.QueryProposalParams - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - proposalID := params.ProposalID - - proposal, ok := keeper.GetProposal(ctx, proposalID) - if !ok { - return nil, sdkerrors.Wrapf(types.ErrUnknownProposal, "%d", proposalID) - } - - var tallyResult v1.TallyResult - - switch { - case proposal.Status == v1.StatusDepositPeriod: - tallyResult = v1.EmptyTallyResult() - - case proposal.Status == v1.StatusPassed || proposal.Status == v1.StatusRejected: - tallyResult = *proposal.FinalTallyResult - - default: - // proposal is in voting period - _, _, tallyResult = keeper.Tally(ctx, proposal) - } - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, tallyResult) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryVotes(ctx sdk.Context, path []string, req abci.RequestQuery, keeper *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params v1.QueryProposalVotesParams - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - votes := keeper.GetVotes(ctx, params.ProposalID) - if votes == nil { - votes = v1.Votes{} - } else { - start, end := client.Paginate(len(votes), params.Page, params.Limit, 100) - if start < 0 || end < 0 { - votes = v1.Votes{} - } else { - votes = votes[start:end] - } - } - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, votes) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - -func queryProposals(ctx sdk.Context, _ []string, req abci.RequestQuery, keeper *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params v1.QueryProposalsParams - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - proposals := keeper.GetProposalsFiltered(ctx, params) - if proposals == nil { - proposals = v1.Proposals{} - } - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, proposals) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go deleted file mode 100644 index d47d87f2a25..00000000000 --- a/x/gov/keeper/querier_test.go +++ /dev/null @@ -1,439 +0,0 @@ -package keeper_test - -import ( - "math/rand" - "strings" - "testing" - "time" - - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/simapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/keeper" - "github.com/cosmos/cosmos-sdk/x/gov/types" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" -) - -const custom = "custom" - -func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier) (v1.DepositParams, v1.VotingParams, v1.TallyParams) { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, v1.QueryParams, v1.ParamDeposit}, "/"), - Data: []byte{}, - } - - bz, err := querier(ctx, []string{v1.QueryParams, v1.ParamDeposit}, query) - require.NoError(t, err) - require.NotNil(t, bz) - - var depositParams v1.DepositParams - require.NoError(t, cdc.UnmarshalJSON(bz, &depositParams)) - - query = abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, v1.QueryParams, v1.ParamVoting}, "/"), - Data: []byte{}, - } - - bz, err = querier(ctx, []string{v1.QueryParams, v1.ParamVoting}, query) - require.NoError(t, err) - require.NotNil(t, bz) - - var votingParams v1.VotingParams - require.NoError(t, cdc.UnmarshalJSON(bz, &votingParams)) - - query = abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, v1.QueryParams, v1.ParamTallying}, "/"), - Data: []byte{}, - } - - bz, err = querier(ctx, []string{v1.QueryParams, v1.ParamTallying}, query) - require.NoError(t, err) - require.NotNil(t, bz) - - var tallyParams v1.TallyParams - require.NoError(t, cdc.UnmarshalJSON(bz, &tallyParams)) - - return depositParams, votingParams, tallyParams -} - -func getQueriedProposals( - t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, - depositor, voter sdk.AccAddress, status v1.ProposalStatus, page, limit int, -) []*v1.Proposal { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, v1.QueryProposals}, "/"), - Data: cdc.MustMarshalJSON(v1.NewQueryProposalsParams(page, limit, status, voter, depositor)), - } - - bz, err := querier(ctx, []string{v1.QueryProposals}, query) - require.NoError(t, err) - require.NotNil(t, bz) - - var proposals v1.Proposals - require.NoError(t, cdc.UnmarshalJSON(bz, &proposals)) - - return proposals -} - -func getQueriedDeposit(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, proposalID uint64, depositor sdk.AccAddress) v1.Deposit { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, v1.QueryDeposit}, "/"), - Data: cdc.MustMarshalJSON(v1.NewQueryDepositParams(proposalID, depositor)), - } - - bz, err := querier(ctx, []string{v1.QueryDeposit}, query) - require.NoError(t, err) - require.NotNil(t, bz) - - var deposit v1.Deposit - require.NoError(t, cdc.UnmarshalJSON(bz, &deposit)) - - return deposit -} - -func getQueriedDeposits(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, proposalID uint64) []v1.Deposit { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, v1.QueryDeposits}, "/"), - Data: cdc.MustMarshalJSON(v1.NewQueryProposalParams(proposalID)), - } - - bz, err := querier(ctx, []string{v1.QueryDeposits}, query) - require.NoError(t, err) - require.NotNil(t, bz) - - var deposits []v1.Deposit - require.NoError(t, cdc.UnmarshalJSON(bz, &deposits)) - - return deposits -} - -func getQueriedVote(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, proposalID uint64, voter sdk.AccAddress) v1.Vote { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, v1.QueryVote}, "/"), - Data: cdc.MustMarshalJSON(v1.NewQueryVoteParams(proposalID, voter)), - } - - bz, err := querier(ctx, []string{v1.QueryVote}, query) - require.NoError(t, err) - require.NotNil(t, bz) - - var vote v1.Vote - require.NoError(t, cdc.UnmarshalJSON(bz, &vote)) - - return vote -} - -func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, proposalID uint64, page, limit int) []v1.Vote { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, v1.QueryVote}, "/"), - Data: cdc.MustMarshalJSON(v1.NewQueryProposalVotesParams(proposalID, page, limit)), - } - - bz, err := querier(ctx, []string{v1.QueryVotes}, query) - require.NoError(t, err) - require.NotNil(t, bz) - - var votes []v1.Vote - require.NoError(t, cdc.UnmarshalJSON(bz, &votes)) - - return votes -} - -func TestQueries(t *testing.T) { - app := simapp.Setup(t, false) - ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - legacyQuerierCdc := app.LegacyAmino() - querier := keeper.NewQuerier(app.GovKeeper, legacyQuerierCdc) - - TestAddrs := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.NewInt(20000001)) - - oneCoins := sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1)) - consCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, app.StakingKeeper.TokensFromConsensusPower(ctx, 10))) - - tp := TestProposal - - depositParams, _, _ := getQueriedParams(t, ctx, legacyQuerierCdc, querier) - - // TestAddrs[0] proposes (and deposits) proposals #1 and #2 - proposal1, err := app.GovKeeper.SubmitProposal(ctx, tp, "") - require.NoError(t, err) - deposit1 := v1.NewDeposit(proposal1.Id, TestAddrs[0], oneCoins) - depositer1, err := sdk.AccAddressFromBech32(deposit1.Depositor) - require.NoError(t, err) - _, err = app.GovKeeper.AddDeposit(ctx, deposit1.ProposalId, depositer1, deposit1.Amount) - require.NoError(t, err) - - proposal1.TotalDeposit = sdk.NewCoins(proposal1.TotalDeposit...).Add(deposit1.Amount...) - - proposal2, err := app.GovKeeper.SubmitProposal(ctx, tp, "") - require.NoError(t, err) - deposit2 := v1.NewDeposit(proposal2.Id, TestAddrs[0], consCoins) - depositer2, err := sdk.AccAddressFromBech32(deposit2.Depositor) - require.NoError(t, err) - _, err = app.GovKeeper.AddDeposit(ctx, deposit2.ProposalId, depositer2, deposit2.Amount) - require.NoError(t, err) - - proposal2.TotalDeposit = sdk.NewCoins(proposal2.TotalDeposit...).Add(deposit2.Amount...) - - // TestAddrs[1] proposes (and deposits) on proposal #3 - proposal3, err := app.GovKeeper.SubmitProposal(ctx, tp, "") - require.NoError(t, err) - deposit3 := v1.NewDeposit(proposal3.Id, TestAddrs[1], oneCoins) - depositer3, err := sdk.AccAddressFromBech32(deposit3.Depositor) - require.NoError(t, err) - - _, err = app.GovKeeper.AddDeposit(ctx, deposit3.ProposalId, depositer3, deposit3.Amount) - require.NoError(t, err) - - proposal3.TotalDeposit = sdk.NewCoins(proposal3.TotalDeposit...).Add(deposit3.Amount...) - - // TestAddrs[1] deposits on proposals #2 & #3 - deposit4 := v1.NewDeposit(proposal2.Id, TestAddrs[1], depositParams.MinDeposit) - depositer4, err := sdk.AccAddressFromBech32(deposit4.Depositor) - require.NoError(t, err) - _, err = app.GovKeeper.AddDeposit(ctx, deposit4.ProposalId, depositer4, deposit4.Amount) - require.NoError(t, err) - - proposal2.TotalDeposit = sdk.NewCoins(proposal2.TotalDeposit...).Add(deposit4.Amount...) - proposal2.Status = v1.StatusVotingPeriod - votingEndTime := ctx.BlockTime().Add(v1.DefaultPeriod) - proposal2.VotingEndTime = &votingEndTime - - deposit5 := v1.NewDeposit(proposal3.Id, TestAddrs[1], depositParams.MinDeposit) - depositer5, err := sdk.AccAddressFromBech32(deposit5.Depositor) - require.NoError(t, err) - _, err = app.GovKeeper.AddDeposit(ctx, deposit5.ProposalId, depositer5, deposit5.Amount) - require.NoError(t, err) - - proposal3.TotalDeposit = sdk.NewCoins(proposal3.TotalDeposit...).Add(deposit5.Amount...) - proposal3.Status = v1.StatusVotingPeriod - votingEndTime = ctx.BlockTime().Add(v1.DefaultPeriod) - proposal3.VotingEndTime = &votingEndTime - // total deposit of TestAddrs[1] on proposal #3 is worth the proposal deposit + individual deposit - deposit5.Amount = sdk.NewCoins(deposit5.Amount...).Add(deposit3.Amount...) - - // check deposits on proposal1 match individual deposits - - deposits := getQueriedDeposits(t, ctx, legacyQuerierCdc, querier, proposal1.Id) - require.Len(t, deposits, 1) - require.Equal(t, deposit1, deposits[0]) - - deposit := getQueriedDeposit(t, ctx, legacyQuerierCdc, querier, proposal1.Id, TestAddrs[0]) - require.Equal(t, deposit1, deposit) - - // check deposits on proposal2 match individual deposits - deposits = getQueriedDeposits(t, ctx, legacyQuerierCdc, querier, proposal2.Id) - require.Len(t, deposits, 2) - // NOTE order of deposits is determined by the addresses - require.Equal(t, deposit2, deposits[0]) - require.Equal(t, deposit4, deposits[1]) - - // check deposits on proposal3 match individual deposits - deposits = getQueriedDeposits(t, ctx, legacyQuerierCdc, querier, proposal3.Id) - require.Len(t, deposits, 1) - require.Equal(t, deposit5, deposits[0]) - - deposit = getQueriedDeposit(t, ctx, legacyQuerierCdc, querier, proposal3.Id, TestAddrs[1]) - require.Equal(t, deposit5, deposit) - - // Only proposal #1 should be in v1.Deposit Period - proposals := getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, nil, v1.StatusDepositPeriod, 1, 0) - require.Len(t, proposals, 1) - require.Equal(t, proposal1, *proposals[0]) - - // Only proposals #2 and #3 should be in Voting Period - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, nil, v1.StatusVotingPeriod, 1, 0) - require.Len(t, proposals, 2) - checkEqualProposal(t, proposal2, *proposals[0]) - checkEqualProposal(t, proposal3, *proposals[1]) - - // Addrs[0] votes on proposals #2 & #3 - vote1 := v1.NewVote(proposal2.Id, TestAddrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "") - vote2 := v1.NewVote(proposal3.Id, TestAddrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "") - app.GovKeeper.SetVote(ctx, vote1) - app.GovKeeper.SetVote(ctx, vote2) - - // Addrs[1] votes on proposal #3 - vote3 := v1.NewVote(proposal3.Id, TestAddrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "") - app.GovKeeper.SetVote(ctx, vote3) - - // Test query voted by TestAddrs[0] - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, TestAddrs[0], v1.StatusNil, 1, 0) - checkEqualProposal(t, proposal2, *proposals[0]) - checkEqualProposal(t, proposal3, *proposals[1]) - - // Test query votes on v1.Proposal 2 - votes := getQueriedVotes(t, ctx, legacyQuerierCdc, querier, proposal2.Id, 1, 0) - require.Len(t, votes, 1) - checkEqualVotes(t, vote1, votes[0]) - - vote := getQueriedVote(t, ctx, legacyQuerierCdc, querier, proposal2.Id, TestAddrs[0]) - checkEqualVotes(t, vote1, vote) - - // Test query votes on v1.Proposal 3 - votes = getQueriedVotes(t, ctx, legacyQuerierCdc, querier, proposal3.Id, 1, 0) - require.Len(t, votes, 2) - checkEqualVotes(t, vote2, votes[0]) - checkEqualVotes(t, vote3, votes[1]) - - // Test query all proposals - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, nil, v1.StatusNil, 1, 0) - checkEqualProposal(t, proposal1, *proposals[0]) - checkEqualProposal(t, proposal2, *proposals[1]) - checkEqualProposal(t, proposal3, *proposals[2]) - - // Test query voted by TestAddrs[1] - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, TestAddrs[1], v1.StatusNil, 1, 0) - require.Equal(t, proposal3.Id, proposals[0].Id) - - // Test query deposited by TestAddrs[0] - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, TestAddrs[0], nil, v1.StatusNil, 1, 0) - require.Equal(t, proposal1.Id, proposals[0].Id) - - // Test query deposited by addr2 - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, TestAddrs[1], nil, v1.StatusNil, 1, 0) - require.Equal(t, proposal2.Id, proposals[0].Id) - require.Equal(t, proposal3.Id, proposals[1].Id) - - // Test query voted AND deposited by addr1 - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, TestAddrs[0], TestAddrs[0], v1.StatusNil, 1, 0) - require.Equal(t, proposal2.Id, proposals[0].Id) -} - -func TestPaginatedVotesQuery(t *testing.T) { - app := simapp.Setup(t, false) - ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - legacyQuerierCdc := app.LegacyAmino() - - proposal := v1.Proposal{ - Id: 100, - Status: v1.StatusVotingPeriod, - } - - app.GovKeeper.SetProposal(ctx, proposal) - - votes := make([]v1.Vote, 20) - random := rand.New(rand.NewSource(time.Now().UnixNano())) - addrMap := make(map[string]struct{}) - genAddr := func() string { - addr := make(sdk.AccAddress, 20) - for { - random.Read(addr) - addrStr := addr.String() - if _, ok := addrMap[addrStr]; !ok { - addrMap[addrStr] = struct{}{} - return addrStr - } - } - } - for i := range votes { - vote := v1.Vote{ - ProposalId: proposal.Id, - Voter: genAddr(), - Options: v1.NewNonSplitVoteOption(v1.OptionYes), - } - votes[i] = vote - app.GovKeeper.SetVote(ctx, vote) - } - - querier := keeper.NewQuerier(app.GovKeeper, legacyQuerierCdc) - - // keeper preserves consistent order for each query, but this is not the insertion order - all := getQueriedVotes(t, ctx, legacyQuerierCdc, querier, proposal.Id, 1, 0) - require.Equal(t, len(all), len(votes)) - - type testCase struct { - description string - page int - limit int - votes []v1.Vote - } - for _, tc := range []testCase{ - { - description: "SkipAll", - page: 2, - limit: len(all), - }, - { - description: "GetFirstChunk", - page: 1, - limit: 10, - votes: all[:10], - }, - { - description: "GetSecondsChunk", - page: 2, - limit: 10, - votes: all[10:], - }, - { - description: "InvalidPage", - page: -1, - }, - } { - tc := tc - t.Run(tc.description, func(t *testing.T) { - votes := getQueriedVotes(t, ctx, legacyQuerierCdc, querier, proposal.Id, tc.page, tc.limit) - require.Equal(t, len(tc.votes), len(votes)) - for i := range votes { - require.Equal(t, tc.votes[i], votes[i]) - } - }) - } -} - -// checkEqualVotes checks that two votes are equal, without taking into account -// graceful fallback for `Option`. -// When querying, the keeper populates the `vote.Option` field when there's -// only 1 vote, this function checks equality of structs while skipping that -// field. -func checkEqualVotes(t *testing.T, vote1, vote2 v1.Vote) { - require.Equal(t, vote1.Options, vote2.Options) - require.Equal(t, vote1.Voter, vote2.Voter) - require.Equal(t, vote1.ProposalId, vote2.ProposalId) -} - -// checkEqualProposal checks that 2 proposals are equal. -// When decoding with Amino, there are weird cases where the voting times -// are actually equal, but `require.Equal()` says they are not: -// -// Diff: -// --- Expected -// +++ Actual -// @@ -68,3 +68,7 @@ -// }, -// - VotingStartTime: (*time.Time)(), -// + VotingStartTime: (*time.Time)({ -// + wall: (uint64) 0, -// + ext: (int64) 0, -// + loc: (*time.Location)() -// + }), -func checkEqualProposal(t *testing.T, p1, p2 v1.Proposal) { - require.Equal(t, p1.Id, p2.Id) - require.Equal(t, p1.Messages, p2.Messages) - require.Equal(t, p1.Status, p2.Status) - require.Equal(t, p1.FinalTallyResult, p2.FinalTallyResult) - require.Equal(t, p1.SubmitTime, p2.SubmitTime) - require.Equal(t, p1.DepositEndTime, p2.DepositEndTime) - require.Equal(t, p1.TotalDeposit, p2.TotalDeposit) - require.Equal(t, convertNilToDefault(p1.VotingStartTime), convertNilToDefault(p2.VotingStartTime)) - require.Equal(t, convertNilToDefault(p1.VotingEndTime), convertNilToDefault(p2.VotingEndTime)) -} - -// convertNilToDefault converts a (*time.Time)() into a (*time.Time)()). -// In proto structs dealing with time, we use *time.Time, which can be nil. -// However, when using Amino, a nil time is unmarshalled into -// (*time.Time)()), which is Jan 1st 1970. -// This function converts a nil time to a default time, to check that they are -// actually equal. -func convertNilToDefault(t *time.Time) *time.Time { - if t == nil { - return &time.Time{} - } - - return t -} diff --git a/x/gov/module.go b/x/gov/module.go index dd95f7e1889..c5d1e563e45 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -239,21 +239,6 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { keeper.RegisterInvariants(ir, am.keeper, am.bankKeeper) } -// Deprecated: Route returns the message routing key for the gov module. -func (am AppModule) Route() sdk.Route { - return sdk.Route{} -} - -// QuerierRoute returns the gov module's querier route name. -func (AppModule) QuerierRoute() string { - return types.QuerierRoute -} - -// LegacyQuerierHandler returns no sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return keeper.NewQuerier(am.keeper, legacyQuerierCdc) -} - // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { msgServer := keeper.NewMsgServerImpl(am.keeper) diff --git a/x/gov/types/keys.go b/x/gov/types/keys.go index 7f58d8fdfba..bbb964c674c 100644 --- a/x/gov/types/keys.go +++ b/x/gov/types/keys.go @@ -18,9 +18,6 @@ const ( // RouterKey is the message route for gov RouterKey = ModuleName - - // QuerierRoute is the querier route for gov - QuerierRoute = ModuleName ) // Keys for governance store diff --git a/x/group/module/module.go b/x/group/module/module.go index 915b24970ab..c0ad9a540cf 100644 --- a/x/group/module/module.go +++ b/x/group/module/module.go @@ -112,23 +112,10 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { keeper.RegisterInvariants(ir, am.keeper) } -// Deprecated: Route returns the message routing key for the group module. -func (am AppModule) Route() sdk.Route { - return sdk.Route{} -} - func (am AppModule) NewHandler() sdk.Handler { return nil } -// QuerierRoute returns the route we respond to for abci queries -func (AppModule) QuerierRoute() string { return "" } - -// LegacyQuerierHandler returns the group module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return nil -} - // InitGenesis performs genesis initialization for the group module. It returns // no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { diff --git a/x/mint/keeper/querier.go b/x/mint/keeper/querier.go deleted file mode 100644 index 294445614a5..00000000000 --- a/x/mint/keeper/querier.go +++ /dev/null @@ -1,62 +0,0 @@ -package keeper - -import ( - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/mint/types" -) - -// NewQuerier returns a minting Querier handler. -func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return func(ctx sdk.Context, path []string, _ abci.RequestQuery) ([]byte, error) { - switch path[0] { - case types.QueryParameters: - return queryParams(ctx, k, legacyQuerierCdc) - - case types.QueryInflation: - return queryInflation(ctx, k, legacyQuerierCdc) - - case types.QueryAnnualProvisions: - return queryAnnualProvisions(ctx, k, legacyQuerierCdc) - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown query path: %s", path[0]) - } - } -} - -func queryParams(ctx sdk.Context, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - params := k.GetParams(ctx) - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, params) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryInflation(ctx sdk.Context, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - minter := k.GetMinter(ctx) - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, minter.Inflation) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryAnnualProvisions(ctx sdk.Context, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - minter := k.GetMinter(ctx) - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, minter.AnnualProvisions) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} diff --git a/x/mint/keeper/querier_test.go b/x/mint/keeper/querier_test.go deleted file mode 100644 index 371bc510124..00000000000 --- a/x/mint/keeper/querier_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/mint/keeper" - keep "github.com/cosmos/cosmos-sdk/x/mint/keeper" - minttestutil "github.com/cosmos/cosmos-sdk/x/mint/testutil" - "github.com/cosmos/cosmos-sdk/x/mint/types" -) - -type MintKeeperTestSuite struct { - suite.Suite - - ctx sdk.Context - legacyAmino *codec.LegacyAmino - mintKeeper keeper.Keeper -} - -func (suite *MintKeeperTestSuite) SetupTest() { - encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModuleBasic{}) - key := sdk.NewKVStoreKey(types.StoreKey) - testCtx := testutil.DefaultContextWithDB(suite.T(), key, sdk.NewTransientStoreKey("transient_test")) - suite.ctx = testCtx.Ctx - - // gomock initializations - ctrl := gomock.NewController(suite.T()) - accountKeeper := minttestutil.NewMockAccountKeeper(ctrl) - bankKeeper := minttestutil.NewMockBankKeeper(ctrl) - stakingKeeper := minttestutil.NewMockStakingKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress(types.ModuleName).Return(sdk.AccAddress{}) - - suite.mintKeeper = keeper.NewKeeper( - encCfg.Codec, - key, - stakingKeeper, - accountKeeper, - bankKeeper, - authtypes.FeeCollectorName, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - - err := suite.mintKeeper.SetParams(suite.ctx, types.DefaultParams()) - suite.Require().NoError(err) - suite.mintKeeper.SetMinter(suite.ctx, types.DefaultInitialMinter()) -} - -func (suite *MintKeeperTestSuite) TestNewQuerier(t *testing.T) { - querier := keep.NewQuerier(suite.mintKeeper, suite.legacyAmino) - - query := abci.RequestQuery{ - Path: "", - Data: []byte{}, - } - - _, err := querier(suite.ctx, []string{types.QueryParameters}, query) - require.NoError(t, err) - - _, err = querier(suite.ctx, []string{types.QueryInflation}, query) - require.NoError(t, err) - - _, err = querier(suite.ctx, []string{types.QueryAnnualProvisions}, query) - require.NoError(t, err) - - _, err = querier(suite.ctx, []string{"foo"}, query) - require.Error(t, err) -} - -func (suite *MintKeeperTestSuite) TestQueryParams(t *testing.T) { - querier := keep.NewQuerier(suite.mintKeeper, suite.legacyAmino) - - var params types.Params - - res, sdkErr := querier(suite.ctx, []string{types.QueryParameters}, abci.RequestQuery{}) - require.NoError(t, sdkErr) - - err := suite.legacyAmino.UnmarshalJSON(res, ¶ms) - require.NoError(t, err) - - require.Equal(t, suite.mintKeeper.GetParams(suite.ctx), params) -} - -func (suite *MintKeeperTestSuite) TestQueryInflation(t *testing.T) { - querier := keep.NewQuerier(suite.mintKeeper, suite.legacyAmino) - - var inflation sdk.Dec - - res, sdkErr := querier(suite.ctx, []string{types.QueryInflation}, abci.RequestQuery{}) - require.NoError(t, sdkErr) - - err := suite.legacyAmino.UnmarshalJSON(res, &inflation) - require.NoError(t, err) - - require.Equal(t, suite.mintKeeper.GetMinter(suite.ctx).Inflation, inflation) -} - -func (suite *MintKeeperTestSuite) TestQueryAnnualProvisions(t *testing.T) { - querier := keep.NewQuerier(suite.mintKeeper, suite.legacyAmino) - - var annualProvisions sdk.Dec - - res, sdkErr := querier(suite.ctx, []string{types.QueryAnnualProvisions}, abci.RequestQuery{}) - require.NoError(t, sdkErr) - - err := suite.legacyAmino.UnmarshalJSON(res, &annualProvisions) - require.NoError(t, err) - - require.Equal(t, suite.mintKeeper.GetMinter(suite.ctx).AnnualProvisions, annualProvisions) -} diff --git a/x/mint/module.go b/x/mint/module.go index 4d9781f3d43..6ee35876e85 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -137,19 +137,6 @@ func (AppModule) Name() string { // RegisterInvariants registers the mint module invariants. func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// Deprecated: Route returns the message routing key for the mint module. -func (AppModule) Route() sdk.Route { return sdk.Route{} } - -// QuerierRoute returns the mint module's querier route name. -func (AppModule) QuerierRoute() string { - return types.QuerierRoute -} - -// LegacyQuerierHandler returns the mint module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return keeper.NewQuerier(am.keeper, legacyQuerierCdc) -} - // RegisterServices registers a gRPC query service to respond to the // module-specific gRPC queries. func (am AppModule) RegisterServices(cfg module.Configurator) { diff --git a/x/mint/types/keys.go b/x/mint/types/keys.go index dc4699b5a9b..69deb872680 100644 --- a/x/mint/types/keys.go +++ b/x/mint/types/keys.go @@ -13,9 +13,6 @@ const ( // StoreKey is the default store key for mint StoreKey = ModuleName - // QuerierRoute is the querier route for the minting store. - QuerierRoute = StoreKey - // Query endpoints supported by the minting querier QueryParameters = "parameters" QueryInflation = "inflation" diff --git a/x/nft/module/module.go b/x/nft/module/module.go index 51537ed7379..b8054addf0d 100644 --- a/x/nft/module/module.go +++ b/x/nft/module/module.go @@ -121,23 +121,10 @@ func (AppModule) Name() string { // RegisterInvariants does nothing, there are no invariants to enforce func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// Route returns the message routing key for the staking module. -func (am AppModule) Route() sdk.Route { - return sdk.NewRoute(nft.RouterKey, nil) -} - func (am AppModule) NewHandler() sdk.Handler { return nil } -// QuerierRoute returns the route we respond to for abci queries -func (AppModule) QuerierRoute() string { return "" } - -// LegacyQuerierHandler returns the nft module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return nil -} - // InitGenesis performs genesis initialization for the nft module. It returns // no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { diff --git a/x/params/keeper/querier.go b/x/params/keeper/querier.go deleted file mode 100644 index 9d6f3c3da69..00000000000 --- a/x/params/keeper/querier.go +++ /dev/null @@ -1,47 +0,0 @@ -package keeper - -import ( - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" -) - -// NewQuerier returns a new querier handler for the x/params module. -func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - switch path[0] { - case types.QueryParams: - return queryParams(ctx, req, k, legacyQuerierCdc) - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown query path: %s", path[0]) - } - } -} - -func queryParams(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QuerySubspaceParams - - if err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - ss, ok := k.GetSubspace(params.Subspace) - if !ok { - return nil, sdkerrors.Wrap(proposal.ErrUnknownSubspace, params.Subspace) - } - - rawValue := ss.GetRaw(ctx, []byte(params.Key)) - resp := types.NewSubspaceParamsResponse(params.Subspace, params.Key, string(rawValue)) - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, resp) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} diff --git a/x/params/module.go b/x/params/module.go index 7d851f6fec0..d3385f50011 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -100,22 +100,9 @@ func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMess return []abci.ValidatorUpdate{} } -// Deprecated: Route returns the message routing key for the params module. -func (AppModule) Route() sdk.Route { - return sdk.Route{} -} - // GenerateGenesisState performs a no-op. func (AppModule) GenerateGenesisState(simState *module.SimulationState) {} -// QuerierRoute returns the x/param module's querier route name. -func (AppModule) QuerierRoute() string { return types.QuerierRoute } - -// LegacyQuerierHandler returns the x/params querier handler. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return keeper.NewQuerier(am.keeper, legacyQuerierCdc) -} - // RegisterServices registers a gRPC query service to respond to the // module-specific gRPC queries. func (am AppModule) RegisterServices(cfg module.Configurator) { diff --git a/x/params/types/keys.go b/x/params/types/keys.go index 25df79848da..87c925383cc 100644 --- a/x/params/types/keys.go +++ b/x/params/types/keys.go @@ -3,7 +3,4 @@ package types const ( // ModuleName defines the module name ModuleName = "params" - - // QuerierRoute defines the module's query routing key - QuerierRoute = ModuleName ) diff --git a/x/slashing/module.go b/x/slashing/module.go index d554ff32e8c..e0e5de62e32 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -128,23 +128,6 @@ func (AppModule) Name() string { // RegisterInvariants registers the slashing module invariants. func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// Deprecated: Route returns the message routing key for the slashing module. -func (am AppModule) Route() sdk.Route { - return sdk.Route{} -} - -// QuerierRoute returns the slashing module's querier route name. -func (AppModule) QuerierRoute() string { - return types.QuerierRoute -} - -// LegacyQuerierHandler returns the slashing module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return func(sdk.Context, []string, abci.RequestQuery) ([]byte, error) { - return nil, fmt.Errorf("legacy querier not supported for the x/%s module", types.ModuleName) - } -} - // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) diff --git a/x/slashing/types/keys.go b/x/slashing/types/keys.go index bf4c1bc7585..02a86e167e2 100644 --- a/x/slashing/types/keys.go +++ b/x/slashing/types/keys.go @@ -17,9 +17,6 @@ const ( // RouterKey is the message route for slashing RouterKey = ModuleName - - // QuerierRoute is the querier route for slashing - QuerierRoute = ModuleName ) // Keys for slashing store diff --git a/x/staking/keeper/grpc_query.go b/x/staking/keeper/grpc_query.go index ecb2802b773..1389d7c05c9 100644 --- a/x/staking/keeper/grpc_query.go +++ b/x/staking/keeper/grpc_query.go @@ -532,3 +532,81 @@ func queryAllRedelegations(store sdk.KVStore, k Querier, req *types.QueryRedeleg return redels, res, err } + +// util + +func DelegationToDelegationResponse(ctx sdk.Context, k *Keeper, del types.Delegation) (types.DelegationResponse, error) { + val, found := k.GetValidator(ctx, del.GetValidatorAddr()) + if !found { + return types.DelegationResponse{}, types.ErrNoValidatorFound + } + + delegatorAddress, err := sdk.AccAddressFromBech32(del.DelegatorAddress) + if err != nil { + return types.DelegationResponse{}, err + } + + return types.NewDelegationResp( + delegatorAddress, + del.GetValidatorAddr(), + del.Shares, + sdk.NewCoin(k.BondDenom(ctx), val.TokensFromShares(del.Shares).TruncateInt()), + ), nil +} + +func DelegationsToDelegationResponses(ctx sdk.Context, k *Keeper, delegations types.Delegations) (types.DelegationResponses, error) { + resp := make(types.DelegationResponses, len(delegations)) + + for i, del := range delegations { + delResp, err := DelegationToDelegationResponse(ctx, k, del) + if err != nil { + return nil, err + } + + resp[i] = delResp + } + + return resp, nil +} + +func RedelegationsToRedelegationResponses(ctx sdk.Context, k *Keeper, redels types.Redelegations) (types.RedelegationResponses, error) { + resp := make(types.RedelegationResponses, len(redels)) + + for i, redel := range redels { + valSrcAddr, err := sdk.ValAddressFromBech32(redel.ValidatorSrcAddress) + if err != nil { + panic(err) + } + valDstAddr, err := sdk.ValAddressFromBech32(redel.ValidatorDstAddress) + if err != nil { + panic(err) + } + + delegatorAddress := sdk.MustAccAddressFromBech32(redel.DelegatorAddress) + + val, found := k.GetValidator(ctx, valDstAddr) + if !found { + return nil, types.ErrNoValidatorFound + } + + entryResponses := make([]types.RedelegationEntryResponse, len(redel.Entries)) + for j, entry := range redel.Entries { + entryResponses[j] = types.NewRedelegationEntryResponse( + entry.CreationHeight, + entry.CompletionTime, + entry.SharesDst, + entry.InitialBalance, + val.TokensFromShares(entry.SharesDst).TruncateInt(), + ) + } + + resp[i] = types.NewRedelegationResponse( + delegatorAddress, + valSrcAddr, + valDstAddr, + entryResponses, + ) + } + + return resp, nil +} diff --git a/x/staking/keeper/querier.go b/x/staking/keeper/querier.go deleted file mode 100644 index 71e778c9b0f..00000000000 --- a/x/staking/keeper/querier.go +++ /dev/null @@ -1,522 +0,0 @@ -package keeper - -import ( - "errors" - "strings" - - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// creates a querier for staking REST endpoints -func NewQuerier(k *Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - switch path[0] { - case types.QueryValidators: - return queryValidators(ctx, req, k, legacyQuerierCdc) - - case types.QueryValidator: - return queryValidator(ctx, req, k, legacyQuerierCdc) - - case types.QueryValidatorDelegations: - return queryValidatorDelegations(ctx, req, k, legacyQuerierCdc) - - case types.QueryValidatorUnbondingDelegations: - return queryValidatorUnbondingDelegations(ctx, req, k, legacyQuerierCdc) - - case types.QueryDelegation: - return queryDelegation(ctx, req, k, legacyQuerierCdc) - - case types.QueryUnbondingDelegation: - return queryUnbondingDelegation(ctx, req, k, legacyQuerierCdc) - - case types.QueryDelegatorDelegations: - return queryDelegatorDelegations(ctx, req, k, legacyQuerierCdc) - - case types.QueryDelegatorUnbondingDelegations: - return queryDelegatorUnbondingDelegations(ctx, req, k, legacyQuerierCdc) - - case types.QueryRedelegations: - return queryRedelegations(ctx, req, k, legacyQuerierCdc) - - case types.QueryDelegatorValidators: - return queryDelegatorValidators(ctx, req, k, legacyQuerierCdc) - - case types.QueryDelegatorValidator: - return queryDelegatorValidator(ctx, req, k, legacyQuerierCdc) - - case types.QueryHistoricalInfo: - return queryHistoricalInfo(ctx, req, k, legacyQuerierCdc) - - case types.QueryPool: - return queryPool(ctx, k, legacyQuerierCdc) - - case types.QueryParameters: - return queryParameters(ctx, k, legacyQuerierCdc) - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint: %s", types.ModuleName, path[0]) - } - } -} - -func queryValidators(ctx sdk.Context, req abci.RequestQuery, k *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryValidatorsParams - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - validators := k.GetAllValidators(ctx) - filteredVals := make(types.Validators, 0, len(validators)) - - for _, val := range validators { - if strings.EqualFold(val.GetStatus().String(), params.Status) { - filteredVals = append(filteredVals, val) - } - } - - start, end := client.Paginate(len(filteredVals), params.Page, params.Limit, int(k.GetParams(ctx).MaxValidators)) - if start < 0 || end < 0 { - filteredVals = []types.Validator{} - } else { - filteredVals = filteredVals[start:end] - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, filteredVals) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryValidator(ctx sdk.Context, req abci.RequestQuery, k *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryValidatorParams - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - validator, found := k.GetValidator(ctx, params.ValidatorAddr) - if !found { - return nil, types.ErrNoValidatorFound - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, validator) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryValidatorDelegations(ctx sdk.Context, req abci.RequestQuery, k *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryValidatorParams - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - delegations := k.GetValidatorDelegations(ctx, params.ValidatorAddr) - - start, end := client.Paginate(len(delegations), params.Page, params.Limit, int(k.GetParams(ctx).MaxValidators)) - if start < 0 || end < 0 { - delegations = []types.Delegation{} - } else { - delegations = delegations[start:end] - } - - delegationResps, err := DelegationsToDelegationResponses(ctx, k, delegations) - if err != nil { - return nil, err - } - - if delegationResps == nil { - delegationResps = types.DelegationResponses{} - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, delegationResps) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryValidatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryValidatorParams - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - unbonds := k.GetUnbondingDelegationsFromValidator(ctx, params.ValidatorAddr) - if unbonds == nil { - unbonds = types.UnbondingDelegations{} - } - - start, end := client.Paginate(len(unbonds), params.Page, params.Limit, int(k.GetParams(ctx).MaxValidators)) - if start < 0 || end < 0 { - unbonds = types.UnbondingDelegations{} - } else { - unbonds = unbonds[start:end] - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, unbonds) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryDelegatorDelegations(ctx sdk.Context, req abci.RequestQuery, k *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryDelegatorParams - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - delegations := k.GetAllDelegatorDelegations(ctx, params.DelegatorAddr) - delegationResps, err := DelegationsToDelegationResponses(ctx, k, delegations) - if err != nil { - return nil, err - } - - if delegationResps == nil { - delegationResps = types.DelegationResponses{} - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, delegationResps) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryDelegatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryDelegatorParams - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - unbondingDelegations := k.GetAllUnbondingDelegations(ctx, params.DelegatorAddr) - if unbondingDelegations == nil { - unbondingDelegations = types.UnbondingDelegations{} - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, unbondingDelegations) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryDelegatorValidators(ctx sdk.Context, req abci.RequestQuery, k *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryDelegatorParams - - stakingParams := k.GetParams(ctx) - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - validators := k.GetDelegatorValidators(ctx, params.DelegatorAddr, stakingParams.MaxValidators) - if validators == nil { - validators = types.Validators{} - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, validators) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryDelegatorValidatorRequest - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - delAddr, err := sdk.AccAddressFromBech32(params.DelegatorAddr) - if err != nil { - return nil, err - } - - valAddr, err := sdk.ValAddressFromBech32(params.ValidatorAddr) - if err != nil { - return nil, err - } - - validator, err := k.GetDelegatorValidator(ctx, delAddr, valAddr) - if err != nil { - return nil, err - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, validator) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryDelegatorValidatorRequest - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - delAddr, err := sdk.AccAddressFromBech32(params.DelegatorAddr) - if err != nil { - return nil, err - } - - valAddr, err := sdk.ValAddressFromBech32(params.ValidatorAddr) - if err != nil { - return nil, err - } - - delegation, found := k.GetDelegation(ctx, delAddr, valAddr) - if !found { - return nil, types.ErrNoDelegation - } - - delegationResp, err := DelegationToDelegationResponse(ctx, k, delegation) - if err != nil { - return nil, err - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, delegationResp) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryDelegatorValidatorRequest - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - delAddr, err := sdk.AccAddressFromBech32(params.DelegatorAddr) - if err != nil { - return nil, err - } - - valAddr, err := sdk.ValAddressFromBech32(params.ValidatorAddr) - if err != nil { - return nil, err - } - - unbond, found := k.GetUnbondingDelegation(ctx, delAddr, valAddr) - if !found { - return nil, types.ErrNoUnbondingDelegation - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, unbond) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryRedelegations(ctx sdk.Context, req abci.RequestQuery, k *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryRedelegationParams - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - var redels []types.Redelegation - - switch { - case !params.DelegatorAddr.Empty() && !params.SrcValidatorAddr.Empty() && !params.DstValidatorAddr.Empty(): - redel, found := k.GetRedelegation(ctx, params.DelegatorAddr, params.SrcValidatorAddr, params.DstValidatorAddr) - if !found { - return nil, types.ErrNoRedelegation - } - - redels = []types.Redelegation{redel} - case params.DelegatorAddr.Empty() && !params.SrcValidatorAddr.Empty() && params.DstValidatorAddr.Empty(): - redels = k.GetRedelegationsFromSrcValidator(ctx, params.SrcValidatorAddr) - default: - redels = k.GetAllRedelegations(ctx, params.DelegatorAddr, params.SrcValidatorAddr, params.DstValidatorAddr) - } - - redelResponses, err := RedelegationsToRedelegationResponses(ctx, k, redels) - if err != nil { - return nil, err - } - - if redelResponses == nil { - redelResponses = types.RedelegationResponses{} - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, redelResponses) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryHistoricalInfo(ctx sdk.Context, req abci.RequestQuery, k *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryHistoricalInfoRequest - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - hi, found := k.GetHistoricalInfo(ctx, params.Height) - if !found { - return nil, types.ErrNoHistoricalInfo - } - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, hi) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryPool(ctx sdk.Context, k *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - bondDenom := k.BondDenom(ctx) - bondedPool := k.GetBondedPool(ctx) - notBondedPool := k.GetNotBondedPool(ctx) - - if bondedPool == nil || notBondedPool == nil { - return nil, errors.New("pool accounts haven't been set") - } - - pool := types.NewPool( - k.bankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount, - k.bankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount, - ) - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, pool) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryParameters(ctx sdk.Context, k *Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - params := k.GetParams(ctx) - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, params) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -// util - -func DelegationToDelegationResponse(ctx sdk.Context, k *Keeper, del types.Delegation) (types.DelegationResponse, error) { - val, found := k.GetValidator(ctx, del.GetValidatorAddr()) - if !found { - return types.DelegationResponse{}, types.ErrNoValidatorFound - } - - delegatorAddress, err := sdk.AccAddressFromBech32(del.DelegatorAddress) - if err != nil { - return types.DelegationResponse{}, err - } - - return types.NewDelegationResp( - delegatorAddress, - del.GetValidatorAddr(), - del.Shares, - sdk.NewCoin(k.BondDenom(ctx), val.TokensFromShares(del.Shares).TruncateInt()), - ), nil -} - -func DelegationsToDelegationResponses(ctx sdk.Context, k *Keeper, delegations types.Delegations) (types.DelegationResponses, error) { - resp := make(types.DelegationResponses, len(delegations)) - - for i, del := range delegations { - delResp, err := DelegationToDelegationResponse(ctx, k, del) - if err != nil { - return nil, err - } - - resp[i] = delResp - } - - return resp, nil -} - -func RedelegationsToRedelegationResponses(ctx sdk.Context, k *Keeper, redels types.Redelegations) (types.RedelegationResponses, error) { - resp := make(types.RedelegationResponses, len(redels)) - - for i, redel := range redels { - valSrcAddr, err := sdk.ValAddressFromBech32(redel.ValidatorSrcAddress) - if err != nil { - panic(err) - } - valDstAddr, err := sdk.ValAddressFromBech32(redel.ValidatorDstAddress) - if err != nil { - panic(err) - } - - delegatorAddress := sdk.MustAccAddressFromBech32(redel.DelegatorAddress) - - val, found := k.GetValidator(ctx, valDstAddr) - if !found { - return nil, types.ErrNoValidatorFound - } - - entryResponses := make([]types.RedelegationEntryResponse, len(redel.Entries)) - for j, entry := range redel.Entries { - entryResponses[j] = types.NewRedelegationEntryResponse( - entry.CreationHeight, - entry.CompletionTime, - entry.SharesDst, - entry.InitialBalance, - val.TokensFromShares(entry.SharesDst).TruncateInt(), - ) - } - - resp[i] = types.NewRedelegationResponse( - delegatorAddress, - valSrcAddr, - valDstAddr, - entryResponses, - ) - } - - return resp, nil -} diff --git a/x/staking/keeper/querier_test.go b/x/staking/keeper/querier_test.go deleted file mode 100644 index fb809595c86..00000000000 --- a/x/staking/keeper/querier_test.go +++ /dev/null @@ -1,755 +0,0 @@ -package keeper_test - -import ( - "fmt" - "testing" - - "cosmossdk.io/math" - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/simapp" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking/keeper" - "github.com/cosmos/cosmos-sdk/x/staking/teststaking" - "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -func TestNewQuerier(t *testing.T) { - cdc, app, ctx := createTestInput(t) - - addrs := simapp.AddTestAddrs(app, ctx, 500, sdk.NewInt(10000)) - _, addrAcc2 := addrs[0], addrs[1] - addrVal1, _ := sdk.ValAddress(addrs[0]), sdk.ValAddress(addrs[1]) - - // Create Validators - amts := []math.Int{sdk.NewInt(9), sdk.NewInt(8)} - var validators [2]types.Validator - for i, amt := range amts { - validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) - validators[i], _ = validators[i].AddTokensFromDel(amt) - app.StakingKeeper.SetValidator(ctx, validators[i]) - app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[i]) - } - - header := tmproto.Header{ - ChainID: "HelloChain", - Height: 5, - } - hi := types.NewHistoricalInfo(header, validators[:], app.StakingKeeper.PowerReduction(ctx)) - app.StakingKeeper.SetHistoricalInfo(ctx, 5, &hi) - - query := abci.RequestQuery{ - Path: "", - Data: []byte{}, - } - - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) - - bz, err := querier(ctx, []string{"other"}, query) - require.Error(t, err) - require.Nil(t, bz) - - _, err = querier(ctx, []string{"pool"}, query) - require.NoError(t, err) - - _, err = querier(ctx, []string{"parameters"}, query) - require.NoError(t, err) - - queryValParams := types.NewQueryValidatorParams(addrVal1, 0, 0) - bz, errRes := cdc.MarshalJSON(queryValParams) - require.NoError(t, errRes) - - query.Path = "/custom/staking/validator" - query.Data = bz - - _, err = querier(ctx, []string{"validator"}, query) - require.NoError(t, err) - - _, err = querier(ctx, []string{"validatorDelegations"}, query) - require.NoError(t, err) - - _, err = querier(ctx, []string{"validatorUnbondingDelegations"}, query) - require.NoError(t, err) - - queryDelParams := types.NewQueryDelegatorParams(addrAcc2) - bz, errRes = cdc.MarshalJSON(queryDelParams) - require.NoError(t, errRes) - - query.Path = "/custom/staking/validator" - query.Data = bz - - _, err = querier(ctx, []string{"delegatorDelegations"}, query) - require.NoError(t, err) - - _, err = querier(ctx, []string{"delegatorUnbondingDelegations"}, query) - require.NoError(t, err) - - _, err = querier(ctx, []string{"delegatorValidators"}, query) - require.NoError(t, err) - - bz, errRes = cdc.MarshalJSON(types.NewQueryRedelegationParams(nil, nil, nil)) - require.NoError(t, errRes) - query.Data = bz - - _, err = querier(ctx, []string{"redelegations"}, query) - require.NoError(t, err) - - queryHisParams := types.QueryHistoricalInfoRequest{Height: 5} - bz, errRes = cdc.MarshalJSON(queryHisParams) - require.NoError(t, errRes) - - query.Path = "/custom/staking/historicalInfo" - query.Data = bz - - _, err = querier(ctx, []string{"historicalInfo"}, query) - require.NoError(t, err) -} - -func TestQueryParametersPool(t *testing.T) { - cdc, app, ctx := createTestInput(t) - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) - - bondDenom := sdk.DefaultBondDenom - - res, err := querier(ctx, []string{types.QueryParameters}, abci.RequestQuery{}) - require.NoError(t, err) - - var params types.Params - errRes := cdc.UnmarshalJSON(res, ¶ms) - require.NoError(t, errRes) - require.Equal(t, app.StakingKeeper.GetParams(ctx), params) - - res, err = querier(ctx, []string{types.QueryPool}, abci.RequestQuery{}) - require.NoError(t, err) - - var pool types.Pool - bondedPool := app.StakingKeeper.GetBondedPool(ctx) - notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx) - require.NoError(t, cdc.UnmarshalJSON(res, &pool)) - require.Equal(t, app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount, pool.NotBondedTokens) - require.Equal(t, app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount, pool.BondedTokens) -} - -func TestQueryValidators(t *testing.T) { - cdc, app, ctx := createTestInput(t) - params := app.StakingKeeper.GetParams(ctx) - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) - - addrs := simapp.AddTestAddrs(app, ctx, 500, app.StakingKeeper.TokensFromConsensusPower(ctx, 10000)) - - // Create Validators - amts := []math.Int{sdk.NewInt(8), sdk.NewInt(7)} - status := []types.BondStatus{types.Unbonded, types.Unbonding} - var validators [2]types.Validator - for i, amt := range amts { - validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) - validators[i], _ = validators[i].AddTokensFromDel(amt) - validators[i] = validators[i].UpdateStatus(status[i]) - } - - app.StakingKeeper.SetValidator(ctx, validators[0]) - app.StakingKeeper.SetValidator(ctx, validators[1]) - - // Query Validators - queriedValidators := app.StakingKeeper.GetValidators(ctx, params.MaxValidators) - require.Len(t, queriedValidators, 3) - - for i, s := range status { - queryValsParams := types.NewQueryValidatorsParams(1, int(params.MaxValidators), s.String()) - bz, err := cdc.MarshalJSON(queryValsParams) - require.NoError(t, err) - - req := abci.RequestQuery{ - Path: fmt.Sprintf("/custom/%s/%s", types.QuerierRoute, types.QueryValidators), - Data: bz, - } - - res, err := querier(ctx, []string{types.QueryValidators}, req) - require.NoError(t, err) - - var validatorsResp []types.Validator - err = cdc.UnmarshalJSON(res, &validatorsResp) - require.NoError(t, err) - - require.Equal(t, 1, len(validatorsResp)) - require.Equal(t, validators[i].OperatorAddress, validatorsResp[0].OperatorAddress) - } - - // Query each validator - for _, validator := range validators { - queryParams := types.NewQueryValidatorParams(validator.GetOperator(), 0, 0) - bz, err := cdc.MarshalJSON(queryParams) - require.NoError(t, err) - - query := abci.RequestQuery{ - Path: "/custom/staking/validator", - Data: bz, - } - res, err := querier(ctx, []string{types.QueryValidator}, query) - require.NoError(t, err) - - var queriedValidator types.Validator - err = cdc.UnmarshalJSON(res, &queriedValidator) - require.NoError(t, err) - - require.True(t, validator.Equal(&queriedValidator)) - } -} - -func TestQueryDelegation(t *testing.T) { - cdc, app, ctx := createTestInput(t) - params := app.StakingKeeper.GetParams(ctx) - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) - - addrs := simapp.AddTestAddrs(app, ctx, 2, app.StakingKeeper.TokensFromConsensusPower(ctx, 10000)) - addrAcc1, addrAcc2 := addrs[0], addrs[1] - addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2) - - pubKeys := simtestutil.CreateTestPubKeys(2) - pk1, pk2 := pubKeys[0], pubKeys[1] - - // Create Validators and Delegation - val1 := teststaking.NewValidator(t, addrVal1, pk1) - app.StakingKeeper.SetValidator(ctx, val1) - app.StakingKeeper.SetValidatorByPowerIndex(ctx, val1) - - val2 := teststaking.NewValidator(t, addrVal2, pk2) - app.StakingKeeper.SetValidator(ctx, val2) - app.StakingKeeper.SetValidatorByPowerIndex(ctx, val2) - - delTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 20) - _, err := app.StakingKeeper.Delegate(ctx, addrAcc2, delTokens, types.Unbonded, val1, true) - require.NoError(t, err) - - // apply TM updates - applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1) - - // Query Delegator bonded validators - queryParams := types.NewQueryDelegatorParams(addrAcc2) - bz, errRes := cdc.MarshalJSON(queryParams) - require.NoError(t, errRes) - - query := abci.RequestQuery{ - Path: "/custom/staking/delegatorValidators", - Data: bz, - } - - delValidators := app.StakingKeeper.GetDelegatorValidators(ctx, addrAcc2, params.MaxValidators) - - res, err := querier(ctx, []string{types.QueryDelegatorValidators}, query) - require.NoError(t, err) - - var validatorsResp types.Validators - errRes = cdc.UnmarshalJSON(res, &validatorsResp) - require.NoError(t, errRes) - - require.Equal(t, len(delValidators), len(validatorsResp)) - require.ElementsMatch(t, delValidators, validatorsResp) - - // error unknown request - query.Data = bz[:len(bz)-1] - - _, err = querier(ctx, []string{types.QueryDelegatorValidators}, query) - require.Error(t, err) - - // Query bonded validator - queryBondParams := types.QueryDelegatorValidatorRequest{DelegatorAddr: addrAcc2.String(), ValidatorAddr: addrVal1.String()} - bz, errRes = cdc.MarshalJSON(queryBondParams) - require.NoError(t, errRes) - - query = abci.RequestQuery{ - Path: "/custom/staking/delegatorValidator", - Data: bz, - } - - res, err = querier(ctx, []string{types.QueryDelegatorValidator}, query) - require.NoError(t, err) - - var validator types.Validator - errRes = cdc.UnmarshalJSON(res, &validator) - require.NoError(t, errRes) - require.True(t, validator.Equal(&delValidators[0])) - - // error unknown request - query.Data = bz[:len(bz)-1] - - _, err = querier(ctx, []string{types.QueryDelegatorValidator}, query) - require.Error(t, err) - - // Query delegation - - query = abci.RequestQuery{ - Path: "/custom/staking/delegation", - Data: bz, - } - - delegation, found := app.StakingKeeper.GetDelegation(ctx, addrAcc2, addrVal1) - require.True(t, found) - - res, err = querier(ctx, []string{types.QueryDelegation}, query) - require.NoError(t, err) - - var delegationRes types.DelegationResponse - errRes = cdc.UnmarshalJSON(res, &delegationRes) - require.NoError(t, errRes) - - require.Equal(t, delegation.ValidatorAddress, delegationRes.Delegation.ValidatorAddress) - require.Equal(t, delegation.DelegatorAddress, delegationRes.Delegation.DelegatorAddress) - require.Equal(t, sdk.NewCoin(sdk.DefaultBondDenom, delegation.Shares.TruncateInt()), delegationRes.Balance) - - // Query Delegator Delegations - bz, errRes = cdc.MarshalJSON(queryParams) - require.NoError(t, errRes) - - query = abci.RequestQuery{ - Path: "/custom/staking/delegatorDelegations", - Data: bz, - } - - res, err = querier(ctx, []string{types.QueryDelegatorDelegations}, query) - require.NoError(t, err) - - var delegatorDelegations types.DelegationResponses - errRes = cdc.UnmarshalJSON(res, &delegatorDelegations) - require.NoError(t, errRes) - require.Len(t, delegatorDelegations, 1) - require.Equal(t, delegation.ValidatorAddress, delegatorDelegations[0].Delegation.ValidatorAddress) - require.Equal(t, delegation.DelegatorAddress, delegatorDelegations[0].Delegation.DelegatorAddress) - require.Equal(t, sdk.NewCoin(sdk.DefaultBondDenom, delegation.Shares.TruncateInt()), delegatorDelegations[0].Balance) - - // error unknown request - query.Data = bz[:len(bz)-1] - - _, err = querier(ctx, []string{types.QueryDelegation}, query) - require.Error(t, err) - - // Query validator delegations - bz, errRes = cdc.MarshalJSON(types.NewQueryValidatorParams(addrVal1, 1, 100)) - require.NoError(t, errRes) - - query = abci.RequestQuery{ - Path: "custom/staking/validatorDelegations", - Data: bz, - } - - res, err = querier(ctx, []string{types.QueryValidatorDelegations}, query) - require.NoError(t, err) - - var delegationsRes types.DelegationResponses - errRes = cdc.UnmarshalJSON(res, &delegationsRes) - require.NoError(t, errRes) - require.Len(t, delegatorDelegations, 1) - require.Equal(t, delegation.ValidatorAddress, delegationsRes[0].Delegation.ValidatorAddress) - require.Equal(t, delegation.DelegatorAddress, delegationsRes[0].Delegation.DelegatorAddress) - require.Equal(t, sdk.NewCoin(sdk.DefaultBondDenom, delegation.Shares.TruncateInt()), delegationsRes[0].Balance) - - // Query unbonding delegation - unbondingTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10) - _, err = app.StakingKeeper.Undelegate(ctx, addrAcc2, val1.GetOperator(), sdk.NewDecFromInt(unbondingTokens)) - require.NoError(t, err) - - queryBondParams = types.QueryDelegatorValidatorRequest{DelegatorAddr: addrAcc2.String(), ValidatorAddr: addrVal1.String()} - bz, errRes = cdc.MarshalJSON(queryBondParams) - require.NoError(t, errRes) - - query = abci.RequestQuery{ - Path: "/custom/staking/unbondingDelegation", - Data: bz, - } - - unbond, found := app.StakingKeeper.GetUnbondingDelegation(ctx, addrAcc2, addrVal1) - require.True(t, found) - - res, err = querier(ctx, []string{types.QueryUnbondingDelegation}, query) - require.NoError(t, err) - - var unbondRes types.UnbondingDelegation - errRes = cdc.UnmarshalJSON(res, &unbondRes) - require.NoError(t, errRes) - - require.Equal(t, unbond, unbondRes) - - // error unknown request - query.Data = bz[:len(bz)-1] - - _, err = querier(ctx, []string{types.QueryUnbondingDelegation}, query) - require.Error(t, err) - - // Query Delegator Unbonding Delegations - - query = abci.RequestQuery{ - Path: "/custom/staking/delegatorUnbondingDelegations", - Data: bz, - } - - res, err = querier(ctx, []string{types.QueryDelegatorUnbondingDelegations}, query) - require.NoError(t, err) - - var delegatorUbds []types.UnbondingDelegation - errRes = cdc.UnmarshalJSON(res, &delegatorUbds) - require.NoError(t, errRes) - require.Equal(t, unbond, delegatorUbds[0]) - - // error unknown request - query.Data = bz[:len(bz)-1] - - _, err = querier(ctx, []string{types.QueryDelegatorUnbondingDelegations}, query) - require.Error(t, err) - - // Query redelegation - redelegationTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10) - _, err = app.StakingKeeper.BeginRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator(), sdk.NewDecFromInt(redelegationTokens)) - require.NoError(t, err) - redel, found := app.StakingKeeper.GetRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator()) - require.True(t, found) - - bz, errRes = cdc.MarshalJSON(types.NewQueryRedelegationParams(addrAcc2, val1.GetOperator(), val2.GetOperator())) - require.NoError(t, errRes) - - query = abci.RequestQuery{ - Path: "/custom/staking/redelegations", - Data: bz, - } - - res, err = querier(ctx, []string{types.QueryRedelegations}, query) - require.NoError(t, err) - - var redelRes types.RedelegationResponses - errRes = cdc.UnmarshalJSON(res, &redelRes) - require.NoError(t, errRes) - require.Len(t, redelRes, 1) - require.Equal(t, redel.DelegatorAddress, redelRes[0].Redelegation.DelegatorAddress) - require.Equal(t, redel.ValidatorSrcAddress, redelRes[0].Redelegation.ValidatorSrcAddress) - require.Equal(t, redel.ValidatorDstAddress, redelRes[0].Redelegation.ValidatorDstAddress) - require.Len(t, redel.Entries, len(redelRes[0].Entries)) -} - -func TestQueryValidatorDelegations_Pagination(t *testing.T) { - cases := []struct { - page int - limit int - expectedResults int - }{ - { - page: 1, - limit: 75, - expectedResults: 75, - }, - { - page: 2, - limit: 75, - expectedResults: 25, - }, - { - page: 1, - limit: 100, - expectedResults: 100, - }, - } - - cdc, app, ctx := createTestInput(t) - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) - - addrs := simapp.AddTestAddrs(app, ctx, 100, app.StakingKeeper.TokensFromConsensusPower(ctx, 10000)) - pubKeys := simtestutil.CreateTestPubKeys(1) - - valAddress := sdk.ValAddress(addrs[0]) - - val1 := teststaking.NewValidator(t, valAddress, pubKeys[0]) - app.StakingKeeper.SetValidator(ctx, val1) - app.StakingKeeper.SetValidatorByPowerIndex(ctx, val1) - - // Create Validators and Delegation - for _, addr := range addrs { - validator, found := app.StakingKeeper.GetValidator(ctx, valAddress) - if !found { - t.Error("expected validator not found") - } - - delTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 20) - _, err := app.StakingKeeper.Delegate(ctx, addr, delTokens, types.Unbonded, validator, true) - require.NoError(t, err) - } - - // apply TM updates - applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1) - - for _, c := range cases { - // Query Delegator bonded validators - queryParams := types.NewQueryDelegatorParams(addrs[0]) - bz, errRes := cdc.MarshalJSON(queryParams) - require.NoError(t, errRes) - - // Query valAddress delegations - bz, errRes = cdc.MarshalJSON(types.NewQueryValidatorParams(valAddress, c.page, c.limit)) - require.NoError(t, errRes) - - query := abci.RequestQuery{ - Path: "custom/staking/validatorDelegations", - Data: bz, - } - - res, err := querier(ctx, []string{types.QueryValidatorDelegations}, query) - require.NoError(t, err) - - var delegationsRes types.DelegationResponses - errRes = cdc.UnmarshalJSON(res, &delegationsRes) - require.NoError(t, errRes) - require.Len(t, delegationsRes, c.expectedResults) - } - - // Undelegate - for _, addr := range addrs { - delTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 20) - _, err := app.StakingKeeper.Undelegate(ctx, addr, val1.GetOperator(), sdk.NewDecFromInt(delTokens)) - require.NoError(t, err) - } - - // apply TM updates - applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1) - - for _, c := range cases { - // Query Unbonding delegations with pagination. - queryParams := types.NewQueryDelegatorParams(addrs[0]) - bz, errRes := cdc.MarshalJSON(queryParams) - require.NoError(t, errRes) - - bz, errRes = cdc.MarshalJSON(types.NewQueryValidatorParams(valAddress, c.page, c.limit)) - require.NoError(t, errRes) - query := abci.RequestQuery{ - Data: bz, - } - - unbondingDelegations := types.UnbondingDelegations{} - res, err := querier(ctx, []string{types.QueryValidatorUnbondingDelegations}, query) - require.NoError(t, err) - - errRes = cdc.UnmarshalJSON(res, &unbondingDelegations) - require.NoError(t, errRes) - require.Len(t, unbondingDelegations, c.expectedResults) - } -} - -func TestQueryRedelegations(t *testing.T) { - cdc, app, ctx := createTestInput(t) - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) - - addrs := simapp.AddTestAddrs(app, ctx, 2, app.StakingKeeper.TokensFromConsensusPower(ctx, 10000)) - addrAcc1, addrAcc2 := addrs[0], addrs[1] - addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2) - - // Create Validators and Delegation - val1 := teststaking.NewValidator(t, addrVal1, PKs[0]) - val2 := teststaking.NewValidator(t, addrVal2, PKs[1]) - app.StakingKeeper.SetValidator(ctx, val1) - app.StakingKeeper.SetValidator(ctx, val2) - - delAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 100) - _, err := app.StakingKeeper.Delegate(ctx, addrAcc2, delAmount, types.Unbonded, val1, true) - require.NoError(t, err) - applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1) - - rdAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 20) - _, err = app.StakingKeeper.BeginRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator(), sdk.NewDecFromInt(rdAmount)) - require.NoError(t, err) - applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1) - - redel, found := app.StakingKeeper.GetRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator()) - require.True(t, found) - - // delegator redelegations - queryDelegatorParams := types.NewQueryDelegatorParams(addrAcc2) - bz, errRes := cdc.MarshalJSON(queryDelegatorParams) - require.NoError(t, errRes) - - query := abci.RequestQuery{ - Path: "/custom/staking/redelegations", - Data: bz, - } - - res, err := querier(ctx, []string{types.QueryRedelegations}, query) - require.NoError(t, err) - - var redelRes types.RedelegationResponses - errRes = cdc.UnmarshalJSON(res, &redelRes) - require.NoError(t, errRes) - require.Len(t, redelRes, 1) - require.Equal(t, redel.DelegatorAddress, redelRes[0].Redelegation.DelegatorAddress) - require.Equal(t, redel.ValidatorSrcAddress, redelRes[0].Redelegation.ValidatorSrcAddress) - require.Equal(t, redel.ValidatorDstAddress, redelRes[0].Redelegation.ValidatorDstAddress) - require.Len(t, redel.Entries, len(redelRes[0].Entries)) - - // validator redelegations - queryValidatorParams := types.NewQueryValidatorParams(val1.GetOperator(), 0, 0) - bz, errRes = cdc.MarshalJSON(queryValidatorParams) - require.NoError(t, errRes) - - query = abci.RequestQuery{ - Path: "/custom/staking/redelegations", - Data: bz, - } - - res, err = querier(ctx, []string{types.QueryRedelegations}, query) - require.NoError(t, err) - - errRes = cdc.UnmarshalJSON(res, &redelRes) - require.NoError(t, errRes) - require.Len(t, redelRes, 1) - require.Equal(t, redel.DelegatorAddress, redelRes[0].Redelegation.DelegatorAddress) - require.Equal(t, redel.ValidatorSrcAddress, redelRes[0].Redelegation.ValidatorSrcAddress) - require.Equal(t, redel.ValidatorDstAddress, redelRes[0].Redelegation.ValidatorDstAddress) - require.Len(t, redel.Entries, len(redelRes[0].Entries)) -} - -func TestQueryUnbondingDelegation(t *testing.T) { - cdc, app, ctx := createTestInput(t) - legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) - - addrs := simapp.AddTestAddrs(app, ctx, 2, app.StakingKeeper.TokensFromConsensusPower(ctx, 10000)) - addrAcc1, addrAcc2 := addrs[0], addrs[1] - addrVal1 := sdk.ValAddress(addrAcc1) - - // Create Validators and Delegation - val1 := teststaking.NewValidator(t, addrVal1, PKs[0]) - app.StakingKeeper.SetValidator(ctx, val1) - - // delegate - delAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 100) - _, err := app.StakingKeeper.Delegate(ctx, addrAcc1, delAmount, types.Unbonded, val1, true) - require.NoError(t, err) - applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1) - - // undelegate - undelAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 20) - _, err = app.StakingKeeper.Undelegate(ctx, addrAcc1, val1.GetOperator(), sdk.NewDecFromInt(undelAmount)) - require.NoError(t, err) - applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1) - - _, found := app.StakingKeeper.GetUnbondingDelegation(ctx, addrAcc1, val1.GetOperator()) - require.True(t, found) - - // - // found: query unbonding delegation by delegator and validator - // - queryValidatorParams := types.QueryDelegatorValidatorRequest{DelegatorAddr: addrAcc1.String(), ValidatorAddr: val1.GetOperator().String()} - bz, errRes := cdc.MarshalJSON(queryValidatorParams) - require.NoError(t, errRes) - query := abci.RequestQuery{ - Path: "/custom/staking/unbondingDelegation", - Data: bz, - } - res, err := querier(ctx, []string{types.QueryUnbondingDelegation}, query) - require.NoError(t, err) - require.NotNil(t, res) - var ubDel types.UnbondingDelegation - require.NoError(t, cdc.UnmarshalJSON(res, &ubDel)) - require.Equal(t, addrAcc1.String(), ubDel.DelegatorAddress) - require.Equal(t, val1.OperatorAddress, ubDel.ValidatorAddress) - require.Equal(t, 1, len(ubDel.Entries)) - - // - // not found: query unbonding delegation by delegator and validator - // - queryValidatorParams = types.QueryDelegatorValidatorRequest{DelegatorAddr: addrAcc2.String(), ValidatorAddr: val1.GetOperator().String()} - bz, errRes = cdc.MarshalJSON(queryValidatorParams) - require.NoError(t, errRes) - query = abci.RequestQuery{ - Path: "/custom/staking/unbondingDelegation", - Data: bz, - } - _, err = querier(ctx, []string{types.QueryUnbondingDelegation}, query) - require.Error(t, err) - - // - // found: query unbonding delegation by delegator and validator - // - queryDelegatorParams := types.NewQueryDelegatorParams(addrAcc1) - bz, errRes = cdc.MarshalJSON(queryDelegatorParams) - require.NoError(t, errRes) - query = abci.RequestQuery{ - Path: "/custom/staking/delegatorUnbondingDelegations", - Data: bz, - } - res, err = querier(ctx, []string{types.QueryDelegatorUnbondingDelegations}, query) - require.NoError(t, err) - require.NotNil(t, res) - var ubDels []types.UnbondingDelegation - require.NoError(t, cdc.UnmarshalJSON(res, &ubDels)) - require.Equal(t, 1, len(ubDels)) - require.Equal(t, addrAcc1.String(), ubDels[0].DelegatorAddress) - require.Equal(t, val1.OperatorAddress, ubDels[0].ValidatorAddress) - - // - // not found: query unbonding delegation by delegator and validator - // - queryDelegatorParams = types.NewQueryDelegatorParams(addrAcc2) - bz, errRes = cdc.MarshalJSON(queryDelegatorParams) - require.NoError(t, errRes) - query = abci.RequestQuery{ - Path: "/custom/staking/delegatorUnbondingDelegations", - Data: bz, - } - res, err = querier(ctx, []string{types.QueryDelegatorUnbondingDelegations}, query) - require.NoError(t, err) - require.NotNil(t, res) - require.NoError(t, cdc.UnmarshalJSON(res, &ubDels)) - require.Equal(t, 0, len(ubDels)) -} - -func TestQueryHistoricalInfo(t *testing.T) { - cdc, app, ctx := createTestInput(t) - legacyQuerierCdc := codec.NewAminoCodec(cdc) - querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino) - - addrs := simapp.AddTestAddrs(app, ctx, 2, app.StakingKeeper.TokensFromConsensusPower(ctx, 10000)) - addrAcc1, addrAcc2 := addrs[0], addrs[1] - addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2) - - // Create Validators and Delegation - val1 := teststaking.NewValidator(t, addrVal1, PKs[0]) - val2 := teststaking.NewValidator(t, addrVal2, PKs[1]) - vals := []types.Validator{val1, val2} - app.StakingKeeper.SetValidator(ctx, val1) - app.StakingKeeper.SetValidator(ctx, val2) - - header := tmproto.Header{ - ChainID: "HelloChain", - Height: 5, - } - hi := types.NewHistoricalInfo(header, vals, app.StakingKeeper.PowerReduction(ctx)) - app.StakingKeeper.SetHistoricalInfo(ctx, 5, &hi) - - queryHistoricalParams := types.QueryHistoricalInfoRequest{Height: 4} - bz, errRes := cdc.MarshalJSON(queryHistoricalParams) - require.NoError(t, errRes) - query := abci.RequestQuery{ - Path: "/custom/staking/historicalInfo", - Data: bz, - } - res, err := querier(ctx, []string{types.QueryHistoricalInfo}, query) - require.Error(t, err, "Invalid query passed") - require.Nil(t, res, "Invalid query returned non-nil result") - - queryHistoricalParams = types.QueryHistoricalInfoRequest{Height: 5} - bz, errRes = cdc.MarshalJSON(queryHistoricalParams) - require.NoError(t, errRes) - query.Data = bz - res, err = querier(ctx, []string{types.QueryHistoricalInfo}, query) - require.NoError(t, err, "Valid query passed") - require.NotNil(t, res, "Valid query returned nil result") - - var recv types.HistoricalInfo - require.NoError(t, cdc.UnmarshalJSON(res, &recv)) - require.Equal(t, hi, recv, "HistoricalInfo query returned wrong result") -} diff --git a/x/staking/module.go b/x/staking/module.go index 4af4bf038ee..6a2f7407247 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -137,21 +137,6 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { keeper.RegisterInvariants(ir, am.keeper) } -// Deprecated: Route returns the message routing key for the staking module. -func (am AppModule) Route() sdk.Route { - return sdk.Route{} -} - -// QuerierRoute returns the staking module's querier route name. -func (AppModule) QuerierRoute() string { - return types.QuerierRoute -} - -// LegacyQuerierHandler returns the staking module sdk.Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return keeper.NewQuerier(am.keeper, legacyQuerierCdc) -} - // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) diff --git a/x/staking/types/keys.go b/x/staking/types/keys.go index 1b86e4e5b5a..c56348789a6 100644 --- a/x/staking/types/keys.go +++ b/x/staking/types/keys.go @@ -21,9 +21,6 @@ const ( // StoreKey is the string store representation StoreKey = ModuleName - // QuerierRoute is the querier route for the staking module - QuerierRoute = ModuleName - // RouterKey is the msg router key for the staking module RouterKey = ModuleName ) diff --git a/x/upgrade/abci_test.go b/x/upgrade/abci_test.go index d20abf072ee..1bcfe0a8fce 100644 --- a/x/upgrade/abci_test.go +++ b/x/upgrade/abci_test.go @@ -33,7 +33,6 @@ type TestSuite struct { module module.BeginBlockAppModule keeper keeper.Keeper - querier sdk.Querier handler govtypesv1beta1.Handler ctx sdk.Context baseApp *baseapp.BaseApp @@ -61,7 +60,6 @@ func setupTest(t *testing.T, height int64, skip map[int64]bool) TestSuite { s.ctx = testCtx.Ctx.WithBlockHeader(tmproto.Header{Time: time.Now(), Height: height}) s.module = upgrade.NewAppModule(s.keeper) - s.querier = s.module.LegacyQuerierHandler(s.encCfg.Amino) s.handler = upgrade.NewSoftwareUpgradeProposalHandler(s.keeper) return s } @@ -177,9 +175,9 @@ func TestHaltIfTooNew(t *testing.T) { func VerifyCleared(t *testing.T, newCtx sdk.Context) { t.Log("Verify that the upgrade plan has been cleared") - bz, err := s.querier(newCtx, []string{types.QueryCurrent}, abci.RequestQuery{}) - require.NoError(t, err) - require.Nil(t, bz, string(bz)) + plan, _ := s.keeper.GetUpgradePlan(newCtx) + expected := types.Plan{} + require.Equal(t, plan, expected) } func TestCanClear(t *testing.T) { diff --git a/x/upgrade/keeper/querier.go b/x/upgrade/keeper/querier.go deleted file mode 100644 index 227d770f206..00000000000 --- a/x/upgrade/keeper/querier.go +++ /dev/null @@ -1,64 +0,0 @@ -package keeper - -import ( - "encoding/binary" - - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/cosmos/cosmos-sdk/x/upgrade/types" - - abci "github.com/tendermint/tendermint/abci/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// NewQuerier creates a querier for upgrade cli and REST endpoints -func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - switch path[0] { - - case types.QueryCurrent: - return queryCurrent(ctx, req, k, legacyQuerierCdc) - - case types.QueryApplied: - return queryApplied(ctx, req, k, legacyQuerierCdc) - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint: %s", types.ModuleName, path[0]) - } - } -} - -func queryCurrent(ctx sdk.Context, _ abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - plan, has := k.GetUpgradePlan(ctx) - if !has { - return nil, nil - } - - res, err := legacyQuerierCdc.MarshalJSON(&plan) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} - -func queryApplied(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryAppliedPlanRequest - - err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - applied := k.GetDoneHeight(ctx, params.Name) - if applied == 0 { - return nil, nil - } - - bz := make([]byte, 8) - binary.BigEndian.PutUint64(bz, uint64(applied)) - - return bz, nil -} diff --git a/x/upgrade/module.go b/x/upgrade/module.go index a3138ddf807..24de870db39 100644 --- a/x/upgrade/module.go +++ b/x/upgrade/module.go @@ -96,19 +96,6 @@ func NewAppModule(keeper keeper.Keeper) AppModule { // RegisterInvariants does nothing, there are no invariants to enforce func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// Deprecated: Route returns the message routing key for the upgrade module. -func (AppModule) Route() sdk.Route { - return sdk.Route{} -} - -// QuerierRoute returns the route we respond to for abci queries -func (AppModule) QuerierRoute() string { return types.QuerierKey } - -// LegacyQuerierHandler registers a query handler to respond to the module-specific queries -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return keeper.NewQuerier(am.keeper, legacyQuerierCdc) -} - // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) diff --git a/x/upgrade/types/keys.go b/x/upgrade/types/keys.go index 45128fc7049..0307fff10bf 100644 --- a/x/upgrade/types/keys.go +++ b/x/upgrade/types/keys.go @@ -11,9 +11,6 @@ const ( // StoreKey is the prefix under which we store this module's data StoreKey = ModuleName - - // QuerierKey is used to handle abci_query requests - QuerierKey = ModuleName ) const (