From c5b89c30589d5d500b1ff6611128a93d6eaf80a2 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 30 May 2019 12:45:09 -0400 Subject: [PATCH 01/23] porting changes from first branch --- types/config.go | 4 ++ types/module.go | 41 ++++++++++++--- x/auth/genaccounts/module.go | 15 +++++- x/auth/module.go | 20 +++++++- x/bank/module.go | 19 ++++++- x/crisis/client/cli/tx.go | 14 ++++++ x/crisis/client/module_client.go | 42 ---------------- x/crisis/module.go | 19 ++++++- x/distribution/client/cli/query.go | 21 ++++++++ x/distribution/client/cli/tx.go | 3 +- x/distribution/client/cli/tx_test.go | 5 +- x/distribution/client/module_client.go | 54 -------------------- x/distribution/module.go | 22 +++++++- x/genutil/module.go | 15 +++++- x/gov/client/cli/query.go | 24 +++++++++ x/gov/client/cli/tx.go | 26 ++++++++++ x/gov/client/module_client.go | 69 -------------------------- x/gov/keeper.go | 1 + x/gov/module.go | 33 +++++++++++- x/mint/client/cli/query.go | 18 +++++++ x/mint/client/module_client.go | 47 ------------------ x/mint/module.go | 22 +++++++- x/slashing/client/cli/query.go | 23 ++++++++- x/slashing/client/cli/tx.go | 15 ++++++ x/slashing/client/module_client.go | 53 -------------------- x/slashing/client/rest/rest.go | 5 +- x/slashing/client/rest/tx.go | 7 ++- x/slashing/module.go | 22 +++++++- x/staking/client/cli/query.go | 26 ++++++++++ x/staking/client/cli/tx.go | 18 +++++++ x/staking/client/module_client.go | 63 ----------------------- x/staking/module.go | 17 +++++++ 32 files changed, 428 insertions(+), 355 deletions(-) delete mode 100644 x/crisis/client/module_client.go delete mode 100644 x/distribution/client/module_client.go delete mode 100644 x/gov/client/module_client.go delete mode 100644 x/mint/client/module_client.go delete mode 100644 x/slashing/client/module_client.go delete mode 100644 x/staking/client/module_client.go diff --git a/types/config.go b/types/config.go index 96d12276cc81..9b6812d9c0d4 100644 --- a/types/config.go +++ b/types/config.go @@ -85,11 +85,13 @@ func (config *Config) SetAddressVerifier(addressVerifier func([]byte) error) { config.addressVerifier = addressVerifier } +// TODO func (config *Config) SetCoinType(coinType uint32) { config.assertNotSealed() config.coinType = coinType } +// TODO func (config *Config) SetFullFundraiserPath(fullFundraiserPath string) { config.assertNotSealed() config.fullFundraiserPath = fullFundraiserPath @@ -144,10 +146,12 @@ func (config *Config) GetAddressVerifier() func([]byte) error { return config.addressVerifier } +// TODO func (config *Config) GetCoinType() uint32 { return config.coinType } +// TODO func (config *Config) GetFullFundraiserPath() string { return config.fullFundraiserPath } diff --git a/types/module.go b/types/module.go index ff1743a55d9f..4bc3dbcd1250 100644 --- a/types/module.go +++ b/types/module.go @@ -22,6 +22,7 @@ ModuleBasicManager. package types import ( + "context" "encoding/json" "github.com/cosmos/cosmos-sdk/codec" @@ -29,19 +30,20 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) -// ModuleClient helps modules provide a standard interface for exporting client functionality -type ModuleClient interface { - GetQueryCmd() *cobra.Command - GetTxCmd() *cobra.Command -} - //__________________________________________________________________________________________ // AppModuleBasic is the standard form for basic non-dependant elements of an application module. type AppModuleBasic interface { Name() string RegisterCodec(*codec.Codec) + + // genesis DefaultGenesis() json.RawMessage ValidateGenesis(json.RawMessage) error + + // client functionality + RegisterRESTRoutes(context.CLIContext, *mux.Router, *codec.Codec) + GetTxCmd() *cobra.Command + GetQueryCmd() *cobra.Command } // collections of AppModuleBasic @@ -77,6 +79,33 @@ func (mbm ModuleBasicManager) ValidateGenesis(genesis map[string]json.RawMessage return nil } +// RegisterRestRoutes registers all module rest routes +func (mbm ModuleBasicManager) RegisterRESTRoutes( + ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + + for _, mb := range mbm { + mb.RegisterRESTRoutes(ctx, rtr, cdc) + } +} + +// add all tx commands to the rootTxCmd +func (mbm ModuleBasicManager) AddTxCommands(rootTxCmd *cobra.Command) { + for _, mb := range mbm { + if cmd := mb.GetTxCmd(); cmd != nil { + rootTxCmd.AddCommand(cmd) + } + } +} + +// add all query commands to the rootQueryCmd +func (mbm ModuleBasicManager) AddQueryCommands(rootQueryCmd *cobra.Command) { + for _, mb := range mbm { + if cmd := mb.GetQueryCmd(); cmd != nil { + rootQueryCmd.AddCommand(cmd) + } + } +} + //_________________________________________________________ // AppModuleGenesis is the standard form for an application module genesis functions type AppModuleGenesis interface { diff --git a/x/auth/genaccounts/module.go b/x/auth/genaccounts/module.go index 89925e185c9a..b7c6564b267a 100644 --- a/x/auth/genaccounts/module.go +++ b/x/auth/genaccounts/module.go @@ -3,10 +3,13 @@ package genaccounts import ( "encoding/json" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - abci "github.com/tendermint/tendermint/abci/types" ) var ( @@ -43,6 +46,16 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router, _ *codec.Codec) { +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } + // extra function from sdk.AppModuleBasic // iterate the genesis accounts and perform an operation at each of them // - to used by other modules diff --git a/x/auth/module.go b/x/auth/module.go index f7381e21f335..7ddb5b744502 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -3,9 +3,13 @@ package auth import ( "encoding/json" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/x/auth/client/rest" ) var ( @@ -44,6 +48,20 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// XXX +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + rest.RegisterRoutes(ctx, rtr, cdc, StoreKey) +} + +// TODO +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } + +// TODO +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } + //___________________________ // app module object type AppModule struct { diff --git a/x/bank/module.go b/x/bank/module.go index 53be045fcdb2..553e6ad6f79b 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -3,10 +3,14 @@ package bank import ( "encoding/json" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/x/bank/client/rest" ) var ( @@ -47,6 +51,19 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// register rest routes +func RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + rest.RegisterRoutes(ctx, rtr, cdc, StoreKey) +} + +// TODO +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } + +// TODO +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } + //___________________________ // app module type AppModule struct { diff --git a/x/crisis/client/cli/tx.go b/x/crisis/client/cli/tx.go index 8f1147793301..91c4b3a7d232 100644 --- a/x/crisis/client/cli/tx.go +++ b/x/crisis/client/cli/tx.go @@ -4,6 +4,7 @@ package cli import ( "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" @@ -31,3 +32,16 @@ func GetCmdInvariantBroken(cdc *codec.Codec) *cobra.Command { } return cmd } + +// GetTxCmd returns the transaction commands for this module +func GetTxCmd(cdc *amino.Codec) *cobra.Command { + txCmd := &cobra.Command{ + Use: crisis.ModuleName, + Short: "crisis transactions subcommands", + } + + txCmd.AddCommand(client.PostCommands( + GetCmdInvariantBroken(cdc), + )...) + return txCmd +} diff --git a/x/crisis/client/module_client.go b/x/crisis/client/module_client.go deleted file mode 100644 index 12c9d2282b49..000000000000 --- a/x/crisis/client/module_client.go +++ /dev/null @@ -1,42 +0,0 @@ -package client - -import ( - "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/x/crisis" - "github.com/cosmos/cosmos-sdk/x/crisis/client/cli" -) - -// ModuleClient exports all client functionality from this module -type ModuleClient struct { - storeKey string - cdc *amino.Codec -} - -// NewModuleClient creates a new ModuleClient object -func NewModuleClient(storeKey string, cdc *amino.Codec) ModuleClient { - return ModuleClient{ - storeKey: storeKey, - cdc: cdc, - } -} - -// GetQueryCmd returns the cli query commands for this module -func (ModuleClient) GetQueryCmd() *cobra.Command { - return nil -} - -// GetTxCmd returns the transaction commands for this module -func (mc ModuleClient) GetTxCmd() *cobra.Command { - txCmd := &cobra.Command{ - Use: crisis.ModuleName, - Short: "crisis transactions subcommands", - } - - txCmd.AddCommand(client.PostCommands( - cli.GetCmdInvariantBroken(mc.cdc), - )...) - return txCmd -} diff --git a/x/crisis/module.go b/x/crisis/module.go index 7bb64f10714c..18209cab6842 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -3,11 +3,14 @@ package crisis import ( "encoding/json" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/x/crisis/client/cli" ) var ( @@ -48,6 +51,20 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd(moduleCdc) +} + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return nil +} + //___________________________ // app module for bank type AppModule struct { diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index 0013d3d08640..e985b30bc3a9 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -6,7 +6,9 @@ import ( "strings" "github.com/spf13/cobra" + amino "github.com/tendermint/go-amino" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -16,6 +18,25 @@ import ( "github.com/cosmos/cosmos-sdk/x/distribution/types" ) +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd(storeKey string, cdc *amino.Codec) *cobra.Command { + distQueryCmd := &cobra.Command{ + Use: "distr", + Short: "Querying commands for the distribution module", + } + + distQueryCmd.AddCommand(client.GetCommands( + GetCmdQueryParams(storeKey, cdc), + GetCmdQueryValidatorOutstandingRewards(storeKey, cdc), + GetCmdQueryValidatorCommission(storeKey, cdc), + GetCmdQueryValidatorSlashes(storeKey, cdc), + GetCmdQueryDelegatorRewards(storeKey, cdc), + GetCmdQueryCommunityPool(storeKey, cdc), + )...) + + return distQueryCmd +} + // GetCmdQueryParams implements the query params command. func GetCmdQueryParams(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index 44c737085417..2626b7faee9b 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -36,13 +36,14 @@ const ( // GetTxCmd returns the transaction commands for this module func GetTxCmd(storeKey string, cdc *amino.Codec) *cobra.Command { distTxCmd := &cobra.Command{ - Use: "dist", + Use: "distr", Short: "Distribution transactions subcommands", } distTxCmd.AddCommand(client.PostCommands( GetCmdWithdrawRewards(cdc), GetCmdSetWithdrawAddr(cdc), + distCmds.GetCmdWithdrawAllRewards(cdc, storeKey), )...) return distTxCmd diff --git a/x/distribution/client/cli/tx_test.go b/x/distribution/client/cli/tx_test.go index c8f80f553f97..d1423cbf8909 100644 --- a/x/distribution/client/cli/tx_test.go +++ b/x/distribution/client/cli/tx_test.go @@ -1,6 +1,8 @@ package cli import ( + "testing" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" @@ -8,7 +10,6 @@ import ( authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" "github.com/stretchr/testify/assert" "github.com/tendermint/tendermint/crypto/secp256k1" - "testing" ) func createFakeTxBuilder() authtxb.TxBuilder { @@ -56,7 +57,7 @@ func Test_splitAndCall_Splitting(t *testing.T) { callCount := 0 err := splitAndApply( func(ctx context.CLIContext, txBldr authtxb.TxBuilder, msgs []sdk.Msg) error { - callCount += 1 + callCount++ assert.NotNil(t, ctx) assert.NotNil(t, txBldr) diff --git a/x/distribution/client/module_client.go b/x/distribution/client/module_client.go deleted file mode 100644 index 780b0cabd8f5..000000000000 --- a/x/distribution/client/module_client.go +++ /dev/null @@ -1,54 +0,0 @@ -package client - -import ( - "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" - - "github.com/cosmos/cosmos-sdk/client" - distCmds "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" -) - -// ModuleClient exports all client functionality from this module -type ModuleClient struct { - storeKey string - cdc *amino.Codec -} - -func NewModuleClient(storeKey string, cdc *amino.Codec) ModuleClient { - return ModuleClient{storeKey, cdc} -} - -// GetQueryCmd returns the cli query commands for this module -func (mc ModuleClient) GetQueryCmd() *cobra.Command { - distQueryCmd := &cobra.Command{ - Use: "distr", - Short: "Querying commands for the distribution module", - } - - distQueryCmd.AddCommand(client.GetCommands( - distCmds.GetCmdQueryParams(mc.storeKey, mc.cdc), - distCmds.GetCmdQueryValidatorOutstandingRewards(mc.storeKey, mc.cdc), - distCmds.GetCmdQueryValidatorCommission(mc.storeKey, mc.cdc), - distCmds.GetCmdQueryValidatorSlashes(mc.storeKey, mc.cdc), - distCmds.GetCmdQueryDelegatorRewards(mc.storeKey, mc.cdc), - distCmds.GetCmdQueryCommunityPool(mc.storeKey, mc.cdc), - )...) - - return distQueryCmd -} - -// GetTxCmd returns the transaction commands for this module -func (mc ModuleClient) GetTxCmd() *cobra.Command { - distTxCmd := &cobra.Command{ - Use: "distr", - Short: "Distribution transactions subcommands", - } - - distTxCmd.AddCommand(client.PostCommands( - distCmds.GetCmdWithdrawRewards(mc.cdc), - distCmds.GetCmdSetWithdrawAddr(mc.cdc), - distCmds.GetCmdWithdrawAllRewards(mc.cdc, mc.storeKey), - )...) - - return distTxCmd -} diff --git a/x/distribution/module.go b/x/distribution/module.go index 03e7a5df1aa3..dac75487684b 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -3,9 +3,14 @@ package distribution import ( "encoding/json" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" + "github.com/cosmos/cosmos-sdk/x/distribution/client/rest" ) var ( @@ -41,6 +46,21 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + rest.RegisterRoutes(ctx, rtr, cdc, StoreKey) +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd(StoreKey, moduleCdc) +} + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(StoreKey, moduleCdc) +} + // app module type AppModule struct { AppModuleBasic diff --git a/x/genutil/module.go b/x/genutil/module.go index ba69d4f54b7e..5f87d6ae57cd 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -3,9 +3,12 @@ package genutil import ( "encoding/json" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" ) var ( @@ -42,6 +45,16 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router, _ *codec.Codec) { +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } + //___________________________ // app module type AppModule struct { diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index fcb0eb636b09..d15cf7d9b4b8 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -8,6 +8,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -16,6 +17,29 @@ import ( gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" ) +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd(storeKey string, cdc *amino.Codec) *cobra.Command { + // Group gov queries under a subcommand + govQueryCmd := &cobra.Command{ + Use: gov.ModuleName, + Short: "Querying commands for the governance module", + } + + govQueryCmd.AddCommand(client.GetCommands( + GetCmdQueryProposal(storeKey, cdc), + GetCmdQueryProposals(storeKey, cdc), + GetCmdQueryVote(storeKey, cdc), + GetCmdQueryVotes(storeKey, cdc), + GetCmdQueryParam(storeKey, cdc), + GetCmdQueryParams(storeKey, cdc), + GetCmdQueryProposer(storeKey, cdc), + GetCmdQueryDeposit(storeKey, cdc), + GetCmdQueryDeposits(storeKey, cdc), + GetCmdQueryTally(storeKey, cdc))...) + + return govQueryCmd +} + // GetCmdQueryProposal implements the query proposal command. func GetCmdQueryProposal(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index de1b662eed52..c8c2ee4bccf4 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -4,6 +4,7 @@ import ( "fmt" "strconv" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" @@ -49,6 +50,31 @@ var ProposalFlags = []string{ FlagDeposit, } +// GetTxCmd returns the transaction commands for this module +// governance ModuleClient is slightly different from other ModuleClients in that +// it contains a slice of "proposal" child commands. These commands are respective +// to proposal type handlers that are implemented in other modules but are mounted +// under the governance CLI (eg. parameter change proposals). +func GetTxCmd(storeKey string, cdc *amino.Codec, pcmds ...*cobra.Command) *cobra.Command { + govTxCmd := &cobra.Command{ + Use: gov.ModuleName, + Short: "Governance transactions subcommands", + } + + cmdSubmitProp := GetCmdSubmitProposal(cdc) + for _, pcmd := range pcmds { + cmdSubmitProp.AddCommand(client.PostCommands(pcmd)[0]) + } + + govTxCmd.AddCommand(client.PostCommands( + GetCmdDeposit(storeKey, cdc), + GetCmdVote(storeKey, cdc), + cmdSubmitProp, + )...) + + return govTxCmd +} + // GetCmdSubmitProposal implements submitting a proposal transaction command. func GetCmdSubmitProposal(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ diff --git a/x/gov/client/module_client.go b/x/gov/client/module_client.go deleted file mode 100644 index dbdf3aca99d5..000000000000 --- a/x/gov/client/module_client.go +++ /dev/null @@ -1,69 +0,0 @@ -package client - -import ( - "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/x/gov" - govCli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" -) - -// ModuleClient exports all client functionality from the governance module. The -// governance ModuleClient is slightly different from other ModuleClients in that -// it contains a slice of "proposal" child commands. These commands are respective -// to proposal type handlers that are implemented in other modules but are mounted -// under the governance CLI (eg. parameter change proposals). -type ModuleClient struct { - storeKey string - cdc *amino.Codec - pcmds []*cobra.Command -} - -func NewModuleClient(storeKey string, cdc *amino.Codec, pcmds ...*cobra.Command) ModuleClient { - return ModuleClient{storeKey, cdc, pcmds} -} - -// GetQueryCmd returns the cli query commands for this module -func (mc ModuleClient) GetQueryCmd() *cobra.Command { - // Group gov queries under a subcommand - govQueryCmd := &cobra.Command{ - Use: gov.ModuleName, - Short: "Querying commands for the governance module", - } - - govQueryCmd.AddCommand(client.GetCommands( - govCli.GetCmdQueryProposal(mc.storeKey, mc.cdc), - govCli.GetCmdQueryProposals(mc.storeKey, mc.cdc), - govCli.GetCmdQueryVote(mc.storeKey, mc.cdc), - govCli.GetCmdQueryVotes(mc.storeKey, mc.cdc), - govCli.GetCmdQueryParam(mc.storeKey, mc.cdc), - govCli.GetCmdQueryParams(mc.storeKey, mc.cdc), - govCli.GetCmdQueryProposer(mc.storeKey, mc.cdc), - govCli.GetCmdQueryDeposit(mc.storeKey, mc.cdc), - govCli.GetCmdQueryDeposits(mc.storeKey, mc.cdc), - govCli.GetCmdQueryTally(mc.storeKey, mc.cdc))...) - - return govQueryCmd -} - -// GetTxCmd returns the transaction commands for this module -func (mc ModuleClient) GetTxCmd() *cobra.Command { - govTxCmd := &cobra.Command{ - Use: gov.ModuleName, - Short: "Governance transactions subcommands", - } - - cmdSubmitProp := govCli.GetCmdSubmitProposal(mc.cdc) - for _, pcmd := range mc.pcmds { - cmdSubmitProp.AddCommand(client.PostCommands(pcmd)[0]) - } - - govTxCmd.AddCommand(client.PostCommands( - govCli.GetCmdDeposit(mc.cdc), - govCli.GetCmdVote(mc.cdc), - cmdSubmitProp, - )...) - - return govTxCmd -} diff --git a/x/gov/keeper.go b/x/gov/keeper.go index 79786cc0ba00..2bb2999d8e44 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -11,6 +11,7 @@ import ( "github.com/tendermint/tendermint/libs/log" ) +// TODO var ( // TODO: Find another way to implement this without using accounts, or find a cleaner way to implement it using accounts. DepositedCoinsAccAddr = sdk.AccAddress(crypto.AddressHash([]byte("govDepositedCoins"))) diff --git a/x/gov/module.go b/x/gov/module.go index 7db8824a0db5..b0ea50488bf0 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -3,10 +3,15 @@ package gov import ( "encoding/json" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" + "github.com/cosmos/cosmos-sdk/x/gov/client/rest" "github.com/cosmos/cosmos-sdk/x/gov/types" - abci "github.com/tendermint/tendermint/abci/types" ) var ( @@ -15,7 +20,16 @@ var ( ) // app module basics object -type AppModuleBasic struct{} +type AppModuleBasic struct { + proposalCmds []*cobra.Command // proposal subcommands which live in goverance +} + +// NewAppModuleBasic creates a new AppModuleBasic object +func NewAppModuleBasic(proposalCmds []*cobra.Command) AppModuleBasic { + return AppModuleBasic{ + proposalCmds: proposalCmds, + } +} var _ sdk.AppModuleBasic = AppModuleBasic{} @@ -44,6 +58,21 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + rest.RegisterRoutes(ctx, rtr, cdc, StoreKey) +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd(StoreKey, moduleCdc) +} + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(StoreKey, moduleCdc) +} + //___________________________ // app module type AppModule struct { diff --git a/x/mint/client/cli/query.go b/x/mint/client/cli/query.go index 65bde6adeb32..91f3f88aabf3 100644 --- a/x/mint/client/cli/query.go +++ b/x/mint/client/cli/query.go @@ -11,6 +11,24 @@ import ( "github.com/cosmos/cosmos-sdk/x/mint" ) +// GetQueryCmd returns the cli query commands for the minting module. +func GetQueryCmd(cdc *codec.Codec) *cobra.Command { + mintingQueryCmd := &cobra.Command{ + Use: mint.ModuleName, + Short: "Querying commands for the minting module", + } + + mintingQueryCmd.AddCommand( + sdkclient.GetCommands( + GetCmdQueryParams(cdc), + GetCmdQueryInflation(cdc), + GetCmdQueryAnnualProvisions(cdc), + )..., + ) + + return mintingQueryCmd +} + // GetCmdQueryParams implements a command to return the current minting // parameters. func GetCmdQueryParams(cdc *codec.Codec) *cobra.Command { diff --git a/x/mint/client/module_client.go b/x/mint/client/module_client.go deleted file mode 100644 index 4a22b6e763b8..000000000000 --- a/x/mint/client/module_client.go +++ /dev/null @@ -1,47 +0,0 @@ -package client - -import ( - "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" - - sdkclient "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/mint/client/cli" -) - -type ModuleClient struct { - storeKey string - cdc *amino.Codec -} - -func NewModuleClient(storeKey string, cdc *amino.Codec) ModuleClient { - return ModuleClient{storeKey, cdc} -} - -// GetQueryCmd returns the cli query commands for the minting module. -func (mc ModuleClient) GetQueryCmd() *cobra.Command { - mintingQueryCmd := &cobra.Command{ - Use: mint.ModuleName, - Short: "Querying commands for the minting module", - } - - mintingQueryCmd.AddCommand( - sdkclient.GetCommands( - cli.GetCmdQueryParams(mc.cdc), - cli.GetCmdQueryInflation(mc.cdc), - cli.GetCmdQueryAnnualProvisions(mc.cdc), - )..., - ) - - return mintingQueryCmd -} - -// GetTxCmd returns the transaction commands for the minting module. -func (mc ModuleClient) GetTxCmd() *cobra.Command { - mintTxCmd := &cobra.Command{ - Use: mint.ModuleName, - Short: "Minting transaction subcommands", - } - - return mintTxCmd -} diff --git a/x/mint/module.go b/x/mint/module.go index d645624fa09f..7d6fad7d33e1 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -3,9 +3,14 @@ package mint import ( "encoding/json" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/x/mint/client/cli" + "github.com/cosmos/cosmos-sdk/x/mint/client/rest" ) var ( @@ -44,6 +49,21 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + rest.RegisterRoutes(ctx, rtr, cdc, StoreKey) +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd() *cobra.Command { + return nil +} + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(moduleCdc) +} + //___________________________ // app module type AppModule struct { diff --git a/x/slashing/client/cli/query.go b/x/slashing/client/cli/query.go index a92c5525d0b2..9c4d83777374 100644 --- a/x/slashing/client/cli/query.go +++ b/x/slashing/client/cli/query.go @@ -6,12 +6,33 @@ import ( "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" // XXX fix + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/slashing" ) +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { + // Group slashing queries under a subcommand + slashingQueryCmd := &cobra.Command{ + Use: slashing.ModuleName, + Short: "Querying commands for the slashing module", + } + + slashingQueryCmd.AddCommand( + client.GetCommands( + GetCmdQuerySigningInfo(storeKey, cdc), + GetCmdQueryParams(cdc), + )..., + ) + + return slashingQueryCmd + +} + // GetCmdQuerySigningInfo implements the command to query signing info. func GetCmdQuerySigningInfo(storeName string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ diff --git a/x/slashing/client/cli/tx.go b/x/slashing/client/cli/tx.go index c049ca3afac7..9cf4d348cf28 100644 --- a/x/slashing/client/cli/tx.go +++ b/x/slashing/client/cli/tx.go @@ -1,6 +1,7 @@ package cli import ( + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" @@ -11,6 +12,20 @@ import ( "github.com/spf13/cobra" ) +// GetTxCmd returns the transaction commands for this module +func GetTxCmd(cdc *codec.Codec) *cobra.Command { + slashingTxCmd := &cobra.Command{ + Use: slashing.ModuleName, + Short: "Slashing transactions subcommands", + } + + slashingTxCmd.AddCommand(client.PostCommands( + GetCmdUnjail(cdc), + )...) + + return slashingTxCmd +} + // GetCmdUnjail implements the create unjail validator command. func GetCmdUnjail(cdc *codec.Codec) *cobra.Command { return &cobra.Command{ diff --git a/x/slashing/client/module_client.go b/x/slashing/client/module_client.go deleted file mode 100644 index aca581f2e8a8..000000000000 --- a/x/slashing/client/module_client.go +++ /dev/null @@ -1,53 +0,0 @@ -package client - -import ( - "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" -) - -// ModuleClient exports all client functionality from this module -type ModuleClient struct { - storeKey string - cdc *amino.Codec -} - -func NewModuleClient(storeKey string, cdc *amino.Codec) ModuleClient { - return ModuleClient{storeKey, cdc} -} - -// GetQueryCmd returns the cli query commands for this module -func (mc ModuleClient) GetQueryCmd() *cobra.Command { - // Group slashing queries under a subcommand - slashingQueryCmd := &cobra.Command{ - Use: slashing.ModuleName, - Short: "Querying commands for the slashing module", - } - - slashingQueryCmd.AddCommand( - client.GetCommands( - cli.GetCmdQuerySigningInfo(mc.storeKey, mc.cdc), - cli.GetCmdQueryParams(mc.cdc), - )..., - ) - - return slashingQueryCmd - -} - -// GetTxCmd returns the transaction commands for this module -func (mc ModuleClient) GetTxCmd() *cobra.Command { - slashingTxCmd := &cobra.Command{ - Use: slashing.ModuleName, - Short: "Slashing transactions subcommands", - } - - slashingTxCmd.AddCommand(client.PostCommands( - cli.GetCmdUnjail(mc.cdc), - )...) - - return slashingTxCmd -} diff --git a/x/slashing/client/rest/rest.go b/x/slashing/client/rest/rest.go index d06cd719df20..d3bfc07350b9 100644 --- a/x/slashing/client/rest/rest.go +++ b/x/slashing/client/rest/rest.go @@ -5,11 +5,10 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" ) // RegisterRoutes registers staking-related REST handlers to a router -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, kb keys.Keybase) { +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { registerQueryRoutes(cliCtx, r, cdc) - registerTxRoutes(cliCtx, r, cdc, kb) + registerTxRoutes(cliCtx, r, cdc) } diff --git a/x/slashing/client/rest/tx.go b/x/slashing/client/rest/tx.go index 95b93740b0ac..1ca16cbc85ee 100644 --- a/x/slashing/client/rest/tx.go +++ b/x/slashing/client/rest/tx.go @@ -9,16 +9,15 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" clientrest "github.com/cosmos/cosmos-sdk/client/rest" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/slashing" ) -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, kb keys.Keybase) { +func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { r.HandleFunc( "/slashing/validators/{validatorAddr}/unjail", - unjailRequestHandlerFn(cdc, kb, cliCtx), + unjailRequestHandlerFn(cdc, cliCtx), ).Methods("POST") } @@ -27,7 +26,7 @@ type UnjailReq struct { BaseReq rest.BaseReq `json:"base_req"` } -func unjailRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { +func unjailRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) diff --git a/x/slashing/module.go b/x/slashing/module.go index 15caaf6bb429..7e5d226c5103 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -3,9 +3,14 @@ package slashing import ( "encoding/json" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" + "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" ) var ( @@ -46,6 +51,21 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + rest.RegisterRoutes(ctx, rtr, cdc, StoreKey) +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd(StoreKey, moduleCdc) +} + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(moduleCdc) +} + //___________________________ // app module type AppModule struct { diff --git a/x/staking/client/cli/query.go b/x/staking/client/cli/query.go index cfe526592d61..b1548af4a00d 100644 --- a/x/staking/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -6,6 +6,7 @@ import ( "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -14,6 +15,31 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/types" ) +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { + stakingQueryCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Querying commands for the staking module", + } + stakingQueryCmd.AddCommand(client.GetCommands( + GetCmdQueryDelegation(mc.storeKey, mc.cdc), + GetCmdQueryDelegations(mc.storeKey, mc.cdc), + GetCmdQueryUnbondingDelegation(mc.storeKey, mc.cdc), + GetCmdQueryUnbondingDelegations(mc.storeKey, mc.cdc), + GetCmdQueryRedelegation(mc.storeKey, mc.cdc), + GetCmdQueryRedelegations(mc.storeKey, mc.cdc), + GetCmdQueryValidator(mc.storeKey, mc.cdc), + GetCmdQueryValidators(mc.storeKey, mc.cdc), + GetCmdQueryValidatorDelegations(mc.storeKey, mc.cdc), + GetCmdQueryValidatorUnbondingDelegations(mc.storeKey, mc.cdc), + GetCmdQueryValidatorRedelegations(mc.storeKey, mc.cdc), + GetCmdQueryParams(mc.storeKey, mc.cdc), + GetCmdQueryPool(mc.storeKey, mc.cdc))...) + + return stakingQueryCmd + +} + // GetCmdQueryValidator implements the validator query command. func GetCmdQueryValidator(storeName string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index 3ece27ae3e6a..c091dce8ad12 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -23,6 +23,24 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/types" ) +// GetTxCmd returns the transaction commands for this module +func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command { + stakingTxCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Staking transaction subcommands", + } + + stakingTxCmd.AddCommand(client.PostCommands( + GetCmdCreateValidator(mc.cdc), + GetCmdEditValidator(mc.cdc), + GetCmdDelegate(mc.cdc), + GetCmdRedelegate(mc.storeKey, mc.cdc), + GetCmdUnbond(mc.storeKey, mc.cdc), + )...) + + return stakingTxCmd +} + // GetCmdCreateValidator implements the create validator command handler. func GetCmdCreateValidator(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ diff --git a/x/staking/client/module_client.go b/x/staking/client/module_client.go deleted file mode 100644 index 754e8c5c8500..000000000000 --- a/x/staking/client/module_client.go +++ /dev/null @@ -1,63 +0,0 @@ -package client - -import ( - "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/x/staking/client/cli" - "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// ModuleClient exports all client functionality from this module -type ModuleClient struct { - storeKey string - cdc *amino.Codec -} - -func NewModuleClient(storeKey string, cdc *amino.Codec) ModuleClient { - return ModuleClient{storeKey, cdc} -} - -// GetQueryCmd returns the cli query commands for this module -func (mc ModuleClient) GetQueryCmd() *cobra.Command { - stakingQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the staking module", - } - stakingQueryCmd.AddCommand(client.GetCommands( - cli.GetCmdQueryDelegation(mc.storeKey, mc.cdc), - cli.GetCmdQueryDelegations(mc.storeKey, mc.cdc), - cli.GetCmdQueryUnbondingDelegation(mc.storeKey, mc.cdc), - cli.GetCmdQueryUnbondingDelegations(mc.storeKey, mc.cdc), - cli.GetCmdQueryRedelegation(mc.storeKey, mc.cdc), - cli.GetCmdQueryRedelegations(mc.storeKey, mc.cdc), - cli.GetCmdQueryValidator(mc.storeKey, mc.cdc), - cli.GetCmdQueryValidators(mc.storeKey, mc.cdc), - cli.GetCmdQueryValidatorDelegations(mc.storeKey, mc.cdc), - cli.GetCmdQueryValidatorUnbondingDelegations(mc.storeKey, mc.cdc), - cli.GetCmdQueryValidatorRedelegations(mc.storeKey, mc.cdc), - cli.GetCmdQueryParams(mc.storeKey, mc.cdc), - cli.GetCmdQueryPool(mc.storeKey, mc.cdc))...) - - return stakingQueryCmd - -} - -// GetTxCmd returns the transaction commands for this module -func (mc ModuleClient) GetTxCmd() *cobra.Command { - stakingTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Staking transaction subcommands", - } - - stakingTxCmd.AddCommand(client.PostCommands( - cli.GetCmdCreateValidator(mc.cdc), - cli.GetCmdEditValidator(mc.cdc), - cli.GetCmdDelegate(mc.cdc), - cli.GetCmdRedelegate(mc.storeKey, mc.cdc), - cli.GetCmdUnbond(mc.storeKey, mc.cdc), - )...) - - return stakingTxCmd -} diff --git a/x/staking/module.go b/x/staking/module.go index aebb11401f40..3876f7ca5251 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -3,6 +3,7 @@ package staking import ( "encoding/json" + "github.com/spf13/cobra" flag "github.com/spf13/pflag" abci "github.com/tendermint/tendermint/abci/types" @@ -14,6 +15,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" "github.com/cosmos/cosmos-sdk/x/staking/client/cli" + "github.com/cosmos/cosmos-sdk/x/staking/client/rest" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -52,6 +54,21 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + rest.RegisterRoutes(ctx, rtr, cdc, StoreKey) +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd(moduleCdc, StoreKey) +} + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(moduleCdc, StoreKey) +} + //_____________________________________ // extra helpers From f4e2f936ed694a55bd89fa6bb39822fd921081e1 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 30 May 2019 13:57:53 -0400 Subject: [PATCH 02/23] fix import cycles --- client/context/context.go | 10 +-- client/context/query.go | 10 +-- x/auth/client/rest/query.go | 12 +-- x/auth/genesis.go | 42 ---------- x/auth/keeper.go | 23 ------ x/auth/{ => types}/account.go | 2 +- x/auth/{ => types}/account_test.go | 2 +- x/auth/{ => types}/codec.go | 2 +- x/auth/{ => types}/feekeeper.go | 2 +- x/auth/{ => types}/feekeeper_test.go | 2 +- x/auth/types/genesis.go | 47 ++++++++++++ x/auth/types/keys.go | 26 +++++++ x/auth/{ => types}/stdtx.go | 2 +- x/auth/{ => types}/stdtx_test.go | 2 +- x/bank/bench_test.go | 7 +- x/bank/client/rest/sendtx.go | 6 +- x/bank/module.go | 3 +- x/bank/{ => types}/codec.go | 2 +- x/bank/{ => types}/errors.go | 2 +- x/bank/{ => types}/msgs.go | 2 +- x/bank/{ => types}/msgs_test.go | 2 +- x/crisis/client/cli/tx.go | 6 +- x/crisis/module.go | 3 +- x/crisis/types/keys.go | 6 ++ x/crisis/{msg.go => types/msgs.go} | 2 +- x/distribution/client/cli/query.go | 5 +- x/distribution/client/cli/tx.go | 4 +- x/distribution/client/cli/tx_test.go | 5 +- x/distribution/client/common/common.go | 32 ++++---- x/distribution/client/rest/query.go | 5 +- x/distribution/client/rest/rest.go | 7 +- x/gov/client/rest/rest.go | 46 +++++------ x/gov/client/utils/query.go | 54 ++++++------- x/gov/client/utils/utils.go | 14 ++-- x/gov/module.go | 2 +- x/mint/client/cli/query.go | 12 +-- x/mint/client/rest/query.go | 8 +- x/mint/keeper.go | 13 ---- x/mint/querier.go | 14 +--- x/mint/types/keys.go | 23 ++++++ x/mint/{ => types}/params.go | 2 +- x/slashing/{tick.go => abci_app.go} | 0 x/slashing/{tick_test.go => abci_app_test.go} | 0 x/slashing/client/cli/query.go | 12 +-- x/slashing/client/cli/tx.go | 10 +-- x/slashing/client/rest/query.go | 12 +-- x/slashing/client/rest/tx.go | 4 +- x/slashing/genesis.go | 71 ----------------- x/slashing/{ => keeper}/hooks.go | 2 +- x/slashing/{ => keeper}/keeper.go | 2 +- x/slashing/{ => keeper}/keeper_test.go | 2 +- x/slashing/keeper/params.go | 54 +++++++++++++ x/slashing/{ => keeper}/signing_info.go | 52 ++----------- x/slashing/{ => keeper}/signing_info_test.go | 2 +- x/slashing/querier.go | 7 -- x/slashing/{ => types}/codec.go | 2 +- x/slashing/{ => types}/errors.go | 2 +- x/slashing/{ => types}/expected_keepers.go | 2 +- x/slashing/types/genesis.go | 76 +++++++++++++++++++ x/slashing/{ => types}/keys.go | 8 +- x/slashing/{ => types}/msg.go | 2 +- x/slashing/{ => types}/msg_test.go | 2 +- x/slashing/{ => types}/params.go | 49 +----------- x/slashing/types/signing_info.go | 47 ++++++++++++ x/staking/client/rest/query.go | 26 +++---- x/staking/client/rest/rest.go | 4 +- x/staking/client/rest/tx.go | 8 +- x/staking/client/rest/utils.go | 8 +- 68 files changed, 489 insertions(+), 448 deletions(-) rename x/auth/{ => types}/account.go (99%) rename x/auth/{ => types}/account_test.go (99%) rename x/auth/{ => types}/codec.go (98%) rename x/auth/{ => types}/feekeeper.go (99%) rename x/auth/{ => types}/feekeeper_test.go (99%) create mode 100644 x/auth/types/genesis.go create mode 100644 x/auth/types/keys.go rename x/auth/{ => types}/stdtx.go (99%) rename x/auth/{ => types}/stdtx_test.go (99%) rename x/bank/{ => types}/codec.go (96%) rename x/bank/{ => types}/errors.go (98%) rename x/bank/{ => types}/msgs.go (99%) rename x/bank/{ => types}/msgs_test.go (99%) create mode 100644 x/crisis/types/keys.go rename x/crisis/{msg.go => types/msgs.go} (99%) create mode 100644 x/mint/types/keys.go rename x/mint/{ => types}/params.go (99%) rename x/slashing/{tick.go => abci_app.go} (100%) rename x/slashing/{tick_test.go => abci_app_test.go} (100%) rename x/slashing/{ => keeper}/hooks.go (99%) rename x/slashing/{ => keeper}/keeper.go (99%) rename x/slashing/{ => keeper}/keeper_test.go (99%) create mode 100644 x/slashing/keeper/params.go rename x/slashing/{ => keeper}/signing_info.go (58%) rename x/slashing/{ => keeper}/signing_info_test.go (98%) rename x/slashing/{ => types}/codec.go (95%) rename x/slashing/{ => types}/errors.go (99%) rename x/slashing/{ => types}/expected_keepers.go (95%) create mode 100644 x/slashing/types/genesis.go rename x/slashing/{ => types}/keys.go (92%) rename x/slashing/{ => types}/msg.go (98%) rename x/slashing/{ => types}/msg_test.go (95%) rename x/slashing/{ => types}/params.go (71%) create mode 100644 x/slashing/types/signing_info.go diff --git a/client/context/context.go b/client/context/context.go index ed027b13b78f..8d18767b9d1c 100644 --- a/client/context/context.go +++ b/client/context/context.go @@ -13,7 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/codec" cryptokeys "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/cosmos/cosmos-sdk/x/auth" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/spf13/viper" @@ -35,7 +35,7 @@ var ( // transaction handling and queries. type CLIContext struct { Codec *codec.Codec - AccDecoder auth.AccountDecoder + AccDecoder authtypes.AccountDecoder Client rpcclient.Client Keybase cryptokeys.Keybase Output io.Writer @@ -89,7 +89,7 @@ func NewCLIContextWithFrom(from string) CLIContext { Client: rpc, Output: os.Stdout, NodeURI: nodeURI, - AccountStore: auth.StoreKey, + AccountStore: authtypes.StoreKey, From: viper.GetString(flags.FlagFrom), OutputFormat: viper.GetString(cli.OutputFlag), Height: viper.GetInt64(flags.FlagHeight), @@ -164,8 +164,8 @@ func (ctx CLIContext) WithCodec(cdc *codec.Codec) CLIContext { } // GetAccountDecoder gets the account decoder for auth.DefaultAccount. -func GetAccountDecoder(cdc *codec.Codec) auth.AccountDecoder { - return func(accBytes []byte) (acct auth.Account, err error) { +func GetAccountDecoder(cdc *codec.Codec) authtypes.AccountDecoder { + return func(accBytes []byte) (acct authtypes.Account, err error) { err = cdc.UnmarshalBinaryBare(accBytes, &acct) if err != nil { panic(err) diff --git a/client/context/query.go b/client/context/query.go index 0d3eda45cd25..fa1cceb5bb2c 100644 --- a/client/context/query.go +++ b/client/context/query.go @@ -16,7 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/rootmulti" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) // GetNode returns an RPC client. If the context's client is not defined, an @@ -59,7 +59,7 @@ func (ctx CLIContext) QuerySubspace(subspace []byte, storeName string) (res []sd // GetAccount queries for an account given an address and a block height. An // error is returned if the query or decoding fails. -func (ctx CLIContext) GetAccount(address []byte) (auth.Account, error) { +func (ctx CLIContext) GetAccount(address []byte) (authtypes.Account, error) { if ctx.AccDecoder == nil { return nil, errors.New("account decoder required but not provided") } @@ -69,7 +69,7 @@ func (ctx CLIContext) GetAccount(address []byte) (auth.Account, error) { return nil, err } - var account auth.Account + var account authtypes.Account if err := ctx.Codec.UnmarshalJSON(res, &account); err != nil { return nil, err } @@ -127,12 +127,12 @@ func (ctx CLIContext) EnsureAccountExistsFromAddr(addr sdk.AccAddress) error { // queryAccount queries an account using custom query endpoint of auth module // returns an error if result is `null` otherwise account data func (ctx CLIContext) queryAccount(addr sdk.AccAddress) ([]byte, error) { - bz, err := ctx.Codec.MarshalJSON(auth.NewQueryAccountParams(addr)) + bz, err := ctx.Codec.MarshalJSON(authtypes.NewQueryAccountParams(addr)) if err != nil { return nil, err } - route := fmt.Sprintf("custom/%s/%s", ctx.AccountStore, auth.QueryAccount) + route := fmt.Sprintf("custom/%s/%s", ctx.AccountStore, authtypes.QueryAccount) res, err := ctx.QueryWithData(route, bz) if err != nil { diff --git a/x/auth/client/rest/query.go b/x/auth/client/rest/query.go index 9df3c14bc055..348fab865abf 100644 --- a/x/auth/client/rest/query.go +++ b/x/auth/client/rest/query.go @@ -10,7 +10,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) // register REST routes @@ -29,7 +29,7 @@ func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, // query accountREST Handler func QueryAccountRequestHandlerFn( storeName string, cdc *codec.Codec, - decoder auth.AccountDecoder, cliCtx context.CLIContext, + decoder types.AccountDecoder, cliCtx context.CLIContext, ) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) @@ -41,7 +41,7 @@ func QueryAccountRequestHandlerFn( return } - res, err := cliCtx.QueryStore(auth.AddressStoreKey(addr), storeName) + res, err := cliCtx.QueryStore(types.AddressStoreKey(addr), storeName) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -49,7 +49,7 @@ func QueryAccountRequestHandlerFn( // the query will return empty account if there is no data if len(res) == 0 { - rest.PostProcessResponse(w, cdc, auth.BaseAccount{}, cliCtx.Indent) + rest.PostProcessResponse(w, cdc, types.BaseAccount{}, cliCtx.Indent) return } @@ -67,7 +67,7 @@ func QueryAccountRequestHandlerFn( // query accountREST Handler func QueryBalancesRequestHandlerFn( storeName string, cdc *codec.Codec, - decoder auth.AccountDecoder, cliCtx context.CLIContext, + decoder types.AccountDecoder, cliCtx context.CLIContext, ) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") @@ -80,7 +80,7 @@ func QueryBalancesRequestHandlerFn( return } - res, err := cliCtx.QueryStore(auth.AddressStoreKey(addr), storeName) + res, err := cliCtx.QueryStore(types.AddressStoreKey(addr), storeName) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return diff --git a/x/auth/genesis.go b/x/auth/genesis.go index 885234f61c71..90e2a3a32bf6 100644 --- a/x/auth/genesis.go +++ b/x/auth/genesis.go @@ -1,30 +1,9 @@ package auth import ( - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" ) -// GenesisState - all auth state that must be provided at genesis -type GenesisState struct { - CollectedFees sdk.Coins `json:"collected_fees"` - Params Params `json:"params"` -} - -// NewGenesisState - Create a new genesis state -func NewGenesisState(collectedFees sdk.Coins, params Params) GenesisState { - return GenesisState{ - CollectedFees: collectedFees, - Params: params, - } -} - -// DefaultGenesisState - Return a default genesis state -func DefaultGenesisState() GenesisState { - return NewGenesisState(sdk.NewCoins(), DefaultParams()) -} - // InitGenesis - Init store state from genesis data func InitGenesis(ctx sdk.Context, ak AccountKeeper, fck FeeCollectionKeeper, data GenesisState) { ak.SetParams(ctx, data.Params) @@ -38,24 +17,3 @@ func ExportGenesis(ctx sdk.Context, ak AccountKeeper, fck FeeCollectionKeeper) G return NewGenesisState(collectedFees, params) } - -// ValidateGenesis performs basic validation of auth genesis data returning an -// error for any failed validation criteria. -func ValidateGenesis(data GenesisState) error { - if data.Params.TxSigLimit == 0 { - return fmt.Errorf("invalid tx signature limit: %d", data.Params.TxSigLimit) - } - if data.Params.SigVerifyCostED25519 == 0 { - return fmt.Errorf("invalid ED25519 signature verification cost: %d", data.Params.SigVerifyCostED25519) - } - if data.Params.SigVerifyCostSecp256k1 == 0 { - return fmt.Errorf("invalid SECK256k1 signature verification cost: %d", data.Params.SigVerifyCostSecp256k1) - } - if data.Params.MaxMemoCharacters == 0 { - return fmt.Errorf("invalid max memo characters: %d", data.Params.MaxMemoCharacters) - } - if data.Params.TxSizeCostPerByte == 0 { - return fmt.Errorf("invalid tx size cost per byte: %d", data.Params.TxSizeCostPerByte) - } - return nil -} diff --git a/x/auth/keeper.go b/x/auth/keeper.go index f630381be1e6..105945994f5e 100644 --- a/x/auth/keeper.go +++ b/x/auth/keeper.go @@ -10,24 +10,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/params/subspace" ) -const ( - // StoreKey is string representation of the store key for auth - StoreKey = "acc" - - // FeeStoreKey is a string representation of the store key for fees - FeeStoreKey = "fee" - - // QuerierRoute is the querier route for acc - QuerierRoute = StoreKey -) - -var ( - // AddressStoreKeyPrefix prefix for account-by-address store - AddressStoreKeyPrefix = []byte{0x01} - - globalAccountNumberKey = []byte("globalAccountNumber") -) - // AccountKeeper encodes/decodes accounts using the go-amino (binary) // encoding/decoding library. type AccountKeeper struct { @@ -82,11 +64,6 @@ func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc Account) Account { return acc } -// AddressStoreKey turn an address to key used to get it from the account store -func AddressStoreKey(addr sdk.AccAddress) []byte { - return append(AddressStoreKeyPrefix, addr.Bytes()...) -} - // GetAccount implements sdk.AccountKeeper. func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) Account { store := ctx.KVStore(ak.key) diff --git a/x/auth/account.go b/x/auth/types/account.go similarity index 99% rename from x/auth/account.go rename to x/auth/types/account.go index 99132d3ba26a..1924f079ccac 100644 --- a/x/auth/account.go +++ b/x/auth/types/account.go @@ -1,4 +1,4 @@ -package auth +package types import ( "errors" diff --git a/x/auth/account_test.go b/x/auth/types/account_test.go similarity index 99% rename from x/auth/account_test.go rename to x/auth/types/account_test.go index d8f7c6fa8ddd..726ae08c96ee 100644 --- a/x/auth/account_test.go +++ b/x/auth/types/account_test.go @@ -1,4 +1,4 @@ -package auth +package types import ( "testing" diff --git a/x/auth/codec.go b/x/auth/types/codec.go similarity index 98% rename from x/auth/codec.go rename to x/auth/types/codec.go index 9b7b35204347..aa67699d25cb 100644 --- a/x/auth/codec.go +++ b/x/auth/types/codec.go @@ -1,4 +1,4 @@ -package auth +package types import ( "github.com/cosmos/cosmos-sdk/codec" diff --git a/x/auth/feekeeper.go b/x/auth/types/feekeeper.go similarity index 99% rename from x/auth/feekeeper.go rename to x/auth/types/feekeeper.go index bc6506b1764a..c0b37a150105 100644 --- a/x/auth/feekeeper.go +++ b/x/auth/types/feekeeper.go @@ -1,4 +1,4 @@ -package auth +package types import ( codec "github.com/cosmos/cosmos-sdk/codec" diff --git a/x/auth/feekeeper_test.go b/x/auth/types/feekeeper_test.go similarity index 99% rename from x/auth/feekeeper_test.go rename to x/auth/types/feekeeper_test.go index ab49305f1c73..5126aa446dd2 100644 --- a/x/auth/feekeeper_test.go +++ b/x/auth/types/feekeeper_test.go @@ -1,4 +1,4 @@ -package auth +package types import ( "testing" diff --git a/x/auth/types/genesis.go b/x/auth/types/genesis.go new file mode 100644 index 000000000000..d7239380463e --- /dev/null +++ b/x/auth/types/genesis.go @@ -0,0 +1,47 @@ +package types + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// GenesisState - all auth state that must be provided at genesis +type GenesisState struct { + CollectedFees sdk.Coins `json:"collected_fees"` + Params Params `json:"params"` +} + +// NewGenesisState - Create a new genesis state +func NewGenesisState(collectedFees sdk.Coins, params Params) GenesisState { + return GenesisState{ + CollectedFees: collectedFees, + Params: params, + } +} + +// DefaultGenesisState - Return a default genesis state +func DefaultGenesisState() GenesisState { + return NewGenesisState(sdk.NewCoins(), DefaultParams()) +} + +// ValidateGenesis performs basic validation of auth genesis data returning an +// error for any failed validation criteria. +func ValidateGenesis(data GenesisState) error { + if data.Params.TxSigLimit == 0 { + return fmt.Errorf("invalid tx signature limit: %d", data.Params.TxSigLimit) + } + if data.Params.SigVerifyCostED25519 == 0 { + return fmt.Errorf("invalid ED25519 signature verification cost: %d", data.Params.SigVerifyCostED25519) + } + if data.Params.SigVerifyCostSecp256k1 == 0 { + return fmt.Errorf("invalid SECK256k1 signature verification cost: %d", data.Params.SigVerifyCostSecp256k1) + } + if data.Params.MaxMemoCharacters == 0 { + return fmt.Errorf("invalid max memo characters: %d", data.Params.MaxMemoCharacters) + } + if data.Params.TxSizeCostPerByte == 0 { + return fmt.Errorf("invalid tx size cost per byte: %d", data.Params.TxSizeCostPerByte) + } + return nil +} diff --git a/x/auth/types/keys.go b/x/auth/types/keys.go new file mode 100644 index 000000000000..674e16910042 --- /dev/null +++ b/x/auth/types/keys.go @@ -0,0 +1,26 @@ +package types + +import sdk "github.com/cosmos/cosmos-sdk/types" + +const ( + // StoreKey is string representation of the store key for auth + StoreKey = "acc" + + // FeeStoreKey is a string representation of the store key for fees + FeeStoreKey = "fee" + + // QuerierRoute is the querier route for acc + QuerierRoute = StoreKey +) + +var ( + // AddressStoreKeyPrefix prefix for account-by-address store + AddressStoreKeyPrefix = []byte{0x01} + + globalAccountNumberKey = []byte("globalAccountNumber") +) + +// AddressStoreKey turn an address to key used to get it from the account store +func AddressStoreKey(addr sdk.AccAddress) []byte { + return append(AddressStoreKeyPrefix, addr.Bytes()...) +} diff --git a/x/auth/stdtx.go b/x/auth/types/stdtx.go similarity index 99% rename from x/auth/stdtx.go rename to x/auth/types/stdtx.go index 2233752621c3..1aac644391ad 100644 --- a/x/auth/stdtx.go +++ b/x/auth/types/stdtx.go @@ -1,4 +1,4 @@ -package auth +package types import ( "encoding/json" diff --git a/x/auth/stdtx_test.go b/x/auth/types/stdtx_test.go similarity index 99% rename from x/auth/stdtx_test.go rename to x/auth/types/stdtx_test.go index 1139407ad293..e74c9429d697 100644 --- a/x/auth/stdtx_test.go +++ b/x/auth/types/stdtx_test.go @@ -1,4 +1,4 @@ -package auth +package types import ( "fmt" diff --git a/x/bank/bench_test.go b/x/bank/bench_test.go index 8425f0f93008..dbc7eebe5589 100644 --- a/x/bank/bench_test.go +++ b/x/bank/bench_test.go @@ -3,11 +3,12 @@ package bank import ( "testing" + abci "github.com/tendermint/tendermint/abci/types" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/mock" - - abci "github.com/tendermint/tendermint/abci/types" ) // getBenchmarkMockApp initializes a mock application for this module, for purposes of benchmarking @@ -15,7 +16,7 @@ import ( func getBenchmarkMockApp() (*mock.App, error) { mapp := mock.NewApp() - RegisterCodec(mapp.Cdc) + types.RegisterCodec(mapp.Cdc) bankKeeper := NewBaseKeeper( mapp.AccountKeeper, mapp.ParamsKeeper.Subspace(DefaultParamspace), diff --git a/x/bank/client/rest/sendtx.go b/x/bank/client/rest/sendtx.go index 3e634e551f61..801bd58e6cad 100644 --- a/x/bank/client/rest/sendtx.go +++ b/x/bank/client/rest/sendtx.go @@ -12,7 +12,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/bank/types" ) // RegisterRoutes - Central function to define routes that get registered by the main application @@ -29,7 +29,7 @@ type SendReq struct { var moduleCdc = codec.New() func init() { - bank.RegisterCodec(moduleCdc) + types.RegisterCodec(moduleCdc) } // SendRequestHandlerFn - http request handler to send coins to a address. @@ -60,7 +60,7 @@ func SendRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIC return } - msg := bank.NewMsgSend(fromAddr, toAddr, req.Amount) + msg := types.NewMsgSend(fromAddr, toAddr, req.Amount) clientrest.WriteGenerateStdTxResponse(w, cdc, cliCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/bank/module.go b/x/bank/module.go index 553e6ad6f79b..40901d21f8ca 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -11,6 +11,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank/client/rest" + "github.com/cosmos/cosmos-sdk/x/bank/types" ) var ( @@ -33,7 +34,7 @@ func (AppModuleBasic) Name() string { // register module codec func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) + types.RegisterCodec(cdc) } // default genesis state diff --git a/x/bank/codec.go b/x/bank/types/codec.go similarity index 96% rename from x/bank/codec.go rename to x/bank/types/codec.go index 2c2cc32a3387..2d169d08fe66 100644 --- a/x/bank/codec.go +++ b/x/bank/types/codec.go @@ -1,4 +1,4 @@ -package bank +package types import ( "github.com/cosmos/cosmos-sdk/codec" diff --git a/x/bank/errors.go b/x/bank/types/errors.go similarity index 98% rename from x/bank/errors.go rename to x/bank/types/errors.go index 5b579fabb28d..d9c0c7d11d1d 100644 --- a/x/bank/errors.go +++ b/x/bank/types/errors.go @@ -1,4 +1,4 @@ -package bank +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/bank/msgs.go b/x/bank/types/msgs.go similarity index 99% rename from x/bank/msgs.go rename to x/bank/types/msgs.go index 2953488673f2..805873fb1443 100644 --- a/x/bank/msgs.go +++ b/x/bank/types/msgs.go @@ -1,4 +1,4 @@ -package bank +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/bank/msgs_test.go b/x/bank/types/msgs_test.go similarity index 99% rename from x/bank/msgs_test.go rename to x/bank/types/msgs_test.go index 3b7813e0d508..2a09c1b9f728 100644 --- a/x/bank/msgs_test.go +++ b/x/bank/types/msgs_test.go @@ -1,4 +1,4 @@ -package bank +package types import ( "fmt" diff --git a/x/crisis/client/cli/tx.go b/x/crisis/client/cli/tx.go index 91c4b3a7d232..9c3b04dc7d85 100644 --- a/x/crisis/client/cli/tx.go +++ b/x/crisis/client/cli/tx.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/crisis" + "github.com/cosmos/cosmos-sdk/x/crisis/types" ) // command to replace a delegator's withdrawal address @@ -26,7 +26,7 @@ func GetCmdInvariantBroken(cdc *codec.Codec) *cobra.Command { senderAddr := cliCtx.GetFromAddress() moduleName, route := args[0], args[1] - msg := crisis.NewMsgVerifyInvariant(senderAddr, moduleName, route) + msg := types.NewMsgVerifyInvariant(senderAddr, moduleName, route) return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) }, } @@ -36,7 +36,7 @@ func GetCmdInvariantBroken(cdc *codec.Codec) *cobra.Command { // GetTxCmd returns the transaction commands for this module func GetTxCmd(cdc *amino.Codec) *cobra.Command { txCmd := &cobra.Command{ - Use: crisis.ModuleName, + Use: types.ModuleName, Short: "crisis transactions subcommands", } diff --git a/x/crisis/module.go b/x/crisis/module.go index 18209cab6842..24eed5a08165 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -11,6 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/crisis/client/cli" + "github.com/cosmos/cosmos-sdk/x/crisis/types" ) var ( @@ -19,7 +20,7 @@ var ( ) // name of this module -const ModuleName = "crisis" +const ModuleName = types.ModuleName // app module basics object type AppModuleBasic struct{} diff --git a/x/crisis/types/keys.go b/x/crisis/types/keys.go new file mode 100644 index 000000000000..8f009eda4148 --- /dev/null +++ b/x/crisis/types/keys.go @@ -0,0 +1,6 @@ +package types + +const ( + // module name + ModuleName = "crisis" +) diff --git a/x/crisis/msg.go b/x/crisis/types/msgs.go similarity index 99% rename from x/crisis/msg.go rename to x/crisis/types/msgs.go index f63623149410..db37c9aed974 100644 --- a/x/crisis/msg.go +++ b/x/crisis/types/msgs.go @@ -1,4 +1,4 @@ -package crisis +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index e985b30bc3a9..a46ebe0e77c4 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -13,7 +13,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - distr "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/distribution/client/common" "github.com/cosmos/cosmos-sdk/x/distribution/types" ) @@ -144,7 +143,7 @@ $ %s query distr slashes cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 0 return fmt.Errorf("end-height %s not a valid uint, please input a valid end-height", args[2]) } - params := distr.NewQueryValidatorSlashesParams(validatorAddr, startHeight, endHeight) + params := types.NewQueryValidatorSlashesParams(validatorAddr, startHeight, endHeight) bz, err := cdc.MarshalJSON(params) if err != nil { return err @@ -199,7 +198,7 @@ $ %s query distr rewards cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosval return err } - var result distr.QueryDelegatorTotalRewardsResponse + var result types.QueryDelegatorTotalRewardsResponse cdc.MustUnmarshalJSON(resp, &result) return cliCtx.PrintOutput(result) }, diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index 2626b7faee9b..317b565b6833 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -16,7 +16,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/gov" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/distribution/client/common" "github.com/cosmos/cosmos-sdk/x/distribution/types" @@ -242,7 +242,7 @@ Where proposal.json contains: from := cliCtx.GetFromAddress() content := types.NewCommunityPoolSpendProposal(proposal.Title, proposal.Description, proposal.Recipient, proposal.Amount) - msg := gov.NewMsgSubmitProposal(content, proposal.Deposit, from) + msg := govtypes.NewMsgSubmitProposal(content, proposal.Deposit, from) if err := msg.ValidateBasic(); err != nil { return err } diff --git a/x/distribution/client/cli/tx_test.go b/x/distribution/client/cli/tx_test.go index d1423cbf8909..333ce645f85a 100644 --- a/x/distribution/client/cli/tx_test.go +++ b/x/distribution/client/cli/tx_test.go @@ -3,13 +3,14 @@ package cli import ( "testing" + "github.com/stretchr/testify/assert" + "github.com/tendermint/tendermint/crypto/secp256k1" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/stretchr/testify/assert" - "github.com/tendermint/tendermint/crypto/secp256k1" ) func createFakeTxBuilder() authtxb.TxBuilder { diff --git a/x/distribution/client/common/common.go b/x/distribution/client/common/common.go index 2f2f6b38b6c9..f1b8e4ef4698 100644 --- a/x/distribution/client/common/common.go +++ b/x/distribution/client/common/common.go @@ -6,31 +6,31 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - distr "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/distribution/types" ) // QueryParams actually queries distribution params. func QueryParams(cliCtx context.CLIContext, queryRoute string) (PrettyParams, error) { - route := fmt.Sprintf("custom/%s/params/%s", queryRoute, distr.ParamCommunityTax) + route := fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamCommunityTax) retCommunityTax, err := cliCtx.QueryWithData(route, []byte{}) if err != nil { return PrettyParams{}, err } - route = fmt.Sprintf("custom/%s/params/%s", queryRoute, distr.ParamBaseProposerReward) + route = fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamBaseProposerReward) retBaseProposerReward, err := cliCtx.QueryWithData(route, []byte{}) if err != nil { return PrettyParams{}, err } - route = fmt.Sprintf("custom/%s/params/%s", queryRoute, distr.ParamBonusProposerReward) + route = fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamBonusProposerReward) retBonusProposerReward, err := cliCtx.QueryWithData(route, []byte{}) if err != nil { return PrettyParams{}, err } - route = fmt.Sprintf("custom/%s/params/%s", queryRoute, distr.ParamWithdrawAddrEnabled) + route = fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamWithdrawAddrEnabled) retWithdrawAddrEnabled, err := cliCtx.QueryWithData(route, []byte{}) if err != nil { return PrettyParams{}, err @@ -50,8 +50,8 @@ func QueryDelegatorTotalRewards(cliCtx context.CLIContext, cdc *codec.Codec, } return cliCtx.QueryWithData( - fmt.Sprintf("custom/%s/%s", queryRoute, distr.QueryDelegatorTotalRewards), - cdc.MustMarshalJSON(distr.NewQueryDelegatorParams(delegatorAddr)), + fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorTotalRewards), + cdc.MustMarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)), ) } @@ -69,8 +69,8 @@ func QueryDelegationRewards(cliCtx context.CLIContext, cdc *codec.Codec, } return cliCtx.QueryWithData( - fmt.Sprintf("custom/%s/%s", queryRoute, distr.QueryDelegationRewards), - cdc.MustMarshalJSON(distr.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr)), + fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegationRewards), + cdc.MustMarshalJSON(types.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr)), ) } @@ -80,8 +80,8 @@ func QueryDelegatorValidators(cliCtx context.CLIContext, cdc *codec.Codec, queryRoute string, delegatorAddr sdk.AccAddress) ([]byte, error) { return cliCtx.QueryWithData( - fmt.Sprintf("custom/%s/%s", queryRoute, distr.QueryDelegatorValidators), - cdc.MustMarshalJSON(distr.NewQueryDelegatorParams(delegatorAddr)), + fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorValidators), + cdc.MustMarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)), ) } @@ -90,8 +90,8 @@ func QueryValidatorCommission(cliCtx context.CLIContext, cdc *codec.Codec, queryRoute string, validatorAddr sdk.ValAddress) ([]byte, error) { return cliCtx.QueryWithData( - fmt.Sprintf("custom/%s/%s", queryRoute, distr.QueryValidatorCommission), - cdc.MustMarshalJSON(distr.NewQueryValidatorCommissionParams(validatorAddr)), + fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryValidatorCommission), + cdc.MustMarshalJSON(types.NewQueryValidatorCommissionParams(validatorAddr)), ) } @@ -115,7 +115,7 @@ func WithdrawAllDelegatorRewards(cliCtx context.CLIContext, cdc *codec.Codec, // build multi-message transaction var msgs []sdk.Msg for _, valAddr := range validators { - msg := distr.NewMsgWithdrawDelegatorReward(delegatorAddr, valAddr) + msg := types.NewMsgWithdrawDelegatorReward(delegatorAddr, valAddr) if err := msg.ValidateBasic(); err != nil { return nil, err } @@ -129,13 +129,13 @@ func WithdrawAllDelegatorRewards(cliCtx context.CLIContext, cdc *codec.Codec, // used to withdraw both validation's commission and self-delegation reward. func WithdrawValidatorRewardsAndCommission(validatorAddr sdk.ValAddress) ([]sdk.Msg, error) { - commissionMsg := distr.NewMsgWithdrawValidatorCommission(validatorAddr) + commissionMsg := types.NewMsgWithdrawValidatorCommission(validatorAddr) if err := commissionMsg.ValidateBasic(); err != nil { return nil, err } // build and validate MsgWithdrawDelegatorReward - rewardMsg := distr.NewMsgWithdrawDelegatorReward( + rewardMsg := types.NewMsgWithdrawDelegatorReward( sdk.AccAddress(validatorAddr.Bytes()), validatorAddr) if err := rewardMsg.ValidateBasic(); err != nil { return nil, err diff --git a/x/distribution/client/rest/query.go b/x/distribution/client/rest/query.go index 919574b5eece..a47b00018010 100644 --- a/x/distribution/client/rest/query.go +++ b/x/distribution/client/rest/query.go @@ -6,7 +6,6 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/distribution/client/common" "github.com/cosmos/cosmos-sdk/x/distribution/types" @@ -111,7 +110,7 @@ func delegatorWithdrawalAddrHandlerFn(cliCtx context.CLIContext, cdc *codec.Code return } - bz := cdc.MustMarshalJSON(distribution.NewQueryDelegatorWithdrawAddrParams(delegatorAddr)) + bz := cdc.MustMarshalJSON(types.NewQueryDelegatorWithdrawAddrParams(delegatorAddr)) res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/withdraw_addr", queryRoute), bz) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -243,7 +242,7 @@ func outstandingRewardsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec, return } - bin := cdc.MustMarshalJSON(distribution.NewQueryValidatorOutstandingRewardsParams(validatorAddr)) + bin := cdc.MustMarshalJSON(types.NewQueryValidatorOutstandingRewardsParams(validatorAddr)) res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/validator_outstanding_rewards", queryRoute), bin) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) diff --git a/x/distribution/client/rest/rest.go b/x/distribution/client/rest/rest.go index 49650c59d9c3..1468674c5583 100644 --- a/x/distribution/client/rest/rest.go +++ b/x/distribution/client/rest/rest.go @@ -1,15 +1,16 @@ package rest import ( - "github.com/gorilla/mux" "net/http" + "github.com/gorilla/mux" + "github.com/cosmos/cosmos-sdk/client/context" clientrest "github.com/cosmos/cosmos-sdk/client/rest" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/gov" govrest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" ) @@ -40,7 +41,7 @@ func postProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Han return } - content := distribution.NewCommunityPoolSpendProposal(req.Title, req.Description, req.Recipient, req.Amount) + content := types.NewCommunityPoolSpendProposal(req.Title, req.Description, req.Recipient, req.Amount) msg := gov.NewMsgSubmitProposal(content, req.Deposit, req.Proposer) if err := msg.ValidateBasic(); err != nil { diff --git a/x/gov/client/rest/rest.go b/x/gov/client/rest/rest.go index 701600357312..227898ad31d2 100644 --- a/x/gov/client/rest/rest.go +++ b/x/gov/client/rest/rest.go @@ -12,8 +12,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/gov" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // REST Variable names @@ -100,9 +100,9 @@ func postProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Han } proposalType := gcutils.NormalizeProposalType(req.ProposalType) - content := gov.ContentFromProposalType(req.Title, req.Description, proposalType) + content := types.ContentFromProposalType(req.Title, req.Description, proposalType) - msg := gov.NewMsgSubmitProposal(content, req.InitialDeposit, req.Proposer) + msg := types.NewMsgSubmitProposal(content, req.InitialDeposit, req.Proposer) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -139,7 +139,7 @@ func depositHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerF } // create the message - msg := gov.NewMsgDeposit(req.Depositor, proposalID, req.Amount) + msg := types.NewMsgDeposit(req.Depositor, proposalID, req.Amount) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -175,14 +175,14 @@ func voteHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc return } - voteOption, err := gov.VoteOptionFromString(gcutils.NormalizeVoteOption(req.Option)) + voteOption, err := types.VoteOptionFromString(gcutils.NormalizeVoteOption(req.Option)) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } // create the message - msg := gov.NewMsgVote(req.Voter, proposalID, voteOption) + msg := types.NewMsgVote(req.Voter, proposalID, voteOption) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -197,7 +197,7 @@ func queryParamsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Hand vars := mux.Vars(r) paramType := vars[RestParamsType] - res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/gov/%s/%s", gov.QueryParams, paramType), nil) + res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/gov/%s/%s", types.QueryParams, paramType), nil) if err != nil { rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) return @@ -223,7 +223,7 @@ func queryProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Ha return } - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -251,7 +251,7 @@ func queryDepositsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Ha return } - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -265,7 +265,7 @@ func queryDepositsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Ha return } - var proposal gov.Proposal + var proposal types.Proposal if err := cdc.UnmarshalJSON(res, &proposal); err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -274,7 +274,7 @@ func queryDepositsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Ha // For inactive proposals we must query the txs directly to get the deposits // as they're no longer in state. propStatus := proposal.Status - if !(propStatus == gov.StatusVotingPeriod || propStatus == gov.StatusDepositPeriod) { + if !(propStatus == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { res, err = gcutils.QueryDepositsByTxQuery(cdc, cliCtx, params) } else { res, err = cliCtx.QueryWithData("custom/gov/deposits", bz) @@ -338,7 +338,7 @@ func queryDepositHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Han return } - params := gov.NewQueryDepositParams(proposalID, depositorAddr) + params := types.NewQueryDepositParams(proposalID, depositorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -352,7 +352,7 @@ func queryDepositHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Han return } - var deposit gov.Deposit + var deposit types.Deposit if err := cdc.UnmarshalJSON(res, &deposit); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -362,7 +362,7 @@ func queryDepositHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Han // which case the deposit would be removed from state and should be queried // for directly via a txs query. if deposit.Empty() { - bz, err := cdc.MarshalJSON(gov.NewQueryProposalParams(proposalID)) + bz, err := cdc.MarshalJSON(types.NewQueryProposalParams(proposalID)) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -415,7 +415,7 @@ func queryVoteHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Handle return } - params := gov.NewQueryVoteParams(proposalID, voterAddr) + params := types.NewQueryVoteParams(proposalID, voterAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -429,7 +429,7 @@ func queryVoteHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Handle return } - var vote gov.Vote + var vote types.Vote if err := cdc.UnmarshalJSON(res, &vote); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -439,7 +439,7 @@ func queryVoteHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Handle // which case the vote would be removed from state and should be queried for // directly via a txs query. if vote.Empty() { - bz, err := cdc.MarshalJSON(gov.NewQueryProposalParams(proposalID)) + bz, err := cdc.MarshalJSON(types.NewQueryProposalParams(proposalID)) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -480,7 +480,7 @@ func queryVotesOnProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) return } - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -494,7 +494,7 @@ func queryVotesOnProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) return } - var proposal gov.Proposal + var proposal types.Proposal if err := cdc.UnmarshalJSON(res, &proposal); err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -503,7 +503,7 @@ func queryVotesOnProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) // For inactive proposals we must query the txs directly to get the votes // as they're no longer in state. propStatus := proposal.Status - if !(propStatus == gov.StatusVotingPeriod || propStatus == gov.StatusDepositPeriod) { + if !(propStatus == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { res, err = gcutils.QueryVotesByTxQuery(cdc, cliCtx, params) } else { res, err = cliCtx.QueryWithData("custom/gov/votes", bz) @@ -526,7 +526,7 @@ func queryProposalsWithParameterFn(cdc *codec.Codec, cliCtx context.CLIContext) strProposalStatus := r.URL.Query().Get(RestProposalStatus) strNumLimit := r.URL.Query().Get(RestNumLimit) - params := gov.QueryProposalsParams{} + params := types.QueryProposalsParams{} if len(bechVoterAddr) != 0 { voterAddr, err := sdk.AccAddressFromBech32(bechVoterAddr) @@ -547,7 +547,7 @@ func queryProposalsWithParameterFn(cdc *codec.Codec, cliCtx context.CLIContext) } if len(strProposalStatus) != 0 { - proposalStatus, err := gov.ProposalStatusFromString(gcutils.NormalizeProposalStatus(strProposalStatus)) + proposalStatus, err := types.ProposalStatusFromString(gcutils.NormalizeProposalStatus(strProposalStatus)) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -595,7 +595,7 @@ func queryTallyOnProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) return } - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { diff --git a/x/gov/client/utils/query.go b/x/gov/client/utils/query.go index 28e996981897..afbb605e6c68 100644 --- a/x/gov/client/utils/query.go +++ b/x/gov/client/utils/query.go @@ -6,8 +6,8 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/gov/tags" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) const ( @@ -38,11 +38,11 @@ func (p Proposer) String() string { // NOTE: SearchTxs is used to facilitate the txs query which does not currently // support configurable pagination. func QueryDepositsByTxQuery( - cdc *codec.Codec, cliCtx context.CLIContext, params gov.QueryProposalParams, + cdc *codec.Codec, cliCtx context.CLIContext, params types.QueryProposalParams, ) ([]byte, error) { tags := []string{ - fmt.Sprintf("%s='%s'", tags.Action, gov.MsgDeposit{}.Type()), + fmt.Sprintf("%s='%s'", tags.Action, types.MsgDeposit{}.Type()), fmt.Sprintf("%s='%s'", tags.ProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))), } @@ -53,14 +53,14 @@ func QueryDepositsByTxQuery( return nil, err } - var deposits []gov.Deposit + var deposits []types.Deposit for _, info := range searchResult.Txs { for _, msg := range info.Tx.GetMsgs() { - if msg.Type() == gov.TypeMsgDeposit { - depMsg := msg.(gov.MsgDeposit) + if msg.Type() == types.TypeMsgDeposit { + depMsg := msg.(types.MsgDeposit) - deposits = append(deposits, gov.Deposit{ + deposits = append(deposits, types.Deposit{ Depositor: depMsg.Depositor, ProposalID: params.ProposalID, Amount: depMsg.Amount, @@ -83,11 +83,11 @@ func QueryDepositsByTxQuery( // NOTE: SearchTxs is used to facilitate the txs query which does not currently // support configurable pagination. func QueryVotesByTxQuery( - cdc *codec.Codec, cliCtx context.CLIContext, params gov.QueryProposalParams, + cdc *codec.Codec, cliCtx context.CLIContext, params types.QueryProposalParams, ) ([]byte, error) { tags := []string{ - fmt.Sprintf("%s='%s'", tags.Action, gov.MsgVote{}.Type()), + fmt.Sprintf("%s='%s'", tags.Action, types.MsgVote{}.Type()), fmt.Sprintf("%s='%s'", tags.ProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))), } @@ -98,14 +98,14 @@ func QueryVotesByTxQuery( return nil, err } - var votes []gov.Vote + var votes []types.Vote for _, info := range searchResult.Txs { for _, msg := range info.Tx.GetMsgs() { - if msg.Type() == gov.TypeMsgVote { - voteMsg := msg.(gov.MsgVote) + if msg.Type() == types.TypeMsgVote { + voteMsg := msg.(types.MsgVote) - votes = append(votes, gov.Vote{ + votes = append(votes, types.Vote{ Voter: voteMsg.Voter, ProposalID: params.ProposalID, Option: voteMsg.Option, @@ -123,11 +123,11 @@ func QueryVotesByTxQuery( // QueryVoteByTxQuery will query for a single vote via a direct txs tags query. func QueryVoteByTxQuery( - cdc *codec.Codec, cliCtx context.CLIContext, params gov.QueryVoteParams, + cdc *codec.Codec, cliCtx context.CLIContext, params types.QueryVoteParams, ) ([]byte, error) { tags := []string{ - fmt.Sprintf("%s='%s'", tags.Action, gov.MsgVote{}.Type()), + fmt.Sprintf("%s='%s'", tags.Action, types.MsgVote{}.Type()), fmt.Sprintf("%s='%s'", tags.ProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))), fmt.Sprintf("%s='%s'", tags.Sender, []byte(params.Voter.String())), } @@ -142,10 +142,10 @@ func QueryVoteByTxQuery( for _, info := range searchResult.Txs { for _, msg := range info.Tx.GetMsgs() { // there should only be a single vote under the given conditions - if msg.Type() == gov.TypeMsgVote { - voteMsg := msg.(gov.MsgVote) + if msg.Type() == types.TypeMsgVote { + voteMsg := msg.(types.MsgVote) - vote := gov.Vote{ + vote := types.Vote{ Voter: voteMsg.Voter, ProposalID: params.ProposalID, Option: voteMsg.Option, @@ -166,11 +166,11 @@ func QueryVoteByTxQuery( // QueryDepositByTxQuery will query for a single deposit via a direct txs tags // query. func QueryDepositByTxQuery( - cdc *codec.Codec, cliCtx context.CLIContext, params gov.QueryDepositParams, + cdc *codec.Codec, cliCtx context.CLIContext, params types.QueryDepositParams, ) ([]byte, error) { tags := []string{ - fmt.Sprintf("%s='%s'", tags.Action, gov.MsgDeposit{}.Type()), + fmt.Sprintf("%s='%s'", tags.Action, types.MsgDeposit{}.Type()), fmt.Sprintf("%s='%s'", tags.ProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))), fmt.Sprintf("%s='%s'", tags.Sender, []byte(params.Depositor.String())), } @@ -185,10 +185,10 @@ func QueryDepositByTxQuery( for _, info := range searchResult.Txs { for _, msg := range info.Tx.GetMsgs() { // there should only be a single deposit under the given conditions - if msg.Type() == gov.TypeMsgDeposit { - depMsg := msg.(gov.MsgDeposit) + if msg.Type() == types.TypeMsgDeposit { + depMsg := msg.(types.MsgDeposit) - deposit := gov.Deposit{ + deposit := types.Deposit{ Depositor: depMsg.Depositor, ProposalID: params.ProposalID, Amount: depMsg.Amount, @@ -213,7 +213,7 @@ func QueryProposerByTxQuery( ) (Proposer, error) { tags := []string{ - fmt.Sprintf("%s='%s'", tags.Action, gov.MsgSubmitProposal{}.Type()), + fmt.Sprintf("%s='%s'", tags.Action, types.MsgSubmitProposal{}.Type()), fmt.Sprintf("%s='%s'", tags.ProposalID, []byte(fmt.Sprintf("%d", proposalID))), } @@ -227,8 +227,8 @@ func QueryProposerByTxQuery( for _, info := range searchResult.Txs { for _, msg := range info.Tx.GetMsgs() { // there should only be a single proposal under the given conditions - if msg.Type() == gov.TypeMsgSubmitProposal { - subMsg := msg.(gov.MsgSubmitProposal) + if msg.Type() == types.TypeMsgSubmitProposal { + subMsg := msg.(types.MsgSubmitProposal) return NewProposer(proposalID, subMsg.Proposer.String()), nil } } @@ -238,7 +238,7 @@ func QueryProposerByTxQuery( // QueryProposalByID takes a proposalID and returns a proposal func QueryProposalByID(proposalID uint64, cliCtx context.CLIContext, cdc *codec.Codec, queryRoute string) ([]byte, error) { - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { return nil, err diff --git a/x/gov/client/utils/utils.go b/x/gov/client/utils/utils.go index 612d82906c98..e23aa3ca1e85 100644 --- a/x/gov/client/utils/utils.go +++ b/x/gov/client/utils/utils.go @@ -1,21 +1,21 @@ package utils -import "github.com/cosmos/cosmos-sdk/x/gov" +import "github.com/cosmos/cosmos-sdk/x/gov/types" // NormalizeVoteOption - normalize user specified vote option func NormalizeVoteOption(option string) string { switch option { case "Yes", "yes": - return gov.OptionYes.String() + return types.OptionYes.String() case "Abstain", "abstain": - return gov.OptionAbstain.String() + return types.OptionAbstain.String() case "No", "no": - return gov.OptionNo.String() + return types.OptionNo.String() case "NoWithVeto", "no_with_veto": - return gov.OptionNoWithVeto.String() + return types.OptionNoWithVeto.String() default: return "" @@ -26,10 +26,10 @@ func NormalizeVoteOption(option string) string { func NormalizeProposalType(proposalType string) string { switch proposalType { case "Text", "text": - return gov.ProposalTypeText + return types.ProposalTypeText case "SoftwareUpgrade", "software_upgrade": - return gov.ProposalTypeSoftwareUpgrade + return types.ProposalTypeSoftwareUpgrade default: return "" diff --git a/x/gov/module.go b/x/gov/module.go index b0ea50488bf0..131ebd961332 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -21,7 +21,7 @@ var ( // app module basics object type AppModuleBasic struct { - proposalCmds []*cobra.Command // proposal subcommands which live in goverance + proposalCmds []*cobra.Command // proposal subcommands which live in governance } // NewAppModuleBasic creates a new AppModuleBasic object diff --git a/x/mint/client/cli/query.go b/x/mint/client/cli/query.go index 91f3f88aabf3..424e79a52ce4 100644 --- a/x/mint/client/cli/query.go +++ b/x/mint/client/cli/query.go @@ -8,13 +8,13 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/mint/types" ) // GetQueryCmd returns the cli query commands for the minting module. func GetQueryCmd(cdc *codec.Codec) *cobra.Command { mintingQueryCmd := &cobra.Command{ - Use: mint.ModuleName, + Use: types.ModuleName, Short: "Querying commands for the minting module", } @@ -39,13 +39,13 @@ func GetCmdQueryParams(cdc *codec.Codec) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - route := fmt.Sprintf("custom/%s/%s", mint.QuerierRoute, mint.QueryParameters) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParameters) res, err := cliCtx.QueryWithData(route, nil) if err != nil { return err } - var params mint.Params + var params types.Params if err := cdc.UnmarshalJSON(res, ¶ms); err != nil { return err } @@ -65,7 +65,7 @@ func GetCmdQueryInflation(cdc *codec.Codec) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - route := fmt.Sprintf("custom/%s/%s", mint.QuerierRoute, mint.QueryInflation) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryInflation) res, err := cliCtx.QueryWithData(route, nil) if err != nil { return err @@ -91,7 +91,7 @@ func GetCmdQueryAnnualProvisions(cdc *codec.Codec) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - route := fmt.Sprintf("custom/%s/%s", mint.QuerierRoute, mint.QueryAnnualProvisions) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAnnualProvisions) res, err := cliCtx.QueryWithData(route, nil) if err != nil { return err diff --git a/x/mint/client/rest/query.go b/x/mint/client/rest/query.go index 2d3cd4a0fea0..171204f79330 100644 --- a/x/mint/client/rest/query.go +++ b/x/mint/client/rest/query.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/mint/types" ) func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { @@ -31,7 +31,7 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Co func queryParamsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - route := fmt.Sprintf("custom/%s/%s", mint.QuerierRoute, mint.QueryParameters) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParameters) res, err := cliCtx.QueryWithData(route, nil) if err != nil { @@ -45,7 +45,7 @@ func queryParamsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Hand func queryInflationHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - route := fmt.Sprintf("custom/%s/%s", mint.QuerierRoute, mint.QueryInflation) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryInflation) res, err := cliCtx.QueryWithData(route, nil) if err != nil { @@ -59,7 +59,7 @@ func queryInflationHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.H func queryAnnualProvisionsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - route := fmt.Sprintf("custom/%s/%s", mint.QuerierRoute, mint.QueryAnnualProvisions) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAnnualProvisions) res, err := cliCtx.QueryWithData(route, nil) if err != nil { diff --git a/x/mint/keeper.go b/x/mint/keeper.go index f298b51611cc..b4815923166e 100644 --- a/x/mint/keeper.go +++ b/x/mint/keeper.go @@ -6,19 +6,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/params" ) -var minterKey = []byte{0x00} // the one key to use for the keeper store - -const ( - // default paramspace for params keeper - DefaultParamspace = ModuleName - - // StoreKey is the default store key for mint - StoreKey = ModuleName - - // QuerierRoute is the querier route for the minting store. - QuerierRoute = StoreKey -) - // keeper of the staking store type Keeper struct { storeKey sdk.StoreKey diff --git a/x/mint/querier.go b/x/mint/querier.go index 4de3fdeeb526..e33b04f8e62d 100644 --- a/x/mint/querier.go +++ b/x/mint/querier.go @@ -7,26 +7,20 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Query endpoints supported by the minting querier -const ( - QueryParameters = "parameters" - QueryInflation = "inflation" - QueryAnnualProvisions = "annual_provisions" + "github.com/cosmos/cosmos-sdk/x/mint/types" ) // NewQuerier returns a minting Querier handler. func NewQuerier(k Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, _ abci.RequestQuery) ([]byte, sdk.Error) { switch path[0] { - case QueryParameters: + case types.QueryParameters: return queryParams(ctx, k) - case QueryInflation: + case types.QueryInflation: return queryInflation(ctx, k) - case QueryAnnualProvisions: + case types.QueryAnnualProvisions: return queryAnnualProvisions(ctx, k) default: diff --git a/x/mint/types/keys.go b/x/mint/types/keys.go new file mode 100644 index 000000000000..6ed2ca5e4333 --- /dev/null +++ b/x/mint/types/keys.go @@ -0,0 +1,23 @@ +package types + +var minterKey = []byte{0x00} // the one key to use for the keeper store + +// nolint +const ( + // module name + ModuleName = "mint" + + // default paramspace for params keeper + DefaultParamspace = ModuleName + + // 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" + QueryAnnualProvisions = "annual_provisions" +) diff --git a/x/mint/params.go b/x/mint/types/params.go similarity index 99% rename from x/mint/params.go rename to x/mint/types/params.go index d51d46fff952..480e60bbdc09 100644 --- a/x/mint/params.go +++ b/x/mint/types/params.go @@ -1,4 +1,4 @@ -package mint +package types import ( "fmt" diff --git a/x/slashing/tick.go b/x/slashing/abci_app.go similarity index 100% rename from x/slashing/tick.go rename to x/slashing/abci_app.go diff --git a/x/slashing/tick_test.go b/x/slashing/abci_app_test.go similarity index 100% rename from x/slashing/tick_test.go rename to x/slashing/abci_app_test.go diff --git a/x/slashing/client/cli/query.go b/x/slashing/client/cli/query.go index 9c4d83777374..3e0934bb6938 100644 --- a/x/slashing/client/cli/query.go +++ b/x/slashing/client/cli/query.go @@ -11,14 +11,14 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) // GetQueryCmd returns the cli query commands for this module func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { // Group slashing queries under a subcommand slashingQueryCmd := &cobra.Command{ - Use: slashing.ModuleName, + Use: types.ModuleName, Short: "Querying commands for the slashing module", } @@ -52,7 +52,7 @@ $ query slashing signing-info cosmosvalconspub1zcjduepqfhvwcmt7p06fvdge } consAddr := sdk.ConsAddress(pk.Address()) - key := slashing.GetValidatorSigningInfoKey(consAddr) + key := types.GetValidatorSigningInfoKey(consAddr) res, err := cliCtx.QueryStore(key, storeName) if err != nil { @@ -63,7 +63,7 @@ $ query slashing signing-info cosmosvalconspub1zcjduepqfhvwcmt7p06fvdge return fmt.Errorf("Validator %s not found in slashing store", consAddr) } - var signingInfo slashing.ValidatorSigningInfo + var signingInfo types.ValidatorSigningInfo cdc.MustUnmarshalBinaryLengthPrefixed(res, &signingInfo) return cliCtx.PrintOutput(signingInfo) }, @@ -83,13 +83,13 @@ $ query slashing params RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - route := fmt.Sprintf("custom/%s/parameters", slashing.QuerierRoute) + route := fmt.Sprintf("custom/%s/parameters", types.QuerierRoute) res, err := cliCtx.QueryWithData(route, nil) if err != nil { return err } - var params slashing.Params + var params types.Params cdc.MustUnmarshalJSON(res, ¶ms) return cliCtx.PrintOutput(params) }, diff --git a/x/slashing/client/cli/tx.go b/x/slashing/client/cli/tx.go index 9cf4d348cf28..d0a3c5bf11ef 100644 --- a/x/slashing/client/cli/tx.go +++ b/x/slashing/client/cli/tx.go @@ -1,21 +1,21 @@ package cli import ( + "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/slashing" - - "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) // GetTxCmd returns the transaction commands for this module func GetTxCmd(cdc *codec.Codec) *cobra.Command { slashingTxCmd := &cobra.Command{ - Use: slashing.ModuleName, + Use: types.ModuleName, Short: "Slashing transactions subcommands", } @@ -44,7 +44,7 @@ $ tx slashing unjail --from mykey valAddr := cliCtx.GetFromAddress() - msg := slashing.NewMsgUnjail(sdk.ValAddress(valAddr)) + msg := types.NewMsgUnjail(sdk.ValAddress(valAddr)) return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) }, } diff --git a/x/slashing/client/rest/query.go b/x/slashing/client/rest/query.go index c17b61053e4f..5b673d5cb94a 100644 --- a/x/slashing/client/rest/query.go +++ b/x/slashing/client/rest/query.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { @@ -40,7 +40,7 @@ func signingInfoHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Hand return } - params := slashing.NewQuerySigningInfoParams(sdk.ConsAddress(pk.Address())) + params := types.NewQuerySigningInfoParams(sdk.ConsAddress(pk.Address())) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -48,7 +48,7 @@ func signingInfoHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Hand return } - route := fmt.Sprintf("custom/%s/%s", slashing.QuerierRoute, slashing.QuerySigningInfo) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySigningInfo) res, err := cliCtx.QueryWithData(route, bz) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -68,14 +68,14 @@ func signingInfoHandlerListFn(cliCtx context.CLIContext, cdc *codec.Codec) http. return } - params := slashing.NewQuerySigningInfosParams(page, limit) + params := types.NewQuerySigningInfosParams(page, limit) bz, err := cdc.MarshalJSON(params) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - route := fmt.Sprintf("custom/%s/%s", slashing.QuerierRoute, slashing.QuerySigningInfos) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySigningInfos) res, err := cliCtx.QueryWithData(route, bz) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -88,7 +88,7 @@ func signingInfoHandlerListFn(cliCtx context.CLIContext, cdc *codec.Codec) http. func queryParamsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - route := fmt.Sprintf("custom/%s/parameters", slashing.QuerierRoute) + route := fmt.Sprintf("custom/%s/parameters", types.QuerierRoute) res, err := cliCtx.QueryWithData(route, nil) if err != nil { diff --git a/x/slashing/client/rest/tx.go b/x/slashing/client/rest/tx.go index 1ca16cbc85ee..4e1941818a20 100644 --- a/x/slashing/client/rest/tx.go +++ b/x/slashing/client/rest/tx.go @@ -11,7 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { @@ -59,7 +59,7 @@ func unjailRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Ha return } - msg := slashing.NewMsgUnjail(valAddr) + msg := types.NewMsgUnjail(valAddr) err = msg.ValidateBasic() if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) diff --git a/x/slashing/genesis.go b/x/slashing/genesis.go index 11a9907bc65c..e594ac6611d8 100644 --- a/x/slashing/genesis.go +++ b/x/slashing/genesis.go @@ -1,80 +1,9 @@ package slashing import ( - "fmt" - "time" - sdk "github.com/cosmos/cosmos-sdk/types" ) -// GenesisState - all slashing state that must be provided at genesis -type GenesisState struct { - Params Params `json:"params"` - SigningInfos map[string]ValidatorSigningInfo `json:"signing_infos"` - MissedBlocks map[string][]MissedBlock `json:"missed_blocks"` -} - -// NewGenesisState creates a new GenesisState object -func NewGenesisState(params Params, signingInfos map[string]ValidatorSigningInfo, - missedBlocks map[string][]MissedBlock) GenesisState { - - return GenesisState{ - Params: params, - SigningInfos: signingInfos, - MissedBlocks: missedBlocks, - } -} - -// MissedBlock -type MissedBlock struct { - Index int64 `json:"index"` - Missed bool `json:"missed"` -} - -// DefaultGenesisState - default GenesisState used by Cosmos Hub -func DefaultGenesisState() GenesisState { - return GenesisState{ - Params: DefaultParams(), - SigningInfos: make(map[string]ValidatorSigningInfo), - MissedBlocks: make(map[string][]MissedBlock), - } -} - -// ValidateGenesis validates the slashing genesis parameters -func ValidateGenesis(data GenesisState) error { - downtime := data.Params.SlashFractionDowntime - if downtime.IsNegative() || downtime.GT(sdk.OneDec()) { - return fmt.Errorf("Slashing fraction downtime should be less than or equal to one and greater than zero, is %s", downtime.String()) - } - - dblSign := data.Params.SlashFractionDoubleSign - if dblSign.IsNegative() || dblSign.GT(sdk.OneDec()) { - return fmt.Errorf("Slashing fraction double sign should be less than or equal to one and greater than zero, is %s", dblSign.String()) - } - - minSign := data.Params.MinSignedPerWindow - if minSign.IsNegative() || minSign.GT(sdk.OneDec()) { - return fmt.Errorf("Min signed per window should be less than or equal to one and greater than zero, is %s", minSign.String()) - } - - maxEvidence := data.Params.MaxEvidenceAge - if maxEvidence < 1*time.Minute { - return fmt.Errorf("Max evidence age must be at least 1 minute, is %s", maxEvidence.String()) - } - - downtimeJail := data.Params.DowntimeJailDuration - if downtimeJail < 1*time.Minute { - return fmt.Errorf("Downtime unblond duration must be at least 1 minute, is %s", downtimeJail.String()) - } - - signedWindow := data.Params.SignedBlocksWindow - if signedWindow < 10 { - return fmt.Errorf("Signed blocks window must be at least 10, is %d", signedWindow) - } - - return nil -} - // InitGenesis initialize default parameters // and the keeper's address to pubkey map func InitGenesis(ctx sdk.Context, keeper Keeper, stakingKeeper StakingKeeper, data GenesisState) { diff --git a/x/slashing/hooks.go b/x/slashing/keeper/hooks.go similarity index 99% rename from x/slashing/hooks.go rename to x/slashing/keeper/hooks.go index 5083ca273d67..8497d6ab83a4 100644 --- a/x/slashing/hooks.go +++ b/x/slashing/keeper/hooks.go @@ -1,5 +1,5 @@ // nolint -package slashing +package keeper import ( "time" diff --git a/x/slashing/keeper.go b/x/slashing/keeper/keeper.go similarity index 99% rename from x/slashing/keeper.go rename to x/slashing/keeper/keeper.go index dbd26db95172..8d927c05abd3 100644 --- a/x/slashing/keeper.go +++ b/x/slashing/keeper/keeper.go @@ -1,4 +1,4 @@ -package slashing +package keeper import ( "fmt" diff --git a/x/slashing/keeper_test.go b/x/slashing/keeper/keeper_test.go similarity index 99% rename from x/slashing/keeper_test.go rename to x/slashing/keeper/keeper_test.go index 7b0bd11745d6..0edb20db08a2 100644 --- a/x/slashing/keeper_test.go +++ b/x/slashing/keeper/keeper_test.go @@ -1,4 +1,4 @@ -package slashing +package keeper import ( "testing" diff --git a/x/slashing/keeper/params.go b/x/slashing/keeper/params.go new file mode 100644 index 000000000000..af59bac29891 --- /dev/null +++ b/x/slashing/keeper/params.go @@ -0,0 +1,54 @@ +package keeper + +import ( + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// MaxEvidenceAge - max age for evidence +func (k Keeper) MaxEvidenceAge(ctx sdk.Context) (res time.Duration) { + k.paramspace.Get(ctx, KeyMaxEvidenceAge, &res) + return +} + +// SignedBlocksWindow - sliding window for downtime slashing +func (k Keeper) SignedBlocksWindow(ctx sdk.Context) (res int64) { + k.paramspace.Get(ctx, KeySignedBlocksWindow, &res) + return +} + +// Downtime slashing threshold +func (k Keeper) MinSignedPerWindow(ctx sdk.Context) int64 { + var minSignedPerWindow sdk.Dec + k.paramspace.Get(ctx, KeyMinSignedPerWindow, &minSignedPerWindow) + signedBlocksWindow := k.SignedBlocksWindow(ctx) + + // NOTE: RoundInt64 will never panic as minSignedPerWindow is + // less than 1. + return minSignedPerWindow.MulInt64(signedBlocksWindow).RoundInt64() +} + +// Downtime unbond duration +func (k Keeper) DowntimeJailDuration(ctx sdk.Context) (res time.Duration) { + k.paramspace.Get(ctx, KeyDowntimeJailDuration, &res) + return +} + +// SlashFractionDoubleSign +func (k Keeper) SlashFractionDoubleSign(ctx sdk.Context) (res sdk.Dec) { + k.paramspace.Get(ctx, KeySlashFractionDoubleSign, &res) + return +} + +// SlashFractionDowntime +func (k Keeper) SlashFractionDowntime(ctx sdk.Context) (res sdk.Dec) { + k.paramspace.Get(ctx, KeySlashFractionDowntime, &res) + return +} + +// GetParams returns the total set of slashing parameters. +func (k Keeper) GetParams(ctx sdk.Context) (params Params) { + k.paramspace.GetParamSet(ctx, ¶ms) + return params +} diff --git a/x/slashing/signing_info.go b/x/slashing/keeper/signing_info.go similarity index 58% rename from x/slashing/signing_info.go rename to x/slashing/keeper/signing_info.go index 01f967fd6046..a173cc2ad27a 100644 --- a/x/slashing/signing_info.go +++ b/x/slashing/keeper/signing_info.go @@ -1,9 +1,6 @@ -package slashing +package keeper import ( - "fmt" - "time" - sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -21,7 +18,9 @@ func (k Keeper) getValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress } // Stored by *validator* address (not operator address) -func (k Keeper) IterateValidatorSigningInfos(ctx sdk.Context, handler func(address sdk.ConsAddress, info ValidatorSigningInfo) (stop bool)) { +func (k Keeper) IterateValidatorSigningInfos(ctx sdk.Context, + handler func(address sdk.ConsAddress, info ValidatorSigningInfo) (stop bool)) { + store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, ValidatorSigningInfoKey) defer iter.Close() @@ -56,7 +55,9 @@ func (k Keeper) getValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.Con } // Stored by *validator* address (not operator address) -func (k Keeper) IterateValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.ConsAddress, handler func(index int64, missed bool) (stop bool)) { +func (k Keeper) IterateValidatorMissedBlockBitArray(ctx sdk.Context, + address sdk.ConsAddress, handler func(index int64, missed bool) (stop bool)) { + store := ctx.KVStore(k.storeKey) index := int64(0) // Array may be sparse @@ -89,42 +90,3 @@ func (k Keeper) clearValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.C store.Delete(iter.Key()) } } - -// Signing info for a validator -type ValidatorSigningInfo struct { - Address sdk.ConsAddress `json:"address"` // validator consensus address - StartHeight int64 `json:"start_height"` // height at which validator was first a candidate OR was unjailed - IndexOffset int64 `json:"index_offset"` // index offset into signed block bit array - JailedUntil time.Time `json:"jailed_until"` // timestamp validator cannot be unjailed until - Tombstoned bool `json:"tombstoned"` // whether or not a validator has been tombstoned (killed out of validator set) - MissedBlocksCounter int64 `json:"missed_blocks_counter"` // missed blocks counter (to avoid scanning the array every time) -} - -// Construct a new `ValidatorSigningInfo` struct -func NewValidatorSigningInfo( - condAddr sdk.ConsAddress, startHeight, indexOffset int64, - jailedUntil time.Time, tombstoned bool, missedBlocksCounter int64, -) ValidatorSigningInfo { - - return ValidatorSigningInfo{ - Address: condAddr, - StartHeight: startHeight, - IndexOffset: indexOffset, - JailedUntil: jailedUntil, - Tombstoned: tombstoned, - MissedBlocksCounter: missedBlocksCounter, - } -} - -// Return human readable signing info -func (i ValidatorSigningInfo) String() string { - return fmt.Sprintf(`Validator Signing Info: - Address: %s - Start Height: %d - Index Offset: %d - Jailed Until: %v - Tombstoned: %t - Missed Blocks Counter: %d`, - i.Address, i.StartHeight, i.IndexOffset, i.JailedUntil, - i.Tombstoned, i.MissedBlocksCounter) -} diff --git a/x/slashing/signing_info_test.go b/x/slashing/keeper/signing_info_test.go similarity index 98% rename from x/slashing/signing_info_test.go rename to x/slashing/keeper/signing_info_test.go index d6803af8da48..91967edd6815 100644 --- a/x/slashing/signing_info_test.go +++ b/x/slashing/keeper/signing_info_test.go @@ -1,4 +1,4 @@ -package slashing +package keeper import ( "testing" diff --git a/x/slashing/querier.go b/x/slashing/querier.go index df6144b58515..ebebb9162370 100644 --- a/x/slashing/querier.go +++ b/x/slashing/querier.go @@ -9,13 +9,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// Query endpoints supported by the slashing querier -const ( - QueryParameters = "parameters" - QuerySigningInfo = "signingInfo" - QuerySigningInfos = "signingInfos" -) - // NewQuerier creates a new querier for slashing clients. func NewQuerier(k Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { diff --git a/x/slashing/codec.go b/x/slashing/types/codec.go similarity index 95% rename from x/slashing/codec.go rename to x/slashing/types/codec.go index f48ce6fc6afa..cebd46890557 100644 --- a/x/slashing/codec.go +++ b/x/slashing/types/codec.go @@ -1,4 +1,4 @@ -package slashing +package types import ( "github.com/cosmos/cosmos-sdk/codec" diff --git a/x/slashing/errors.go b/x/slashing/types/errors.go similarity index 99% rename from x/slashing/errors.go rename to x/slashing/types/errors.go index 47a52159213d..2e0fa8349333 100644 --- a/x/slashing/errors.go +++ b/x/slashing/types/errors.go @@ -1,5 +1,5 @@ //nolint -package slashing +package types import ( "fmt" diff --git a/x/slashing/expected_keepers.go b/x/slashing/types/expected_keepers.go similarity index 95% rename from x/slashing/expected_keepers.go rename to x/slashing/types/expected_keepers.go index c0a637abec2a..dd0c0c94928c 100644 --- a/x/slashing/expected_keepers.go +++ b/x/slashing/types/expected_keepers.go @@ -1,4 +1,4 @@ -package slashing +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/slashing/types/genesis.go b/x/slashing/types/genesis.go new file mode 100644 index 000000000000..a375235b798b --- /dev/null +++ b/x/slashing/types/genesis.go @@ -0,0 +1,76 @@ +package types + +import ( + "fmt" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// GenesisState - all slashing state that must be provided at genesis +type GenesisState struct { + Params Params `json:"params"` + SigningInfos map[string]ValidatorSigningInfo `json:"signing_infos"` + MissedBlocks map[string][]MissedBlock `json:"missed_blocks"` +} + +// NewGenesisState creates a new GenesisState object +func NewGenesisState(params Params, signingInfos map[string]ValidatorSigningInfo, + missedBlocks map[string][]MissedBlock) GenesisState { + + return GenesisState{ + Params: params, + SigningInfos: signingInfos, + MissedBlocks: missedBlocks, + } +} + +// MissedBlock +type MissedBlock struct { + Index int64 `json:"index"` + Missed bool `json:"missed"` +} + +// DefaultGenesisState - default GenesisState used by Cosmos Hub +func DefaultGenesisState() GenesisState { + return GenesisState{ + Params: DefaultParams(), + SigningInfos: make(map[string]ValidatorSigningInfo), + MissedBlocks: make(map[string][]MissedBlock), + } +} + +// ValidateGenesis validates the slashing genesis parameters +func ValidateGenesis(data GenesisState) error { + downtime := data.Params.SlashFractionDowntime + if downtime.IsNegative() || downtime.GT(sdk.OneDec()) { + return fmt.Errorf("Slashing fraction downtime should be less than or equal to one and greater than zero, is %s", downtime.String()) + } + + dblSign := data.Params.SlashFractionDoubleSign + if dblSign.IsNegative() || dblSign.GT(sdk.OneDec()) { + return fmt.Errorf("Slashing fraction double sign should be less than or equal to one and greater than zero, is %s", dblSign.String()) + } + + minSign := data.Params.MinSignedPerWindow + if minSign.IsNegative() || minSign.GT(sdk.OneDec()) { + return fmt.Errorf("Min signed per window should be less than or equal to one and greater than zero, is %s", minSign.String()) + } + + maxEvidence := data.Params.MaxEvidenceAge + if maxEvidence < 1*time.Minute { + return fmt.Errorf("Max evidence age must be at least 1 minute, is %s", maxEvidence.String()) + } + + downtimeJail := data.Params.DowntimeJailDuration + if downtimeJail < 1*time.Minute { + return fmt.Errorf("Downtime unblond duration must be at least 1 minute, is %s", downtimeJail.String()) + } + + signedWindow := data.Params.SignedBlocksWindow + if signedWindow < 10 { + return fmt.Errorf("Signed blocks window must be at least 10, is %d", signedWindow) + } + + return nil +} diff --git a/x/slashing/keys.go b/x/slashing/types/keys.go similarity index 92% rename from x/slashing/keys.go rename to x/slashing/types/keys.go index 009a31b4aa48..0b4f291f64e8 100644 --- a/x/slashing/keys.go +++ b/x/slashing/types/keys.go @@ -1,4 +1,4 @@ -package slashing +package types import ( "encoding/binary" @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// nolint const ( // StoreKey is the store key string for slashing StoreKey = ModuleName @@ -15,6 +16,11 @@ const ( // QuerierRoute is the querier route for slashing QuerierRoute = ModuleName + + // Query endpoints supported by the slashing querier + QueryParameters = "parameters" + QuerySigningInfo = "signingInfo" + QuerySigningInfos = "signingInfos" ) // key prefix bytes diff --git a/x/slashing/msg.go b/x/slashing/types/msg.go similarity index 98% rename from x/slashing/msg.go rename to x/slashing/types/msg.go index 5e49969f8732..aa0aac534388 100644 --- a/x/slashing/msg.go +++ b/x/slashing/types/msg.go @@ -1,4 +1,4 @@ -package slashing +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/slashing/msg_test.go b/x/slashing/types/msg_test.go similarity index 95% rename from x/slashing/msg_test.go rename to x/slashing/types/msg_test.go index f0e19fc54294..31f7a70e75db 100644 --- a/x/slashing/msg_test.go +++ b/x/slashing/types/msg_test.go @@ -1,4 +1,4 @@ -package slashing +package types import ( "testing" diff --git a/x/slashing/params.go b/x/slashing/types/params.go similarity index 71% rename from x/slashing/params.go rename to x/slashing/types/params.go index 98cae397fe6f..6173effe016c 100644 --- a/x/slashing/params.go +++ b/x/slashing/types/params.go @@ -1,4 +1,4 @@ -package slashing +package types import ( "fmt" @@ -100,50 +100,3 @@ func DefaultParams() Params { SlashFractionDowntime: DefaultSlashFractionDowntime, } } - -// MaxEvidenceAge - max age for evidence -func (k Keeper) MaxEvidenceAge(ctx sdk.Context) (res time.Duration) { - k.paramspace.Get(ctx, KeyMaxEvidenceAge, &res) - return -} - -// SignedBlocksWindow - sliding window for downtime slashing -func (k Keeper) SignedBlocksWindow(ctx sdk.Context) (res int64) { - k.paramspace.Get(ctx, KeySignedBlocksWindow, &res) - return -} - -// Downtime slashing threshold -func (k Keeper) MinSignedPerWindow(ctx sdk.Context) int64 { - var minSignedPerWindow sdk.Dec - k.paramspace.Get(ctx, KeyMinSignedPerWindow, &minSignedPerWindow) - signedBlocksWindow := k.SignedBlocksWindow(ctx) - - // NOTE: RoundInt64 will never panic as minSignedPerWindow is - // less than 1. - return minSignedPerWindow.MulInt64(signedBlocksWindow).RoundInt64() -} - -// Downtime unbond duration -func (k Keeper) DowntimeJailDuration(ctx sdk.Context) (res time.Duration) { - k.paramspace.Get(ctx, KeyDowntimeJailDuration, &res) - return -} - -// SlashFractionDoubleSign -func (k Keeper) SlashFractionDoubleSign(ctx sdk.Context) (res sdk.Dec) { - k.paramspace.Get(ctx, KeySlashFractionDoubleSign, &res) - return -} - -// SlashFractionDowntime -func (k Keeper) SlashFractionDowntime(ctx sdk.Context) (res sdk.Dec) { - k.paramspace.Get(ctx, KeySlashFractionDowntime, &res) - return -} - -// GetParams returns the total set of slashing parameters. -func (k Keeper) GetParams(ctx sdk.Context) (params Params) { - k.paramspace.GetParamSet(ctx, ¶ms) - return params -} diff --git a/x/slashing/types/signing_info.go b/x/slashing/types/signing_info.go new file mode 100644 index 000000000000..dba9e434c30c --- /dev/null +++ b/x/slashing/types/signing_info.go @@ -0,0 +1,47 @@ +package types + +import ( + "fmt" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// Signing info for a validator +type ValidatorSigningInfo struct { + Address sdk.ConsAddress `json:"address"` // validator consensus address + StartHeight int64 `json:"start_height"` // height at which validator was first a candidate OR was unjailed + IndexOffset int64 `json:"index_offset"` // index offset into signed block bit array + JailedUntil time.Time `json:"jailed_until"` // timestamp validator cannot be unjailed until + Tombstoned bool `json:"tombstoned"` // whether or not a validator has been tombstoned (killed out of validator set) + MissedBlocksCounter int64 `json:"missed_blocks_counter"` // missed blocks counter (to avoid scanning the array every time) +} + +// Construct a new `ValidatorSigningInfo` struct +func NewValidatorSigningInfo( + condAddr sdk.ConsAddress, startHeight, indexOffset int64, + jailedUntil time.Time, tombstoned bool, missedBlocksCounter int64, +) ValidatorSigningInfo { + + return ValidatorSigningInfo{ + Address: condAddr, + StartHeight: startHeight, + IndexOffset: indexOffset, + JailedUntil: jailedUntil, + Tombstoned: tombstoned, + MissedBlocksCounter: missedBlocksCounter, + } +} + +// Return human readable signing info +func (i ValidatorSigningInfo) String() string { + return fmt.Sprintf(`Validator Signing Info: + Address: %s + Start Height: %d + Index Offset: %d + Jailed Until: %v + Tombstoned: %t + Missed Blocks Counter: %d`, + i.Address, i.StartHeight, i.IndexOffset, i.JailedUntil, + i.Tombstoned, i.MissedBlocksCounter) +} diff --git a/x/staking/client/rest/query.go b/x/staking/client/rest/query.go index 19c52026c713..bee61a2c8f3a 100644 --- a/x/staking/client/rest/query.go +++ b/x/staking/client/rest/query.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/gorilla/mux" ) @@ -103,7 +103,7 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Co // HTTP request handler to query a delegator delegations func delegatorDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryDelegator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", staking.QuerierRoute, staking.QueryDelegatorDelegations)) + return queryDelegator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegatorDelegations)) } // HTTP request handler to query a delegator unbonding delegations @@ -139,15 +139,15 @@ func delegatorTxsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Han switch { case isBondTx: - actions = append(actions, staking.MsgDelegate{}.Type()) + actions = append(actions, types.MsgDelegate{}.Type()) case isUnbondTx: - actions = append(actions, staking.MsgUndelegate{}.Type()) + actions = append(actions, types.MsgUndelegate{}.Type()) case isRedTx: - actions = append(actions, staking.MsgBeginRedelegate{}.Type()) + actions = append(actions, types.MsgBeginRedelegate{}.Type()) case noQuery: - actions = append(actions, staking.MsgDelegate{}.Type()) - actions = append(actions, staking.MsgUndelegate{}.Type()) - actions = append(actions, staking.MsgBeginRedelegate{}.Type()) + actions = append(actions, types.MsgDelegate{}.Type()) + actions = append(actions, types.MsgUndelegate{}.Type()) + actions = append(actions, types.MsgBeginRedelegate{}.Type()) default: w.WriteHeader(http.StatusNoContent) return @@ -178,7 +178,7 @@ func unbondingDelegationHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) h // HTTP request handler to query redelegations func redelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var params staking.QueryRedelegationParams + var params types.QueryRedelegationParams bechDelegatorAddr := r.URL.Query().Get("delegator") bechSrcValidatorAddr := r.URL.Query().Get("validator_from") @@ -228,7 +228,7 @@ func redelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Ha // HTTP request handler to query a delegation func delegationHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryBonds(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", staking.QuerierRoute, staking.QueryDelegation)) + return queryBonds(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegation)) } // HTTP request handler to query all delegator bonded validators @@ -255,14 +255,14 @@ func validatorsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Handl status = sdk.BondStatusBonded } - params := staking.NewQueryValidatorsParams(page, limit, status) + params := types.NewQueryValidatorsParams(page, limit, status) bz, err := cdc.MarshalJSON(params) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - route := fmt.Sprintf("custom/%s/%s", staking.QuerierRoute, staking.QueryValidators) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryValidators) res, err := cliCtx.QueryWithData(route, bz) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -279,7 +279,7 @@ func validatorHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Handle // HTTP request handler to query all unbonding delegations from a validator func validatorDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryValidator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", staking.QuerierRoute, staking.QueryValidatorDelegations)) + return queryValidator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryValidatorDelegations)) } // HTTP request handler to query all unbonding delegations from a validator diff --git a/x/staking/client/rest/rest.go b/x/staking/client/rest/rest.go index 507fcb517fc4..d06cd719df20 100644 --- a/x/staking/client/rest/rest.go +++ b/x/staking/client/rest/rest.go @@ -1,11 +1,11 @@ package rest import ( + "github.com/gorilla/mux" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keys" - - "github.com/gorilla/mux" ) // RegisterRoutes registers staking-related REST handlers to a router diff --git a/x/staking/client/rest/tx.go b/x/staking/client/rest/tx.go index f42a90c9d02a..565cbae6afcf 100644 --- a/x/staking/client/rest/tx.go +++ b/x/staking/client/rest/tx.go @@ -12,7 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, kb keys.Keybase) { @@ -70,7 +70,7 @@ func postDelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context. return } - msg := staking.NewMsgDelegate(req.DelegatorAddress, req.ValidatorAddress, req.Amount) + msg := types.NewMsgDelegate(req.DelegatorAddress, req.ValidatorAddress, req.Amount) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -104,7 +104,7 @@ func postRedelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx contex return } - msg := staking.NewMsgBeginRedelegate(req.DelegatorAddress, req.ValidatorSrcAddress, req.ValidatorDstAddress, req.Amount) + msg := types.NewMsgBeginRedelegate(req.DelegatorAddress, req.ValidatorSrcAddress, req.ValidatorDstAddress, req.Amount) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -138,7 +138,7 @@ func postUnbondingDelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx return } - msg := staking.NewMsgUndelegate(req.DelegatorAddress, req.ValidatorAddress, req.Amount) + msg := types.NewMsgUndelegate(req.DelegatorAddress, req.ValidatorAddress, req.Amount) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return diff --git a/x/staking/client/rest/utils.go b/x/staking/client/rest/utils.go index 0bb363aa55a4..d5ad533814f0 100644 --- a/x/staking/client/rest/utils.go +++ b/x/staking/client/rest/utils.go @@ -11,8 +11,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking/tags" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // contains checks if the a given query contains one of the tx types @@ -50,7 +50,7 @@ func queryBonds(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string) ht return } - params := staking.NewQueryBondsParams(delegatorAddr, validatorAddr) + params := types.NewQueryBondsParams(delegatorAddr, validatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -78,7 +78,7 @@ func queryDelegator(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string return } - params := staking.NewQueryDelegatorParams(delegatorAddr) + params := types.NewQueryDelegatorParams(delegatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -106,7 +106,7 @@ func queryValidator(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string return } - params := staking.NewQueryValidatorParams(validatorAddr) + params := types.NewQueryValidatorParams(validatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { From ca8f4cd6eb084657d3845167d8bac70939344428 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 30 May 2019 14:48:12 -0400 Subject: [PATCH 03/23] circle dep cont. --- crypto/ledger_mock.go | 14 ++++---- crypto/ledger_secp256k1.go | 10 +++--- crypto/ledger_test.go | 4 +-- types/address.go | 1 - types/address_test.go | 2 +- types/{ => module}/module.go | 56 ++++++++++++++++--------------- types/{ => module}/module_test.go | 2 +- 7 files changed, 45 insertions(+), 44 deletions(-) rename types/{ => module}/module.go (82%) rename types/{ => module}/module_test.go (95%) diff --git a/crypto/ledger_mock.go b/crypto/ledger_mock.go index 8d2509bbe3ca..28ea2c9ab107 100644 --- a/crypto/ledger_mock.go +++ b/crypto/ledger_mock.go @@ -8,15 +8,15 @@ import ( "github.com/btcsuite/btcd/btcec" "github.com/pkg/errors" + secp256k1 "github.com/tendermint/btcd/btcec" + "github.com/tendermint/tendermint/crypto" + tmsecp256k1 "github.com/tendermint/tendermint/crypto/secp256k1" + bip39 "github.com/cosmos/go-bip39" "github.com/cosmos/cosmos-sdk/crypto/keys/hd" "github.com/cosmos/cosmos-sdk/tests" - "github.com/cosmos/cosmos-sdk/types" - - secp256k1 "github.com/tendermint/btcd/btcec" - "github.com/tendermint/tendermint/crypto" - tmsecp256k1 "github.com/tendermint/tendermint/crypto/secp256k1" + sdk "github.com/cosmos/cosmos-sdk/types" ) // If ledger support (build tag) has been enabled, which implies a CGO dependency, @@ -41,7 +41,7 @@ func (mock LedgerSECP256K1Mock) GetPublicKeySECP256K1(derivationPath []uint32) ( if derivationPath[0] != 44 { return nil, errors.New("Invalid derivation path") } - if derivationPath[1] != types.CoinType { + if derivationPath[1] != sdk.CoinType { return nil, errors.New("Invalid derivation path") } @@ -80,7 +80,7 @@ func (mock LedgerSECP256K1Mock) GetAddressPubKeySECP256K1(derivationPath []uint3 copy(compressedPublicKey[:], cmp.SerializeCompressed()) // Generate the bech32 addr using existing tmcrypto/etc. - addr := types.AccAddress(compressedPublicKey.Address()).String() + addr := sdk.AccAddress(compressedPublicKey.Address()).String() return pk, addr, err } diff --git a/crypto/ledger_secp256k1.go b/crypto/ledger_secp256k1.go index b0c573f113dd..f2070f6657a9 100644 --- a/crypto/ledger_secp256k1.go +++ b/crypto/ledger_secp256k1.go @@ -7,12 +7,12 @@ import ( "github.com/btcsuite/btcd/btcec" "github.com/pkg/errors" - "github.com/cosmos/cosmos-sdk/crypto/keys/hd" - "github.com/cosmos/cosmos-sdk/types" - tmbtcec "github.com/tendermint/btcd/btcec" tmcrypto "github.com/tendermint/tendermint/crypto" tmsecp256k1 "github.com/tendermint/tendermint/crypto/secp256k1" + + "github.com/cosmos/cosmos-sdk/crypto/keys/hd" + sdk "github.com/cosmos/cosmos-sdk/types" ) var ( @@ -102,7 +102,7 @@ func (pkl PrivKeyLedgerSecp256k1) Sign(message []byte) ([]byte, error) { return sign(device, pkl, message) } -// LedgerShowAddress triggers a ledger device to show the corresponding address. +// LedgerShowAddress triggers a ledger device to show the corresponding sdk. func LedgerShowAddress(path hd.BIP44Params, expectedPubKey tmcrypto.PubKey) error { device, err := getLedgerDevice() if err != nil { @@ -119,7 +119,7 @@ func LedgerShowAddress(path hd.BIP44Params, expectedPubKey tmcrypto.PubKey) erro return fmt.Errorf("the key's pubkey does not match with the one retrieved from Ledger. Check that the HD path and device are the correct ones") } - pubKey2, _, err := getPubKeyAddrSafe(device, path, types.Bech32PrefixAccAddr) + pubKey2, _, err := getPubKeyAddrSafe(device, path, sdk.Bech32PrefixAccAddr) if err != nil { return err } diff --git a/crypto/ledger_test.go b/crypto/ledger_test.go index 5a3f639e0d34..24407d00e838 100644 --- a/crypto/ledger_test.go +++ b/crypto/ledger_test.go @@ -4,12 +4,12 @@ import ( "fmt" "testing" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/stretchr/testify/require" tmcrypto "github.com/tendermint/tendermint/crypto" cryptoAmino "github.com/tendermint/tendermint/crypto/encoding/amino" - "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/crypto/keys/hd" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/types/address.go b/types/address.go index 7fa6074332ec..6342498cc9f7 100644 --- a/types/address.go +++ b/types/address.go @@ -10,7 +10,6 @@ import ( "github.com/tendermint/tendermint/crypto" cryptoAmino "github.com/tendermint/tendermint/crypto/encoding/amino" - "github.com/tendermint/tendermint/libs/bech32" ) diff --git a/types/address_test.go b/types/address_test.go index 406ff1b7e73d..58ad4690bec5 100644 --- a/types/address_test.go +++ b/types/address_test.go @@ -1,4 +1,4 @@ -package types_test +package types import ( "encoding/hex" diff --git a/types/module.go b/types/module/module.go similarity index 82% rename from types/module.go rename to types/module/module.go index 4bc3dbcd1250..c1b9400dd396 100644 --- a/types/module.go +++ b/types/module/module.go @@ -1,5 +1,5 @@ /* -Package types contains application module patterns and associated "manager" functionality. +Package module contains application module patterns and associated "manager" functionality. The module pattern has been broken down by: - independent module functionality (AppModuleBasic) - inter-dependent module functionality (AppModule) @@ -17,17 +17,19 @@ process. This separation is necessary, however we still want to allow for a high level pattern for modules to follow - for instance, such that we don't have to manually register all of the codecs for all the modules. This basic procedure as well as other basic patterns are handled through the use of -ModuleBasicManager. +BasicManager. */ -package types +package module import ( - "context" "encoding/json" - "github.com/cosmos/cosmos-sdk/codec" + "github.com/gorilla/mux" "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" ) //__________________________________________________________________________________________ @@ -47,21 +49,21 @@ type AppModuleBasic interface { } // collections of AppModuleBasic -type ModuleBasicManager []AppModuleBasic +type BasicManager []AppModuleBasic -func NewModuleBasicManager(modules ...AppModuleBasic) ModuleBasicManager { +func NewModuleBasicManager(modules ...AppModuleBasic) BasicManager { return modules } // RegisterCodecs registers all module codecs -func (mbm ModuleBasicManager) RegisterCodec(cdc *codec.Codec) { +func (mbm BasicManager) RegisterCodec(cdc *codec.Codec) { for _, mb := range mbm { mb.RegisterCodec(cdc) } } // Provided default genesis information for all modules -func (mbm ModuleBasicManager) DefaultGenesis() map[string]json.RawMessage { +func (mbm BasicManager) DefaultGenesis() map[string]json.RawMessage { genesis := make(map[string]json.RawMessage) for _, mb := range mbm { genesis[mb.Name()] = mb.DefaultGenesis() @@ -70,7 +72,7 @@ func (mbm ModuleBasicManager) DefaultGenesis() map[string]json.RawMessage { } // Provided default genesis information for all modules -func (mbm ModuleBasicManager) ValidateGenesis(genesis map[string]json.RawMessage) error { +func (mbm BasicManager) ValidateGenesis(genesis map[string]json.RawMessage) error { for _, mb := range mbm { if err := mb.ValidateGenesis(genesis[mb.Name()]); err != nil { return err @@ -80,7 +82,7 @@ func (mbm ModuleBasicManager) ValidateGenesis(genesis map[string]json.RawMessage } // RegisterRestRoutes registers all module rest routes -func (mbm ModuleBasicManager) RegisterRESTRoutes( +func (mbm BasicManager) RegisterRESTRoutes( ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { for _, mb := range mbm { @@ -89,7 +91,7 @@ func (mbm ModuleBasicManager) RegisterRESTRoutes( } // add all tx commands to the rootTxCmd -func (mbm ModuleBasicManager) AddTxCommands(rootTxCmd *cobra.Command) { +func (mbm BasicManager) AddTxCommands(rootTxCmd *cobra.Command) { for _, mb := range mbm { if cmd := mb.GetTxCmd(); cmd != nil { rootTxCmd.AddCommand(cmd) @@ -98,7 +100,7 @@ func (mbm ModuleBasicManager) AddTxCommands(rootTxCmd *cobra.Command) { } // add all query commands to the rootQueryCmd -func (mbm ModuleBasicManager) AddQueryCommands(rootQueryCmd *cobra.Command) { +func (mbm BasicManager) AddQueryCommands(rootQueryCmd *cobra.Command) { for _, mb := range mbm { if cmd := mb.GetQueryCmd(); cmd != nil { rootQueryCmd.AddCommand(cmd) @@ -172,7 +174,7 @@ func (GenesisOnlyAppModule) EndBlock(_ Context, _ abci.RequestEndBlock) ([]abci. //____________________________________________________________________________ // module manager provides the high level utility for managing and executing // operations for a group of modules -type ModuleManager struct { +type Manager struct { Modules map[string]AppModule OrderInitGenesis []string OrderExportGenesis []string @@ -180,8 +182,8 @@ type ModuleManager struct { OrderEndBlockers []string } -// NewModuleManager creates a new ModuleManager object -func NewModuleManager(modules ...AppModule) *ModuleManager { +// NewModuleManager creates a new Manager object +func NewModuleManager(modules ...AppModule) *Manager { moduleMap := make(map[string]AppModule) var modulesStr []string @@ -190,7 +192,7 @@ func NewModuleManager(modules ...AppModule) *ModuleManager { modulesStr = append(modulesStr, module.Name()) } - return &ModuleManager{ + return &Manager{ Modules: moduleMap, OrderInitGenesis: modulesStr, OrderExportGenesis: modulesStr, @@ -200,34 +202,34 @@ func NewModuleManager(modules ...AppModule) *ModuleManager { } // set the order of init genesis calls -func (mm *ModuleManager) SetOrderInitGenesis(moduleNames ...string) { +func (mm *Manager) SetOrderInitGenesis(moduleNames ...string) { mm.OrderInitGenesis = moduleNames } // set the order of export genesis calls -func (mm *ModuleManager) SetOrderExportGenesis(moduleNames ...string) { +func (mm *Manager) SetOrderExportGenesis(moduleNames ...string) { mm.OrderExportGenesis = moduleNames } // set the order of set begin-blocker calls -func (mm *ModuleManager) SetOrderBeginBlockers(moduleNames ...string) { +func (mm *Manager) SetOrderBeginBlockers(moduleNames ...string) { mm.OrderBeginBlockers = moduleNames } // set the order of set end-blocker calls -func (mm *ModuleManager) SetOrderEndBlockers(moduleNames ...string) { +func (mm *Manager) SetOrderEndBlockers(moduleNames ...string) { mm.OrderEndBlockers = moduleNames } // register all module routes and module querier routes -func (mm *ModuleManager) RegisterInvariants(invarRouter InvariantRouter) { +func (mm *Manager) RegisterInvariants(invarRouter InvariantRouter) { for _, module := range mm.Modules { module.RegisterInvariants(invarRouter) } } // register all module routes and module querier routes -func (mm *ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) { +func (mm *Manager) RegisterRoutes(router Router, queryRouter QueryRouter) { for _, module := range mm.Modules { if module.Route() != "" { router.AddRoute(module.Route(), module.NewHandler()) @@ -239,7 +241,7 @@ func (mm *ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) } // perform init genesis functionality for modules -func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.RawMessage) abci.ResponseInitChain { +func (mm *Manager) InitGenesis(ctx Context, genesisData map[string]json.RawMessage) abci.ResponseInitChain { var validatorUpdates []abci.ValidatorUpdate for _, moduleName := range mm.OrderInitGenesis { if genesisData[moduleName] == nil { @@ -262,7 +264,7 @@ func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.Ra } // perform export genesis functionality for modules -func (mm *ModuleManager) ExportGenesis(ctx Context) map[string]json.RawMessage { +func (mm *Manager) ExportGenesis(ctx Context) map[string]json.RawMessage { genesisData := make(map[string]json.RawMessage) for _, moduleName := range mm.OrderExportGenesis { genesisData[moduleName] = mm.Modules[moduleName].ExportGenesis(ctx) @@ -271,7 +273,7 @@ func (mm *ModuleManager) ExportGenesis(ctx Context) map[string]json.RawMessage { } // perform begin block functionality for modules -func (mm *ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { +func (mm *Manager) BeginBlock(ctx Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { tags := EmptyTags() for _, moduleName := range mm.OrderBeginBlockers { moduleTags := mm.Modules[moduleName].BeginBlock(ctx, req) @@ -284,7 +286,7 @@ func (mm *ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) abc } // perform end block functionality for modules -func (mm *ModuleManager) EndBlock(ctx Context, req abci.RequestEndBlock) abci.ResponseEndBlock { +func (mm *Manager) EndBlock(ctx Context, req abci.RequestEndBlock) abci.ResponseEndBlock { validatorUpdates := []abci.ValidatorUpdate{} tags := EmptyTags() for _, moduleName := range mm.OrderEndBlockers { diff --git a/types/module_test.go b/types/module/module_test.go similarity index 95% rename from types/module_test.go rename to types/module/module_test.go index 939d70bfb334..afcc3f4afb2c 100644 --- a/types/module_test.go +++ b/types/module/module_test.go @@ -1,4 +1,4 @@ -package types +package module import ( "testing" From 8206f89547192ae8784b1df4a3518a5fa51a3f3c Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 30 May 2019 15:23:48 -0400 Subject: [PATCH 04/23] working on compile errors --- go.mod | 1 + types/address.go | 1 + types/address_test.go | 2 +- x/auth/module.go | 6 +- x/auth/querier.go | 19 +---- x/auth/test_utils.go | 75 ------------------- x/auth/types/keys.go | 3 + x/auth/{ => types}/params.go | 7 +- x/auth/{ => types}/params_test.go | 2 +- x/auth/types/querier.go | 21 ++++++ x/auth/types/test_utils.go | 117 ++++++++++++++++++++++++++++++ x/bank/module.go | 5 +- x/bank/types/key.go | 5 ++ x/crisis/genesis.go | 29 +------- x/crisis/params.go | 23 +----- x/crisis/{ => types}/codec.go | 2 +- x/crisis/{ => types}/errors.go | 2 +- x/crisis/types/genesis.go | 24 ++++++ x/crisis/types/params.go | 23 ++++++ x/crisis/{ => types}/route.go | 2 +- x/params/module.go | 4 +- 21 files changed, 216 insertions(+), 157 deletions(-) rename x/auth/{ => types}/params.go (95%) rename x/auth/{ => types}/params_test.go (94%) create mode 100644 x/auth/types/querier.go create mode 100644 x/auth/types/test_utils.go create mode 100644 x/bank/types/key.go rename x/crisis/{ => types}/codec.go (96%) rename x/crisis/{ => types}/errors.go (97%) create mode 100644 x/crisis/types/genesis.go create mode 100644 x/crisis/types/params.go rename x/crisis/{ => types}/route.go (97%) diff --git a/go.mod b/go.mod index fb811b9e82ac..652db42afcbb 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/cosmos/go-bip39 v0.0.0-20180618194314-52158e4697b8 github.com/cosmos/ledger-cosmos-go v0.10.3 github.com/fortytw2/leaktest v1.3.0 // indirect + github.com/go-kit/kit v0.8.0 github.com/go-logfmt/logfmt v0.4.0 // indirect github.com/gogo/protobuf v1.1.1 github.com/golang/protobuf v1.3.0 diff --git a/types/address.go b/types/address.go index 6342498cc9f7..7fa6074332ec 100644 --- a/types/address.go +++ b/types/address.go @@ -10,6 +10,7 @@ import ( "github.com/tendermint/tendermint/crypto" cryptoAmino "github.com/tendermint/tendermint/crypto/encoding/amino" + "github.com/tendermint/tendermint/libs/bech32" ) diff --git a/types/address_test.go b/types/address_test.go index 58ad4690bec5..406ff1b7e73d 100644 --- a/types/address_test.go +++ b/types/address_test.go @@ -1,4 +1,4 @@ -package types +package types_test import ( "encoding/hex" diff --git a/x/auth/module.go b/x/auth/module.go index 7ddb5b744502..18f4ba25ff67 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -10,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/client/rest" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( @@ -17,15 +18,12 @@ var ( _ sdk.AppModuleBasic = AppModuleBasic{} ) -// name of this module -const ModuleName = "auth" - // app module basics object type AppModuleBasic struct{} // module name func (AppModuleBasic) Name() string { - return ModuleName + return types.ModuleName } // register module codec diff --git a/x/auth/querier.go b/x/auth/querier.go index 2a5dbf422a92..5e8d6a245fea 100644 --- a/x/auth/querier.go +++ b/x/auth/querier.go @@ -7,11 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" -) - -// query endpoints supported by the auth Querier -const ( - QueryAccount = "account" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) // creates a querier for auth REST endpoints @@ -26,19 +22,8 @@ func NewQuerier(keeper AccountKeeper) sdk.Querier { } } -// defines the params for query: "custom/acc/account" -type QueryAccountParams struct { - Address sdk.AccAddress -} - -func NewQueryAccountParams(addr sdk.AccAddress) QueryAccountParams { - return QueryAccountParams{ - Address: addr, - } -} - func queryAccount(ctx sdk.Context, req abci.RequestQuery, keeper AccountKeeper) ([]byte, sdk.Error) { - var params QueryAccountParams + var params types.QueryAccountParams if err := keeper.cdc.UnmarshalJSON(req.Data, ¶ms); err != nil { return nil, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } diff --git a/x/auth/test_utils.go b/x/auth/test_utils.go index 88b002985d59..294ae075b1cc 100644 --- a/x/auth/test_utils.go +++ b/x/auth/test_utils.go @@ -3,8 +3,6 @@ package auth import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/secp256k1" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" @@ -48,76 +46,3 @@ func setupTestInput() testInput { return testInput{cdc: cdc, ctx: ctx, ak: ak, fck: fck} } - -func newTestMsg(addrs ...sdk.AccAddress) *sdk.TestMsg { - return sdk.NewTestMsg(addrs...) -} - -func newStdFee() StdFee { - return NewStdFee(50000, - sdk.NewCoins(sdk.NewInt64Coin("atom", 150)), - ) -} - -// coins to more than cover the fee -func newCoins() sdk.Coins { - return sdk.Coins{ - sdk.NewInt64Coin("atom", 10000000), - } -} - -func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { - key := secp256k1.GenPrivKey() - pub := key.PubKey() - addr := sdk.AccAddress(pub.Address()) - return key, pub, addr -} - -func newTestTx(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee) sdk.Tx { - sigs := make([]StdSignature, len(privs)) - for i, priv := range privs { - signBytes := StdSignBytes(ctx.ChainID(), accNums[i], seqs[i], fee, msgs, "") - - sig, err := priv.Sign(signBytes) - if err != nil { - panic(err) - } - - sigs[i] = StdSignature{PubKey: priv.PubKey(), Signature: sig} - } - - tx := NewStdTx(msgs, fee, sigs, "") - return tx -} - -func newTestTxWithMemo(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee, memo string) sdk.Tx { - sigs := make([]StdSignature, len(privs)) - for i, priv := range privs { - signBytes := StdSignBytes(ctx.ChainID(), accNums[i], seqs[i], fee, msgs, memo) - - sig, err := priv.Sign(signBytes) - if err != nil { - panic(err) - } - - sigs[i] = StdSignature{PubKey: priv.PubKey(), Signature: sig} - } - - tx := NewStdTx(msgs, fee, sigs, memo) - return tx -} - -func newTestTxWithSignBytes(msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee, signBytes []byte, memo string) sdk.Tx { - sigs := make([]StdSignature, len(privs)) - for i, priv := range privs { - sig, err := priv.Sign(signBytes) - if err != nil { - panic(err) - } - - sigs[i] = StdSignature{PubKey: priv.PubKey(), Signature: sig} - } - - tx := NewStdTx(msgs, fee, sigs, memo) - return tx -} diff --git a/x/auth/types/keys.go b/x/auth/types/keys.go index 674e16910042..a8a73c7650d6 100644 --- a/x/auth/types/keys.go +++ b/x/auth/types/keys.go @@ -3,6 +3,9 @@ package types import sdk "github.com/cosmos/cosmos-sdk/types" const ( + // module name + ModuleName = "auth" + // StoreKey is string representation of the store key for auth StoreKey = "acc" diff --git a/x/auth/params.go b/x/auth/types/params.go similarity index 95% rename from x/auth/params.go rename to x/auth/types/params.go index 971d76e25fb2..8cb09a5b2c76 100644 --- a/x/auth/params.go +++ b/x/auth/types/params.go @@ -1,11 +1,10 @@ -package auth +package types import ( "bytes" "fmt" "strings" - "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/params/subspace" ) @@ -55,8 +54,8 @@ func NewParams(maxMemoCharacters, txSigLimit, txSizeCostPerByte, } // ParamKeyTable for auth module -func ParamKeyTable() params.KeyTable { - return params.NewKeyTable().RegisterParamSet(&Params{}) +func ParamKeyTable() subspace.KeyTable { + return subspace.NewKeyTable().RegisterParamSet(&Params{}) } // ParamSetPairs implements the ParamSet interface and returns all the key/value pairs diff --git a/x/auth/params_test.go b/x/auth/types/params_test.go similarity index 94% rename from x/auth/params_test.go rename to x/auth/types/params_test.go index 67699c4304db..9929b8e06a1c 100644 --- a/x/auth/params_test.go +++ b/x/auth/types/params_test.go @@ -1,4 +1,4 @@ -package auth +package types import ( "testing" diff --git a/x/auth/types/querier.go b/x/auth/types/querier.go new file mode 100644 index 000000000000..e0b45fc7a80a --- /dev/null +++ b/x/auth/types/querier.go @@ -0,0 +1,21 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// query endpoints supported by the auth Querier +const ( + QueryAccount = "account" +) + +// defines the params for query: "custom/acc/account" +type QueryAccountParams struct { + Address sdk.AccAddress +} + +func NewQueryAccountParams(addr sdk.AccAddress) QueryAccountParams { + return QueryAccountParams{ + Address: addr, + } +} diff --git a/x/auth/types/test_utils.go b/x/auth/types/test_utils.go new file mode 100644 index 000000000000..546b74cbd409 --- /dev/null +++ b/x/auth/types/test_utils.go @@ -0,0 +1,117 @@ +// nolint +package types + +import ( + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/crypto/secp256k1" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type testInput struct { + cdc *codec.Codec + ctx sdk.Context + fck FeeCollectionKeeper +} + +func setupTestInput() testInput { + db := dbm.NewMemDB() + + cdc := codec.New() + RegisterBaseAccount(cdc) + + authCapKey := sdk.NewKVStoreKey("authCapKey") + fckCapKey := sdk.NewKVStoreKey("fckCapKey") + keyParams := sdk.NewKVStoreKey("subspace") + tkeyParams := sdk.NewTransientStoreKey("transient_subspace") + + ms := store.NewCommitMultiStore(db) + ms.MountStoreWithDB(authCapKey, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(fckCapKey, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) + ms.LoadLatestVersion() + + fck := NewFeeCollectionKeeper(cdc, fckCapKey) + ctx := sdk.NewContext(ms, abci.Header{ChainID: "test-chain-id"}, false, log.NewNopLogger()) + + return testInput{cdc: cdc, ctx: ctx, fck: fck} +} + +func newTestMsg(addrs ...sdk.AccAddress) *sdk.TestMsg { + return sdk.NewTestMsg(addrs...) +} + +func newStdFee() StdFee { + return NewStdFee(50000, + sdk.NewCoins(sdk.NewInt64Coin("atom", 150)), + ) +} + +// coins to more than cover the fee +func newCoins() sdk.Coins { + return sdk.Coins{ + sdk.NewInt64Coin("atom", 10000000), + } +} + +func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { + key := secp256k1.GenPrivKey() + pub := key.PubKey() + addr := sdk.AccAddress(pub.Address()) + return key, pub, addr +} + +func newTestTx(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee) sdk.Tx { + sigs := make([]StdSignature, len(privs)) + for i, priv := range privs { + signBytes := StdSignBytes(ctx.ChainID(), accNums[i], seqs[i], fee, msgs, "") + + sig, err := priv.Sign(signBytes) + if err != nil { + panic(err) + } + + sigs[i] = StdSignature{PubKey: priv.PubKey(), Signature: sig} + } + + tx := NewStdTx(msgs, fee, sigs, "") + return tx +} + +func newTestTxWithMemo(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee, memo string) sdk.Tx { + sigs := make([]StdSignature, len(privs)) + for i, priv := range privs { + signBytes := StdSignBytes(ctx.ChainID(), accNums[i], seqs[i], fee, msgs, memo) + + sig, err := priv.Sign(signBytes) + if err != nil { + panic(err) + } + + sigs[i] = StdSignature{PubKey: priv.PubKey(), Signature: sig} + } + + tx := NewStdTx(msgs, fee, sigs, memo) + return tx +} + +func newTestTxWithSignBytes(msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee, signBytes []byte, memo string) sdk.Tx { + sigs := make([]StdSignature, len(privs)) + for i, priv := range privs { + sig, err := priv.Sign(signBytes) + if err != nil { + panic(err) + } + + sigs[i] = StdSignature{PubKey: priv.PubKey(), Signature: sig} + } + + tx := NewStdTx(msgs, fee, sigs, memo) + return tx +} diff --git a/x/bank/module.go b/x/bank/module.go index 40901d21f8ca..84c15cb20d4a 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -19,9 +19,6 @@ var ( _ sdk.AppModuleBasic = AppModuleBasic{} ) -// name of this module -const ModuleName = "bank" - // app module basics object type AppModuleBasic struct{} @@ -29,7 +26,7 @@ var _ sdk.AppModuleBasic = AppModuleBasic{} // module name func (AppModuleBasic) Name() string { - return ModuleName + return types.ModuleName } // register module codec diff --git a/x/bank/types/key.go b/x/bank/types/key.go new file mode 100644 index 000000000000..57604b2ab8d4 --- /dev/null +++ b/x/bank/types/key.go @@ -0,0 +1,5 @@ +package types + +const ( + ModuleName = "bank" +) diff --git a/x/crisis/genesis.go b/x/crisis/genesis.go index 7cd702b8486b..29c8c9cb7291 100644 --- a/x/crisis/genesis.go +++ b/x/crisis/genesis.go @@ -2,39 +2,16 @@ package crisis import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/crisis/types" ) -// GenesisState - crisis genesis state -type GenesisState struct { - ConstantFee sdk.Coin `json:"constant_fee"` -} - -// NewGenesisState creates a new GenesisState object -func NewGenesisState(constantFee sdk.Coin) GenesisState { - return GenesisState{ - ConstantFee: constantFee, - } -} - -// DefaultGenesisState creates a default GenesisState object -func DefaultGenesisState() GenesisState { - return GenesisState{ - ConstantFee: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)), - } -} - // new crisis genesis -func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) { +func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) { keeper.SetConstantFee(ctx, data.ConstantFee) } // ExportGenesis returns a GenesisState for a given context and keeper. -func ExportGenesis(ctx sdk.Context, keeper Keeper) GenesisState { +func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { constantFee := keeper.GetConstantFee(ctx) return NewGenesisState(constantFee) } - -// ValidateGenesis - placeholder function -func ValidateGenesis(data GenesisState) error { - return nil -} diff --git a/x/crisis/params.go b/x/crisis/params.go index 14c8a2567315..e8f40759ddc5 100644 --- a/x/crisis/params.go +++ b/x/crisis/params.go @@ -2,33 +2,16 @@ package crisis import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/crisis/types" ) -// Default parameter namespace -const ( - DefaultParamspace = ModuleName -) - -var ( - // key for constant fee parameter - ParamStoreKeyConstantFee = []byte("ConstantFee") -) - -// type declaration for parameters -func ParamKeyTable() params.KeyTable { - return params.NewKeyTable( - ParamStoreKeyConstantFee, sdk.Coin{}, - ) -} - // GetConstantFee get's the constant fee from the paramSpace func (k Keeper) GetConstantFee(ctx sdk.Context) (constantFee sdk.Coin) { - k.paramSpace.Get(ctx, ParamStoreKeyConstantFee, &constantFee) + k.paramSpace.Get(ctx, types.ParamStoreKeyConstantFee, &constantFee) return } // GetConstantFee set's the constant fee in the paramSpace func (k Keeper) SetConstantFee(ctx sdk.Context, constantFee sdk.Coin) { - k.paramSpace.Set(ctx, ParamStoreKeyConstantFee, constantFee) + k.paramSpace.Set(ctx, types.ParamStoreKeyConstantFee, constantFee) } diff --git a/x/crisis/codec.go b/x/crisis/types/codec.go similarity index 96% rename from x/crisis/codec.go rename to x/crisis/types/codec.go index 9d35754139cf..ccc690a4fd08 100644 --- a/x/crisis/codec.go +++ b/x/crisis/types/codec.go @@ -1,4 +1,4 @@ -package crisis +package types import ( "github.com/cosmos/cosmos-sdk/codec" diff --git a/x/crisis/errors.go b/x/crisis/types/errors.go similarity index 97% rename from x/crisis/errors.go rename to x/crisis/types/errors.go index 7a03134fd582..3b7392abfae6 100644 --- a/x/crisis/errors.go +++ b/x/crisis/types/errors.go @@ -1,4 +1,4 @@ -package crisis +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/crisis/types/genesis.go b/x/crisis/types/genesis.go new file mode 100644 index 000000000000..1a7e0f9ae072 --- /dev/null +++ b/x/crisis/types/genesis.go @@ -0,0 +1,24 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// GenesisState - crisis genesis state +type GenesisState struct { + ConstantFee sdk.Coin `json:"constant_fee"` +} + +// NewGenesisState creates a new GenesisState object +func NewGenesisState(constantFee sdk.Coin) GenesisState { + return GenesisState{ + ConstantFee: constantFee, + } +} + +// DefaultGenesisState creates a default GenesisState object +func DefaultGenesisState() GenesisState { + return GenesisState{ + ConstantFee: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)), + } +} diff --git a/x/crisis/types/params.go b/x/crisis/types/params.go new file mode 100644 index 000000000000..a0dbdf726783 --- /dev/null +++ b/x/crisis/types/params.go @@ -0,0 +1,23 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/params" +) + +// Default parameter namespace +const ( + DefaultParamspace = ModuleName +) + +var ( + // key for constant fee parameter + ParamStoreKeyConstantFee = []byte("ConstantFee") +) + +// type declaration for parameters +func ParamKeyTable() params.KeyTable { + return params.NewKeyTable( + ParamStoreKeyConstantFee, sdk.Coin{}, + ) +} diff --git a/x/crisis/route.go b/x/crisis/types/route.go similarity index 97% rename from x/crisis/route.go rename to x/crisis/types/route.go index 0f8808581c26..1096798e8c71 100644 --- a/x/crisis/route.go +++ b/x/crisis/types/route.go @@ -1,4 +1,4 @@ -package crisis +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/params/module.go b/x/params/module.go index 1749dfc5a82e..275303cab076 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -4,12 +4,12 @@ import ( "encoding/json" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/params/types" ) var ( - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleBasic = AppModuleBasic{} ) const moduleName = "params" From 32e14a54992d89ae6cf0954c1bf00a10808c87f1 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 30 May 2019 15:25:08 -0400 Subject: [PATCH 05/23] simapp addition --- simapp/app.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/simapp/app.go b/simapp/app.go index 95036981d645..7666988ae571 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -50,7 +50,7 @@ func init() { staking.AppModuleBasic{}, mint.AppModuleBasic{}, distr.AppModuleBasic{}, - gov.AppModuleBasic{}, + gov.NewAppModuleBasic(paramcli.GetCmdSubmitProposal()), params.AppModuleBasic{}, crisis.AppModuleBasic{}, slashing.AppModuleBasic{}, From 93d6e601211e6dbb6fa35bb2c879954e1807e9b9 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 30 May 2019 15:30:15 -0400 Subject: [PATCH 06/23] ... --- x/auth/ante.go | 43 ++++++++++++++++++++++--------------------- x/auth/keeper.go | 27 ++++++++++++++------------- 2 files changed, 36 insertions(+), 34 deletions(-) diff --git a/x/auth/ante.go b/x/auth/ante.go index b31ac30db304..87f5ccc92a04 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( @@ -30,23 +31,23 @@ func init() { // SignatureVerificationGasConsumer is the type of function that is used to both consume gas when verifying signatures // and also to accept or reject different types of PubKey's. This is where apps can define their own PubKey types. -type SignatureVerificationGasConsumer = func(meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params Params) sdk.Result +type SignatureVerificationGasConsumer = func(meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params types.Params) sdk.Result // NewAnteHandler returns an AnteHandler that checks and increments sequence // numbers, checks signatures & account numbers, and deducts fees from the first // signer. -func NewAnteHandler(ak AccountKeeper, fck FeeCollectionKeeper, sigGasConsumer SignatureVerificationGasConsumer) sdk.AnteHandler { +func NewAnteHandler(ak AccountKeeper, fck types.FeeCollectionKeeper, sigGasConsumer SignatureVerificationGasConsumer) sdk.AnteHandler { return func( ctx sdk.Context, tx sdk.Tx, simulate bool, ) (newCtx sdk.Context, res sdk.Result, abort bool) { - // all transactions must be of type auth.StdTx - stdTx, ok := tx.(StdTx) + // all transactions must be of type auth.types.StdTx + stdTx, ok := tx.(types.StdTx) if !ok { // Set a gas meter with limit 0 as to prevent an infinite gas meter attack // during runTx. newCtx = SetGasMeter(simulate, ctx, 0) - return newCtx, sdk.ErrInternal("tx must be StdTx").Result(), true + return newCtx, sdk.ErrInternal("tx must be types.StdTx").Result(), true } params := ak.GetParams(ctx) @@ -103,7 +104,7 @@ func NewAnteHandler(ak AccountKeeper, fck FeeCollectionKeeper, sigGasConsumer Si // stdSigs contains the sequence number, account number, and signatures. // When simulating, this would just be a 0-length slice. signerAddrs := stdTx.GetSigners() - signerAccs := make([]Account, len(signerAddrs)) + signerAccs := make([]types.Account, len(signerAddrs)) isGenesis := ctx.BlockHeight() == 0 // fetch first signer, who's going to pay the fees @@ -151,7 +152,7 @@ func NewAnteHandler(ak AccountKeeper, fck FeeCollectionKeeper, sigGasConsumer Si // GetSignerAcc returns an account for a given address that is expected to sign // a transaction. -func GetSignerAcc(ctx sdk.Context, ak AccountKeeper, addr sdk.AccAddress) (Account, sdk.Result) { +func GetSignerAcc(ctx sdk.Context, ak AccountKeeper, addr sdk.AccAddress) (types.Account, sdk.Result) { if acc := ak.GetAccount(ctx, addr); acc != nil { return acc, sdk.Result{} } @@ -160,7 +161,7 @@ func GetSignerAcc(ctx sdk.Context, ak AccountKeeper, addr sdk.AccAddress) (Accou // ValidateSigCount validates that the transaction has a valid cumulative total // amount of signatures. -func ValidateSigCount(stdTx StdTx, params Params) sdk.Result { +func ValidateSigCount(stdTx types.StdTx, params types.Params) sdk.Result { stdSigs := stdTx.GetSignatures() sigCount := 0 @@ -177,7 +178,7 @@ func ValidateSigCount(stdTx StdTx, params Params) sdk.Result { } // ValidateMemo validates the memo size. -func ValidateMemo(stdTx StdTx, params Params) sdk.Result { +func ValidateMemo(stdTx types.StdTx, params types.Params) sdk.Result { memoLength := len(stdTx.GetMemo()) if uint64(memoLength) > params.MaxMemoCharacters { return sdk.ErrMemoTooLarge( @@ -194,9 +195,9 @@ func ValidateMemo(stdTx StdTx, params Params) sdk.Result { // verify the signature and increment the sequence. If the account doesn't have // a pubkey, set it. func processSig( - ctx sdk.Context, acc Account, sig StdSignature, signBytes []byte, simulate bool, params Params, + ctx sdk.Context, acc types.Account, sig types.StdSignature, signBytes []byte, simulate bool, params types.Params, sigGasConsumer SignatureVerificationGasConsumer, -) (updatedAcc Account, res sdk.Result) { +) (updatedAcc types.Account, res sdk.Result) { pubKey, res := ProcessPubKey(acc, sig, simulate) if !res.IsOK() { @@ -211,7 +212,7 @@ func processSig( if simulate { // Simulated txs should not contain a signature and are not required to // contain a pubkey, so we must account for tx size of including a - // StdSignature (Amino encoding) and simulate gas consumption + // types.StdSignature (Amino encoding) and simulate gas consumption // (assuming a SECP256k1 simulation key). consumeSimSigGas(ctx.GasMeter(), pubKey, sig, params) } @@ -231,8 +232,8 @@ func processSig( return acc, res } -func consumeSimSigGas(gasmeter sdk.GasMeter, pubkey crypto.PubKey, sig StdSignature, params Params) { - simSig := StdSignature{PubKey: pubkey} +func consumeSimSigGas(gasmeter sdk.GasMeter, pubkey crypto.PubKey, sig types.StdSignature, params types.Params) { + simSig := types.StdSignature{PubKey: pubkey} if len(sig.Signature) == 0 { simSig.Signature = simSecp256k1Sig[:] } @@ -250,10 +251,10 @@ func consumeSimSigGas(gasmeter sdk.GasMeter, pubkey crypto.PubKey, sig StdSignat } // ProcessPubKey verifies that the given account address matches that of the -// StdSignature. In addition, it will set the public key of the account if it +// types.StdSignature. In addition, it will set the public key of the account if it // has not been set. -func ProcessPubKey(acc Account, sig StdSignature, simulate bool) (crypto.PubKey, sdk.Result) { - // If pubkey is not known for account, set it from the StdSignature. +func ProcessPubKey(acc types.Account, sig types.StdSignature, simulate bool) (crypto.PubKey, sdk.Result) { + // If pubkey is not known for account, set it from the types.StdSignature. pubKey := acc.GetPubKey() if simulate { // In simulate mode the transaction comes with no signatures, thus if the @@ -286,7 +287,7 @@ func ProcessPubKey(acc Account, sig StdSignature, simulate bool) (crypto.PubKey, // for signature verification based upon the public key type. The cost is fetched from the given params and is matched // by the concrete type. func DefaultSigVerificationGasConsumer( - meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params Params, + meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params types.Params, ) sdk.Result { switch pubkey := pubkey.(type) { case ed25519.PubKeyEd25519: @@ -311,7 +312,7 @@ func DefaultSigVerificationGasConsumer( func consumeMultisignatureVerificationGas(meter sdk.GasMeter, sig multisig.Multisignature, pubkey multisig.PubKeyMultisigThreshold, - params Params) { + params types.Params) { size := sig.BitArray.Size() sigIndex := 0 @@ -327,7 +328,7 @@ func consumeMultisignatureVerificationGas(meter sdk.GasMeter, // // NOTE: We could use the CoinKeeper (in addition to the AccountKeeper, because // the CoinKeeper doesn't give us accounts), but it seems easier to do this. -func DeductFees(blockTime time.Time, acc Account, fee StdFee) (Account, sdk.Result) { +func DeductFees(blockTime time.Time, acc types.Account, fee StdFee) (types.Account, sdk.Result) { coins := acc.GetCoins() feeAmount := fee.Amount @@ -403,7 +404,7 @@ func SetGasMeter(simulate bool, ctx sdk.Context, gasLimit uint64) sdk.Context { // GetSignBytes returns a slice of bytes to sign over for a given transaction // and an account. -func GetSignBytes(chainID string, stdTx StdTx, acc Account, genesis bool) []byte { +func GetSignBytes(chainID string, stdTx types.StdTx, acc types.Account, genesis bool) []byte { var accNum uint64 if !genesis { accNum = acc.GetAccountNumber() diff --git a/x/auth/keeper.go b/x/auth/keeper.go index 105945994f5e..1cfe3fe1027c 100644 --- a/x/auth/keeper.go +++ b/x/auth/keeper.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/params/subspace" ) @@ -16,8 +17,8 @@ type AccountKeeper struct { // The (unexposed) key used to access the store from the Context. key sdk.StoreKey - // The prototypical Account constructor. - proto func() Account + // The prototypical types.Account constructor. + proto func() types.Account // The codec codec for binary encoding/decoding of accounts. cdc *codec.Codec @@ -29,7 +30,7 @@ type AccountKeeper struct { // (binary) encode and decode concrete sdk.Accounts. // nolint func NewAccountKeeper( - cdc *codec.Codec, key sdk.StoreKey, paramstore subspace.Subspace, proto func() Account, + cdc *codec.Codec, key sdk.StoreKey, paramstore subspace.Subspace, proto func() types.Account, ) AccountKeeper { return AccountKeeper{ @@ -41,7 +42,7 @@ func NewAccountKeeper( } // NewAccountWithAddress implements sdk.AccountKeeper. -func (ak AccountKeeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) Account { +func (ak AccountKeeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) types.Account { acc := ak.proto() err := acc.SetAddress(addr) if err != nil { @@ -57,7 +58,7 @@ func (ak AccountKeeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddre } // NewAccount creates a new account -func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc Account) Account { +func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc types.Account) types.Account { if err := acc.SetAccountNumber(ak.GetNextAccountNumber(ctx)); err != nil { panic(err) } @@ -65,7 +66,7 @@ func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc Account) Account { } // GetAccount implements sdk.AccountKeeper. -func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) Account { +func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.Account { store := ctx.KVStore(ak.key) bz := store.Get(AddressStoreKey(addr)) if bz == nil { @@ -76,9 +77,9 @@ func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) Account } // GetAllAccounts returns all accounts in the accountKeeper. -func (ak AccountKeeper) GetAllAccounts(ctx sdk.Context) []Account { - accounts := []Account{} - appendAccount := func(acc Account) (stop bool) { +func (ak AccountKeeper) GetAllAccounts(ctx sdk.Context) []types.Account { + accounts := []types.Account{} + appendAccount := func(acc types.Account) (stop bool) { accounts = append(accounts, acc) return false } @@ -87,7 +88,7 @@ func (ak AccountKeeper) GetAllAccounts(ctx sdk.Context) []Account { } // SetAccount implements sdk.AccountKeeper. -func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc Account) { +func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc types.Account) { addr := acc.GetAddress() store := ctx.KVStore(ak.key) bz, err := ak.cdc.MarshalBinaryBare(acc) @@ -99,14 +100,14 @@ func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc Account) { // RemoveAccount removes an account for the account mapper store. // NOTE: this will cause supply invariant violation if called -func (ak AccountKeeper) RemoveAccount(ctx sdk.Context, acc Account) { +func (ak AccountKeeper) RemoveAccount(ctx sdk.Context, acc types.Account) { addr := acc.GetAddress() store := ctx.KVStore(ak.key) store.Delete(AddressStoreKey(addr)) } // IterateAccounts implements sdk.AccountKeeper. -func (ak AccountKeeper) IterateAccounts(ctx sdk.Context, process func(Account) (stop bool)) { +func (ak AccountKeeper) IterateAccounts(ctx sdk.Context, process func(types.Account) (stop bool)) { store := ctx.KVStore(ak.key) iter := sdk.KVStorePrefixIterator(store, AddressStoreKeyPrefix) defer iter.Close() @@ -192,7 +193,7 @@ func (ak AccountKeeper) GetParams(ctx sdk.Context) (params Params) { // ----------------------------------------------------------------------------- // Misc. -func (ak AccountKeeper) decodeAccount(bz []byte) (acc Account) { +func (ak AccountKeeper) decodeAccount(bz []byte) (acc types.Account) { err := ak.cdc.UnmarshalBinaryBare(bz, &acc) if err != nil { panic(err) From bf098516ece94f08fb009273495a1e3f3cfbeef1 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 30 May 2019 21:07:47 -0400 Subject: [PATCH 07/23] working through compile errors --- types/module/module.go | 45 ++++---- x/auth/alias.go | 80 +++++++++++++ x/auth/ante.go | 10 +- x/auth/ante_test.go | 11 +- x/auth/client/txbuilder/stdsignmsg.go | 16 +-- x/auth/genaccounts/module.go | 14 ++- x/auth/genesis.go | 9 +- x/auth/keeper.go | 20 ++-- x/auth/module.go | 32 +++--- x/auth/querier.go | 2 +- x/auth/test_utils.go | 13 ++- x/auth/types/codec.go | 8 +- x/auth/types/keys.go | 3 +- x/auth/types/params.go | 4 +- x/auth/types/stdtx.go | 10 +- x/bank/alias.go | 45 ++++++++ x/bank/app_test.go | 55 ++++----- x/bank/bench_test.go | 6 +- x/bank/client/rest/sendtx.go | 7 +- x/bank/handler.go | 13 ++- x/bank/invariants.go | 3 +- x/bank/keeper.go | 15 +-- x/bank/keeper_test.go | 19 +-- x/bank/module.go | 25 ++-- x/bank/types/codec.go | 6 +- x/bank/types/key.go | 1 + x/bank/types/msgs.go | 4 +- x/bank/{ => types}/params.go | 2 +- x/crisis/alias.go | 38 ++++++ x/crisis/client/cli/tx.go | 2 +- x/crisis/genesis.go | 2 +- x/crisis/handler.go | 7 +- x/crisis/keeper.go | 11 +- x/crisis/module.go | 29 ++--- x/crisis/types/codec.go | 9 +- x/crisis/types/msgs.go | 2 +- x/distribution/alias.go | 58 +++++----- x/distribution/client/cli/tx.go | 2 +- x/distribution/keeper/proposal_handler.go | 1 + x/distribution/keeper/querier.go | 134 ++++------------------ x/distribution/keeper/querier_test.go | 50 ++++---- x/distribution/module.go | 7 +- x/distribution/types/querier.go | 97 ++++++++++++++++ x/genutil/client/cli/gentx.go | 3 +- x/genutil/client/cli/init.go | 4 +- x/genutil/client/cli/init_test.go | 3 +- x/genutil/client/cli/validate_genesis.go | 4 +- x/genutil/module.go | 11 +- x/gov/alias.go | 19 +++ x/gov/client/cli/query.go | 2 +- x/gov/client/cli/tx.go | 6 +- x/gov/module.go | 17 ++- x/gov/querier.go | 81 +------------ x/gov/types/querier.go | 83 ++++++++++++++ x/mint/alias.go | 39 +++++++ x/mint/client/cli/query.go | 3 +- x/mint/genesis.go | 5 +- x/mint/module.go | 9 +- x/mint/{ => types}/codec.go | 9 +- x/params/module.go | 13 +++ x/slashing/genesis.go | 6 +- x/slashing/handler.go | 3 +- x/slashing/keeper/hooks.go | 3 +- x/slashing/keeper/keeper.go | 11 +- x/slashing/keeper/keeper_test.go | 7 +- x/slashing/keeper/params.go | 15 +-- x/slashing/keeper/signing_info.go | 25 ++-- x/slashing/module.go | 15 +-- x/slashing/querier.go | 20 ---- x/slashing/types/keys.go | 5 +- x/slashing/types/querier.go | 25 ++++ x/staking/client/cli/query.go | 26 ++--- x/staking/client/cli/tx.go | 10 +- x/staking/client/rest/query.go | 13 ++- x/staking/client/rest/rest.go | 5 +- x/staking/client/rest/tx.go | 15 ++- x/staking/client/rest/utils.go | 8 +- x/staking/module.go | 14 ++- x/staking/types/expected_keepers.go | 4 +- 79 files changed, 884 insertions(+), 584 deletions(-) create mode 100644 x/auth/alias.go create mode 100644 x/bank/alias.go rename x/bank/{ => types}/params.go (97%) create mode 100644 x/crisis/alias.go create mode 100644 x/distribution/types/querier.go create mode 100644 x/gov/types/querier.go create mode 100644 x/mint/alias.go rename x/mint/{ => types}/codec.go (53%) create mode 100644 x/slashing/types/querier.go diff --git a/types/module/module.go b/types/module/module.go index c1b9400dd396..ed052e067de4 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -30,6 +30,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" ) //__________________________________________________________________________________________ @@ -112,8 +113,8 @@ func (mbm BasicManager) AddQueryCommands(rootQueryCmd *cobra.Command) { // AppModuleGenesis is the standard form for an application module genesis functions type AppModuleGenesis interface { AppModuleBasic - InitGenesis(Context, json.RawMessage) []abci.ValidatorUpdate - ExportGenesis(Context) json.RawMessage + InitGenesis(sdk.Context, json.RawMessage) []abci.ValidatorUpdate + ExportGenesis(sdk.Context) json.RawMessage } // AppModule is the standard form for an application module @@ -121,16 +122,16 @@ type AppModule interface { AppModuleGenesis // registers - RegisterInvariants(InvariantRouter) + RegisterInvariants(sdk.InvariantRouter) // routes Route() string - NewHandler() Handler + NewHandler() sdk.Handler QuerierRoute() string - NewQuerierHandler() Querier + NewQuerierHandler() sdk.Querier - BeginBlock(Context, abci.RequestBeginBlock) Tags - EndBlock(Context, abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags) + BeginBlock(sdk.Context, abci.RequestBeginBlock) sdk.Tags + EndBlock(sdk.Context, abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) } //___________________________ @@ -147,28 +148,28 @@ func NewGenesisOnlyAppModule(amg AppModuleGenesis) AppModule { } // register invariants -func (GenesisOnlyAppModule) RegisterInvariants(_ InvariantRouter) {} +func (GenesisOnlyAppModule) RegisterInvariants(_ sdk.InvariantRouter) {} // module message route ngame func (GenesisOnlyAppModule) Route() string { return "" } // module handler -func (GenesisOnlyAppModule) NewHandler() Handler { return nil } +func (GenesisOnlyAppModule) NewHandler() sdk.Handler { return nil } // module querier route ngame func (GenesisOnlyAppModule) QuerierRoute() string { return "" } // module querier -func (gam GenesisOnlyAppModule) NewQuerierHandler() Querier { return nil } +func (gam GenesisOnlyAppModule) NewQuerierHandler() sdk.Querier { return nil } // module begin-block -func (gam GenesisOnlyAppModule) BeginBlock(ctx Context, req abci.RequestBeginBlock) Tags { - return EmptyTags() +func (gam GenesisOnlyAppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) sdk.Tags { + return sdk.EmptyTags() } // module end-block -func (GenesisOnlyAppModule) EndBlock(_ Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags) { - return []abci.ValidatorUpdate{}, EmptyTags() +func (GenesisOnlyAppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) { + return []abci.ValidatorUpdate{}, sdk.EmptyTags() } //____________________________________________________________________________ @@ -222,14 +223,14 @@ func (mm *Manager) SetOrderEndBlockers(moduleNames ...string) { } // register all module routes and module querier routes -func (mm *Manager) RegisterInvariants(invarRouter InvariantRouter) { +func (mm *Manager) RegisterInvariants(invarRouter sdk.InvariantRouter) { for _, module := range mm.Modules { module.RegisterInvariants(invarRouter) } } // register all module routes and module querier routes -func (mm *Manager) RegisterRoutes(router Router, queryRouter QueryRouter) { +func (mm *Manager) RegisterRoutes(router sdk.Router, queryRouter sdk.QueryRouter) { for _, module := range mm.Modules { if module.Route() != "" { router.AddRoute(module.Route(), module.NewHandler()) @@ -241,7 +242,7 @@ func (mm *Manager) RegisterRoutes(router Router, queryRouter QueryRouter) { } // perform init genesis functionality for modules -func (mm *Manager) InitGenesis(ctx Context, genesisData map[string]json.RawMessage) abci.ResponseInitChain { +func (mm *Manager) InitGenesis(ctx sdk.Context, genesisData map[string]json.RawMessage) abci.ResponseInitChain { var validatorUpdates []abci.ValidatorUpdate for _, moduleName := range mm.OrderInitGenesis { if genesisData[moduleName] == nil { @@ -264,7 +265,7 @@ func (mm *Manager) InitGenesis(ctx Context, genesisData map[string]json.RawMessa } // perform export genesis functionality for modules -func (mm *Manager) ExportGenesis(ctx Context) map[string]json.RawMessage { +func (mm *Manager) ExportGenesis(ctx sdk.Context) map[string]json.RawMessage { genesisData := make(map[string]json.RawMessage) for _, moduleName := range mm.OrderExportGenesis { genesisData[moduleName] = mm.Modules[moduleName].ExportGenesis(ctx) @@ -273,8 +274,8 @@ func (mm *Manager) ExportGenesis(ctx Context) map[string]json.RawMessage { } // perform begin block functionality for modules -func (mm *Manager) BeginBlock(ctx Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - tags := EmptyTags() +func (mm *Manager) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { + tags := sdk.EmptyTags() for _, moduleName := range mm.OrderBeginBlockers { moduleTags := mm.Modules[moduleName].BeginBlock(ctx, req) tags = tags.AppendTags(moduleTags) @@ -286,9 +287,9 @@ func (mm *Manager) BeginBlock(ctx Context, req abci.RequestBeginBlock) abci.Resp } // perform end block functionality for modules -func (mm *Manager) EndBlock(ctx Context, req abci.RequestEndBlock) abci.ResponseEndBlock { +func (mm *Manager) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { validatorUpdates := []abci.ValidatorUpdate{} - tags := EmptyTags() + tags := sdk.EmptyTags() for _, moduleName := range mm.OrderEndBlockers { moduleValUpdates, moduleTags := mm.Modules[moduleName].EndBlock(ctx, req) tags = tags.AppendTags(moduleTags) diff --git a/x/auth/alias.go b/x/auth/alias.go new file mode 100644 index 000000000000..dd2c8c35ad9d --- /dev/null +++ b/x/auth/alias.go @@ -0,0 +1,80 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/auth/types +package auth + +import ( + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +const ( + ModuleName = types.ModuleName + StoreKey = types.StoreKey + FeeStoreKey = types.FeeStoreKey + QuerierRoute = types.QuerierRoute + DefaultParamspace = types.DefaultParamspace + DefaultMaxMemoCharacters = types.DefaultMaxMemoCharacters + DefaultTxSigLimit = types.DefaultTxSigLimit + DefaultTxSizeCostPerByte = types.DefaultTxSizeCostPerByte + DefaultSigVerifyCostED25519 = types.DefaultSigVerifyCostED25519 + DefaultSigVerifyCostSecp256k1 = types.DefaultSigVerifyCostSecp256k1 + QueryAccount = types.QueryAccount +) + +var ( + // functions aliases + NewBaseAccount = types.NewBaseAccount + ProtoBaseAccount = types.ProtoBaseAccount + NewBaseAccountWithAddress = types.NewBaseAccountWithAddress + NewBaseVestingAccount = types.NewBaseVestingAccount + NewContinuousVestingAccountRaw = types.NewContinuousVestingAccountRaw + NewContinuousVestingAccount = types.NewContinuousVestingAccount + NewDelayedVestingAccountRaw = types.NewDelayedVestingAccountRaw + NewDelayedVestingAccount = types.NewDelayedVestingAccount + RegisterCodec = types.RegisterCodec + RegisterBaseAccount = types.RegisterBaseAccount + NewFeeCollectionKeeper = types.NewFeeCollectionKeeper + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + ValidateGenesis = types.ValidateGenesis + AddressStoreKey = types.AddressStoreKey + NewParams = types.NewParams + ParamKeyTable = types.ParamKeyTable + DefaultParams = types.DefaultParams + NewQueryAccountParams = types.NewQueryAccountParams + NewStdTx = types.NewStdTx + CountSubKeys = types.CountSubKeys + NewStdFee = types.NewStdFee + StdSignBytes = types.StdSignBytes + DefaultTxDecoder = types.DefaultTxDecoder + DefaultTxEncoder = types.DefaultTxEncoder + + // variable aliases + ModuleCdc = types.ModuleCdc + AddressStoreKeyPrefix = types.AddressStoreKeyPrefix + GlobalAccountNumberKey = types.GlobalAccountNumberKey + KeyMaxMemoCharacters = types.KeyMaxMemoCharacters + KeyTxSigLimit = types.KeyTxSigLimit + KeyTxSizeCostPerByte = types.KeyTxSizeCostPerByte + KeySigVerifyCostED25519 = types.KeySigVerifyCostED25519 + KeySigVerifyCostSecp256k1 = types.KeySigVerifyCostSecp256k1 +) + +type ( + Account = types.Account + VestingAccount = types.VestingAccount + AccountDecoder = types.AccountDecoder + BaseAccount = types.BaseAccount + BaseVestingAccount = types.BaseVestingAccount + ContinuousVestingAccount = types.ContinuousVestingAccount + DelayedVestingAccount = types.DelayedVestingAccount + FeeCollectionKeeper = types.FeeCollectionKeeper + GenesisState = types.GenesisState + Params = types.Params + QueryAccountParams = types.QueryAccountParams + StdTx = types.StdTx + StdFee = types.StdFee + StdSignDoc = types.StdSignDoc + StdSignature = types.StdSignature +) diff --git a/x/auth/ante.go b/x/auth/ante.go index 87f5ccc92a04..71662ed15024 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -166,7 +166,7 @@ func ValidateSigCount(stdTx types.StdTx, params types.Params) sdk.Result { sigCount := 0 for i := 0; i < len(stdSigs); i++ { - sigCount += countSubKeys(stdSigs[i].PubKey) + sigCount += types.CountSubKeys(stdSigs[i].PubKey) if uint64(sigCount) > params.TxSigLimit { return sdk.ErrTooManySignatures( fmt.Sprintf("signatures: %d, limit: %d", sigCount, params.TxSigLimit), @@ -238,7 +238,7 @@ func consumeSimSigGas(gasmeter sdk.GasMeter, pubkey crypto.PubKey, sig types.Std simSig.Signature = simSecp256k1Sig[:] } - sigBz := moduleCdc.MustMarshalBinaryLengthPrefixed(simSig) + sigBz := types.ModuleCdc.MustMarshalBinaryLengthPrefixed(simSig) cost := sdk.Gas(len(sigBz) + 6) // If the pubkey is a multi-signature pubkey, then we estimate for the maximum @@ -328,7 +328,7 @@ func consumeMultisignatureVerificationGas(meter sdk.GasMeter, // // NOTE: We could use the CoinKeeper (in addition to the AccountKeeper, because // the CoinKeeper doesn't give us accounts), but it seems easier to do this. -func DeductFees(blockTime time.Time, acc types.Account, fee StdFee) (types.Account, sdk.Result) { +func DeductFees(blockTime time.Time, acc types.Account, fee types.StdFee) (types.Account, sdk.Result) { coins := acc.GetCoins() feeAmount := fee.Amount @@ -366,7 +366,7 @@ func DeductFees(blockTime time.Time, acc types.Account, fee StdFee) (types.Accou // // Contract: This should only be called during CheckTx as it cannot be part of // consensus. -func EnsureSufficientMempoolFees(ctx sdk.Context, stdFee StdFee) sdk.Result { +func EnsureSufficientMempoolFees(ctx sdk.Context, stdFee types.StdFee) sdk.Result { minGasPrices := ctx.MinGasPrices() if !minGasPrices.IsZero() { requiredFees := make(sdk.Coins, len(minGasPrices)) @@ -410,7 +410,7 @@ func GetSignBytes(chainID string, stdTx types.StdTx, acc types.Account, genesis accNum = acc.GetAccountNumber() } - return StdSignBytes( + return types.StdSignBytes( chainID, accNum, acc.GetSequence(), stdTx.Fee, stdTx.Msgs, stdTx.Memo, ) } diff --git a/x/auth/ante_test.go b/x/auth/ante_test.go index 380b8eb9141a..ae992408a7a8 100644 --- a/x/auth/ante_test.go +++ b/x/auth/ante_test.go @@ -13,6 +13,7 @@ import ( "github.com/tendermint/tendermint/crypto/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) // run the tx through the anteHandler and ensure its valid @@ -32,8 +33,8 @@ func checkInvalidTx(t *testing.T, anteHandler sdk.AnteHandler, ctx sdk.Context, require.Equal(t, sdk.CodespaceRoot, result.Codespace) if code == sdk.CodeOutOfGas { - stdTx, ok := tx.(StdTx) - require.True(t, ok, "tx must be in form auth.StdTx") + stdTx, ok := tx.(types.StdTx) + require.True(t, ok, "tx must be in form auth.types.StdTx") // GasWanted set correctly require.Equal(t, stdTx.Fee.Gas, result.GasWanted, "Gas wanted not set correctly") require.True(t, result.GasUsed > result.GasWanted, "GasUsed not greated than GasWanted") @@ -68,7 +69,7 @@ func TestAnteHandlerSigErrors(t *testing.T) { // tx.GetSigners returns addresses in correct order: addr1, addr2, addr3 expectedSigners := []sdk.AccAddress{addr1, addr2, addr3} - stdTx := tx.(StdTx) + stdTx := tx.(types.StdTx) require.Equal(t, expectedSigners, stdTx.GetSigners()) // Check no signatures fails @@ -512,7 +513,7 @@ func TestAnteHandlerSetPubKey(t *testing.T) { msg = newTestMsg(addr2) msgs = []sdk.Msg{msg} tx = newTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) - sigs := tx.(StdTx).GetSignatures() + sigs := tx.(types.StdTx).GetSignatures() sigs[0].PubKey = nil checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInvalidPubKey) @@ -666,7 +667,7 @@ func TestCountSubkeys(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(T *testing.T) { - require.Equal(t, tt.want, countSubKeys(tt.args.pub)) + require.Equal(t, tt.want, CountSubKeys(tt.args.pub)) }) } } diff --git a/x/auth/client/txbuilder/stdsignmsg.go b/x/auth/client/txbuilder/stdsignmsg.go index f5c78cc3f929..465b10be600e 100644 --- a/x/auth/client/txbuilder/stdsignmsg.go +++ b/x/auth/client/txbuilder/stdsignmsg.go @@ -2,22 +2,22 @@ package context import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) // StdSignMsg is a convenience structure for passing along // a Msg with the other requirements for a StdSignDoc before // it is signed. For use in the CLI. type StdSignMsg struct { - ChainID string `json:"chain_id"` - AccountNumber uint64 `json:"account_number"` - Sequence uint64 `json:"sequence"` - Fee auth.StdFee `json:"fee"` - Msgs []sdk.Msg `json:"msgs"` - Memo string `json:"memo"` + ChainID string `json:"chain_id"` + AccountNumber uint64 `json:"account_number"` + Sequence uint64 `json:"sequence"` + Fee types.StdFee `json:"fee"` + Msgs []sdk.Msg `json:"msgs"` + Memo string `json:"memo"` } // get message bytes func (msg StdSignMsg) Bytes() []byte { - return auth.StdSignBytes(msg.ChainID, msg.AccountNumber, msg.Sequence, msg.Fee, msg.Msgs, msg.Memo) + return types.StdSignBytes(msg.ChainID, msg.AccountNumber, msg.Sequence, msg.Fee, msg.Msgs, msg.Memo) } diff --git a/x/auth/genaccounts/module.go b/x/auth/genaccounts/module.go index b7c6564b267a..c1b92958e3cf 100644 --- a/x/auth/genaccounts/module.go +++ b/x/auth/genaccounts/module.go @@ -3,18 +3,21 @@ package genaccounts import ( "encoding/json" + "github.com/gorilla/mux" "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" ) var ( - _ sdk.AppModuleGenesis = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleGenesis = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) // module name @@ -47,8 +50,7 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { } // register rest routes -func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router, _ *codec.Codec) { -} +func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router, _ *codec.Codec) {} // get the root tx command of this module func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } @@ -79,9 +81,9 @@ type AppModule struct { } // NewAppModule creates a new AppModule object -func NewAppModule(accountKeeper AccountKeeper) sdk.AppModule { +func NewAppModule(accountKeeper AccountKeeper) module.AppModule { - return sdk.NewGenesisOnlyAppModule(AppModule{ + return module.NewGenesisOnlyAppModule(AppModule{ AppModuleBasic: AppModuleBasic{}, accountKeeper: accountKeeper, }) diff --git a/x/auth/genesis.go b/x/auth/genesis.go index 90e2a3a32bf6..5ba1dda098c6 100644 --- a/x/auth/genesis.go +++ b/x/auth/genesis.go @@ -2,18 +2,19 @@ package auth import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) // InitGenesis - Init store state from genesis data -func InitGenesis(ctx sdk.Context, ak AccountKeeper, fck FeeCollectionKeeper, data GenesisState) { +func InitGenesis(ctx sdk.Context, ak AccountKeeper, fck types.FeeCollectionKeeper, data types.GenesisState) { ak.SetParams(ctx, data.Params) - fck.setCollectedFees(ctx, data.CollectedFees) + fck.AddCollectedFees(ctx, data.CollectedFees) } // ExportGenesis returns a GenesisState for a given context and keeper -func ExportGenesis(ctx sdk.Context, ak AccountKeeper, fck FeeCollectionKeeper) GenesisState { +func ExportGenesis(ctx sdk.Context, ak AccountKeeper, fck types.FeeCollectionKeeper) types.GenesisState { collectedFees := fck.GetCollectedFees(ctx) params := ak.GetParams(ctx) - return NewGenesisState(collectedFees, params) + return types.NewGenesisState(collectedFees, params) } diff --git a/x/auth/keeper.go b/x/auth/keeper.go index 1cfe3fe1027c..3afe3f7eef09 100644 --- a/x/auth/keeper.go +++ b/x/auth/keeper.go @@ -37,7 +37,7 @@ func NewAccountKeeper( key: key, proto: proto, cdc: cdc, - paramSubspace: paramstore.WithKeyTable(ParamKeyTable()), + paramSubspace: paramstore.WithKeyTable(types.ParamKeyTable()), } } @@ -68,7 +68,7 @@ func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc types.Account) types.Acc // GetAccount implements sdk.AccountKeeper. func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.Account { store := ctx.KVStore(ak.key) - bz := store.Get(AddressStoreKey(addr)) + bz := store.Get(types.AddressStoreKey(addr)) if bz == nil { return nil } @@ -95,7 +95,7 @@ func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc types.Account) { if err != nil { panic(err) } - store.Set(AddressStoreKey(addr), bz) + store.Set(types.AddressStoreKey(addr), bz) } // RemoveAccount removes an account for the account mapper store. @@ -103,13 +103,13 @@ func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc types.Account) { func (ak AccountKeeper) RemoveAccount(ctx sdk.Context, acc types.Account) { addr := acc.GetAddress() store := ctx.KVStore(ak.key) - store.Delete(AddressStoreKey(addr)) + store.Delete(types.AddressStoreKey(addr)) } // IterateAccounts implements sdk.AccountKeeper. func (ak AccountKeeper) IterateAccounts(ctx sdk.Context, process func(types.Account) (stop bool)) { store := ctx.KVStore(ak.key) - iter := sdk.KVStorePrefixIterator(store, AddressStoreKeyPrefix) + iter := sdk.KVStorePrefixIterator(store, types.AddressStoreKeyPrefix) defer iter.Close() for { if !iter.Valid() { @@ -160,7 +160,7 @@ func (ak AccountKeeper) setSequence(ctx sdk.Context, addr sdk.AccAddress, newSeq func (ak AccountKeeper) GetNextAccountNumber(ctx sdk.Context) uint64 { var accNumber uint64 store := ctx.KVStore(ak.key) - bz := store.Get(globalAccountNumberKey) + bz := store.Get(types.GlobalAccountNumberKey) if bz == nil { accNumber = 0 } else { @@ -171,21 +171,21 @@ func (ak AccountKeeper) GetNextAccountNumber(ctx sdk.Context) uint64 { } bz = ak.cdc.MustMarshalBinaryLengthPrefixed(accNumber + 1) - store.Set(globalAccountNumberKey, bz) + store.Set(types.GlobalAccountNumberKey, bz) return accNumber } // ----------------------------------------------------------------------------- -// Params +// types.Params // SetParams sets the auth module's parameters. -func (ak AccountKeeper) SetParams(ctx sdk.Context, params Params) { +func (ak AccountKeeper) SetParams(ctx sdk.Context, params types.Params) { ak.paramSubspace.SetParamSet(ctx, ¶ms) } // GetParams gets the auth module's parameters. -func (ak AccountKeeper) GetParams(ctx sdk.Context) (params Params) { +func (ak AccountKeeper) GetParams(ctx sdk.Context) (params types.Params) { ak.paramSubspace.GetParamSet(ctx, ¶ms) return } diff --git a/x/auth/module.go b/x/auth/module.go index 18f4ba25ff67..6c47c9367681 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -3,19 +3,21 @@ package auth import ( "encoding/json" + "github.com/gorilla/mux" "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth/client/rest" "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) // app module basics object @@ -28,28 +30,28 @@ func (AppModuleBasic) Name() string { // register module codec func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) + types.RegisterCodec(cdc) } // default genesis state func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return moduleCdc.MustMarshalJSON(DefaultGenesisState()) + return types.ModuleCdc.MustMarshalJSON(types.DefaultGenesisState()) } // module validate genesis func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) + var data types.GenesisState + err := types.ModuleCdc.UnmarshalJSON(bz, &data) if err != nil { return err } - return ValidateGenesis(data) + return types.ValidateGenesis(data) } // XXX // register rest routes func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { - rest.RegisterRoutes(ctx, rtr, cdc, StoreKey) + rest.RegisterRoutes(ctx, rtr, cdc, types.StoreKey) } // TODO @@ -65,12 +67,12 @@ func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } type AppModule struct { AppModuleBasic accountKeeper AccountKeeper - feeCollectionKeeper FeeCollectionKeeper + feeCollectionKeeper types.FeeCollectionKeeper } // NewAppModule creates a new AppModule object func NewAppModule(accountKeeper AccountKeeper, - feeCollectionKeeper FeeCollectionKeeper) AppModule { + feeCollectionKeeper types.FeeCollectionKeeper) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{}, accountKeeper: accountKeeper, @@ -80,7 +82,7 @@ func NewAppModule(accountKeeper AccountKeeper, // module name func (AppModule) Name() string { - return ModuleName + return types.ModuleName } // register invariants @@ -94,7 +96,7 @@ func (AppModule) NewHandler() sdk.Handler { return nil } // module querier route name func (AppModule) QuerierRoute() string { - return QuerierRoute + return types.QuerierRoute } // module querier @@ -104,8 +106,8 @@ func (am AppModule) NewQuerierHandler() sdk.Querier { // module init-genesis func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { - var genesisState GenesisState - moduleCdc.MustUnmarshalJSON(data, &genesisState) + var genesisState types.GenesisState + types.ModuleCdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.accountKeeper, am.feeCollectionKeeper, genesisState) return []abci.ValidatorUpdate{} } @@ -113,7 +115,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va // module export genesis func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.accountKeeper, am.feeCollectionKeeper) - return moduleCdc.MustMarshalJSON(gs) + return types.ModuleCdc.MustMarshalJSON(gs) } // module begin-block diff --git a/x/auth/querier.go b/x/auth/querier.go index 5e8d6a245fea..ea2fd5c46cd4 100644 --- a/x/auth/querier.go +++ b/x/auth/querier.go @@ -14,7 +14,7 @@ import ( func NewQuerier(keeper AccountKeeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { switch path[0] { - case QueryAccount: + case types.QueryAccount: return queryAccount(ctx, req, keeper) default: return nil, sdk.ErrUnknownRequest("unknown auth query endpoint") diff --git a/x/auth/test_utils.go b/x/auth/test_utils.go index 294ae075b1cc..557cc00ecb85 100644 --- a/x/auth/test_utils.go +++ b/x/auth/test_utils.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/params/subspace" ) @@ -16,14 +17,14 @@ type testInput struct { cdc *codec.Codec ctx sdk.Context ak AccountKeeper - fck FeeCollectionKeeper + fck types.FeeCollectionKeeper } func setupTestInput() testInput { db := dbm.NewMemDB() cdc := codec.New() - RegisterBaseAccount(cdc) + types.RegisterBaseAccount(cdc) authCapKey := sdk.NewKVStoreKey("authCapKey") fckCapKey := sdk.NewKVStoreKey("fckCapKey") @@ -37,12 +38,12 @@ func setupTestInput() testInput { ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) ms.LoadLatestVersion() - ps := subspace.NewSubspace(cdc, keyParams, tkeyParams, DefaultParamspace) - ak := NewAccountKeeper(cdc, authCapKey, ps, ProtoBaseAccount) - fck := NewFeeCollectionKeeper(cdc, fckCapKey) + ps := subspace.NewSubspace(cdc, keyParams, tkeyParams, types.DefaultParamspace) + ak := NewAccountKeeper(cdc, authCapKey, ps, types.ProtoBaseAccount) + fck := types.NewFeeCollectionKeeper(cdc, fckCapKey) ctx := sdk.NewContext(ms, abci.Header{ChainID: "test-chain-id"}, false, log.NewNopLogger()) - ak.SetParams(ctx, DefaultParams()) + ak.SetParams(ctx, types.DefaultParams()) return testInput{cdc: cdc, ctx: ctx, ak: ak, fck: fck} } diff --git a/x/auth/types/codec.go b/x/auth/types/codec.go index aa67699d25cb..6cb924687aed 100644 --- a/x/auth/types/codec.go +++ b/x/auth/types/codec.go @@ -26,9 +26,11 @@ func RegisterBaseAccount(cdc *codec.Codec) { codec.RegisterCrypto(cdc) } -var moduleCdc = codec.New() +// module wide codec +var ModuleCdc = codec.New() func init() { - RegisterCodec(moduleCdc) - codec.RegisterCrypto(moduleCdc) + RegisterCodec(ModuleCdc) + codec.RegisterCrypto(ModuleCdc) + ModuleCdc.Seal() } diff --git a/x/auth/types/keys.go b/x/auth/types/keys.go index a8a73c7650d6..30cf80490bf7 100644 --- a/x/auth/types/keys.go +++ b/x/auth/types/keys.go @@ -20,7 +20,8 @@ var ( // AddressStoreKeyPrefix prefix for account-by-address store AddressStoreKeyPrefix = []byte{0x01} - globalAccountNumberKey = []byte("globalAccountNumber") + // param key for global account number + GlobalAccountNumberKey = []byte("globalAccountNumber") ) // AddressStoreKey turn an address to key used to get it from the account store diff --git a/x/auth/types/params.go b/x/auth/types/params.go index 8cb09a5b2c76..ed0f4881140c 100644 --- a/x/auth/types/params.go +++ b/x/auth/types/params.go @@ -73,8 +73,8 @@ func (p *Params) ParamSetPairs() subspace.ParamSetPairs { // Equal returns a boolean determining if two Params types are identical. func (p Params) Equal(p2 Params) bool { - bz1 := moduleCdc.MustMarshalBinaryLengthPrefixed(&p) - bz2 := moduleCdc.MustMarshalBinaryLengthPrefixed(&p2) + bz1 := ModuleCdc.MustMarshalBinaryLengthPrefixed(&p) + bz2 := ModuleCdc.MustMarshalBinaryLengthPrefixed(&p2) return bytes.Equal(bz1, bz2) } diff --git a/x/auth/types/stdtx.go b/x/auth/types/stdtx.go index 1aac644391ad..18cdfaf0a0f2 100644 --- a/x/auth/types/stdtx.go +++ b/x/auth/types/stdtx.go @@ -59,8 +59,8 @@ func (tx StdTx) ValidateBasic() sdk.Error { return nil } -// countSubKeys counts the total number of keys for a multi-sig public key. -func countSubKeys(pub crypto.PubKey) int { +// CountSubKeys counts the total number of keys for a multi-sig public key. +func CountSubKeys(pub crypto.PubKey) int { v, ok := pub.(multisig.PubKeyMultisigThreshold) if !ok { return 1 @@ -68,7 +68,7 @@ func countSubKeys(pub crypto.PubKey) int { numKeys := 0 for _, subkey := range v.PubKeys { - numKeys += countSubKeys(subkey) + numKeys += CountSubKeys(subkey) } return numKeys @@ -133,7 +133,7 @@ func (fee StdFee) Bytes() []byte { if len(fee.Amount) == 0 { fee.Amount = sdk.NewCoins() } - bz, err := moduleCdc.MarshalJSON(fee) // TODO + bz, err := ModuleCdc.MarshalJSON(fee) // TODO if err != nil { panic(err) } @@ -171,7 +171,7 @@ func StdSignBytes(chainID string, accnum uint64, sequence uint64, fee StdFee, ms for _, msg := range msgs { msgsBytes = append(msgsBytes, json.RawMessage(msg.GetSignBytes())) } - bz, err := moduleCdc.MarshalJSON(StdSignDoc{ + bz, err := ModuleCdc.MarshalJSON(StdSignDoc{ AccountNumber: accnum, ChainID: chainID, Fee: json.RawMessage(fee.Bytes()), diff --git a/x/bank/alias.go b/x/bank/alias.go new file mode 100644 index 000000000000..595c3ab61425 --- /dev/null +++ b/x/bank/alias.go @@ -0,0 +1,45 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/bank/types +package bank + +import ( + "github.com/cosmos/cosmos-sdk/x/bank/types" +) + +const ( + DefaultCodespace = types.DefaultCodespace + CodeSendDisabled = types.CodeSendDisabled + CodeInvalidInputsOutputs = types.CodeInvalidInputsOutputs + ModuleName = types.ModuleName + RouterKey = types.RouterKey + DefaultParamspace = types.DefaultParamspace + DefaultSendEnabled = types.DefaultSendEnabled +) + +var ( + // functions aliases + RegisterCodec = types.RegisterCodec + ErrNoInputs = types.ErrNoInputs + ErrNoOutputs = types.ErrNoOutputs + ErrInputOutputMismatch = types.ErrInputOutputMismatch + ErrSendDisabled = types.ErrSendDisabled + NewMsgSend = types.NewMsgSend + NewMsgMultiSend = types.NewMsgMultiSend + NewInput = types.NewInput + NewOutput = types.NewOutput + ValidateInputsOutputs = types.ValidateInputsOutputs + ParamKeyTable = types.ParamKeyTable + + // variable aliases + ModuleCdc = types.ModuleCdc + ParamStoreKeySendEnabled = types.ParamStoreKeySendEnabled +) + +type ( + MsgSend = types.MsgSend + MsgMultiSend = types.MsgMultiSend + Input = types.Input + Output = types.Output +) diff --git a/x/bank/app_test.go b/x/bank/app_test.go index 951a1746932b..651021eadb9d 100644 --- a/x/bank/app_test.go +++ b/x/bank/app_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/mock" "github.com/stretchr/testify/require" @@ -45,43 +46,43 @@ var ( manyCoins = sdk.Coins{sdk.NewInt64Coin("foocoin", 1), sdk.NewInt64Coin("barcoin", 1)} freeFee = auth.NewStdFee(100000, sdk.Coins{sdk.NewInt64Coin("foocoin", 0)}) - sendMsg1 = NewMsgSend(addr1, addr2, coins) + sendMsg1 = types.NewMsgSend(addr1, addr2, coins) - multiSendMsg1 = MsgMultiSend{ - Inputs: []Input{NewInput(addr1, coins)}, - Outputs: []Output{NewOutput(addr2, coins)}, + multiSendMsg1 = types.MsgMultiSend{ + Inputs: []types.Input{types.NewInput(addr1, coins)}, + Outputs: []types.Output{types.NewOutput(addr2, coins)}, } - multiSendMsg2 = MsgMultiSend{ - Inputs: []Input{NewInput(addr1, coins)}, - Outputs: []Output{ - NewOutput(addr2, halfCoins), - NewOutput(addr3, halfCoins), + multiSendMsg2 = types.MsgMultiSend{ + Inputs: []types.Input{types.NewInput(addr1, coins)}, + Outputs: []types.Output{ + types.NewOutput(addr2, halfCoins), + types.NewOutput(addr3, halfCoins), }, } - multiSendMsg3 = MsgMultiSend{ - Inputs: []Input{ - NewInput(addr1, coins), - NewInput(addr4, coins), + multiSendMsg3 = types.MsgMultiSend{ + Inputs: []types.Input{ + types.NewInput(addr1, coins), + types.NewInput(addr4, coins), }, - Outputs: []Output{ - NewOutput(addr2, coins), - NewOutput(addr3, coins), + Outputs: []types.Output{ + types.NewOutput(addr2, coins), + types.NewOutput(addr3, coins), }, } - multiSendMsg4 = MsgMultiSend{ - Inputs: []Input{ - NewInput(addr2, coins), + multiSendMsg4 = types.MsgMultiSend{ + Inputs: []types.Input{ + types.NewInput(addr2, coins), }, - Outputs: []Output{ - NewOutput(addr1, coins), + Outputs: []types.Output{ + types.NewOutput(addr1, coins), }, } - multiSendMsg5 = MsgMultiSend{ - Inputs: []Input{ - NewInput(addr1, manyCoins), + multiSendMsg5 = types.MsgMultiSend{ + Inputs: []types.Input{ + types.NewInput(addr1, manyCoins), }, - Outputs: []Output{ - NewOutput(addr2, manyCoins), + Outputs: []types.Output{ + types.NewOutput(addr2, manyCoins), }, } ) @@ -122,7 +123,7 @@ func TestSendNotEnoughBalance(t *testing.T) { origAccNum := res1.GetAccountNumber() origSeq := res1.GetSequence() - sendMsg := NewMsgSend(addr1, addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 100)}) + sendMsg := types.NewMsgSend(addr1, addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 100)}) header := abci.Header{Height: mapp.LastBlockHeight() + 1} mock.SignCheckDeliver(t, mapp.Cdc, mapp.BaseApp, header, []sdk.Msg{sendMsg}, []uint64{origAccNum}, []uint64{origSeq}, false, false, priv1) diff --git a/x/bank/bench_test.go b/x/bank/bench_test.go index dbc7eebe5589..f4e5042805a2 100644 --- a/x/bank/bench_test.go +++ b/x/bank/bench_test.go @@ -19,10 +19,10 @@ func getBenchmarkMockApp() (*mock.App, error) { types.RegisterCodec(mapp.Cdc) bankKeeper := NewBaseKeeper( mapp.AccountKeeper, - mapp.ParamsKeeper.Subspace(DefaultParamspace), - DefaultCodespace, + mapp.ParamsKeeper.Subspace(types.DefaultParamspace), + types.DefaultCodespace, ) - mapp.Router().AddRoute(RouterKey, NewHandler(bankKeeper)) + mapp.Router().AddRoute(types.RouterKey, NewHandler(bankKeeper)) mapp.SetInitChainer(getInitChainer(mapp, bankKeeper)) err := mapp.CompleteSetup() diff --git a/x/bank/client/rest/sendtx.go b/x/bank/client/rest/sendtx.go index 801bd58e6cad..57e0ec32e328 100644 --- a/x/bank/client/rest/sendtx.go +++ b/x/bank/client/rest/sendtx.go @@ -8,7 +8,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" clientrest "github.com/cosmos/cosmos-sdk/client/rest" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" @@ -16,8 +15,8 @@ import ( ) // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, kb keys.Keybase) { - r.HandleFunc("/bank/accounts/{address}/transfers", SendRequestHandlerFn(cdc, kb, cliCtx)).Methods("POST") +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { + r.HandleFunc("/bank/accounts/{address}/transfers", SendRequestHandlerFn(cdc, cliCtx)).Methods("POST") } // SendReq defines the properties of a send request's body. @@ -33,7 +32,7 @@ func init() { } // SendRequestHandlerFn - http request handler to send coins to a address. -func SendRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { +func SendRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) bech32Addr := vars["address"] diff --git a/x/bank/handler.go b/x/bank/handler.go index 3afff836ae1f..040e440e3da7 100644 --- a/x/bank/handler.go +++ b/x/bank/handler.go @@ -5,16 +5,17 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/bank/tags" + "github.com/cosmos/cosmos-sdk/x/bank/types" ) // NewHandler returns a handler for "bank" type messages. func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { switch msg := msg.(type) { - case MsgSend: + case types.MsgSend: return handleMsgSend(ctx, k, msg) - case MsgMultiSend: + case types.MsgMultiSend: return handleMsgMultiSend(ctx, k, msg) default: @@ -25,9 +26,9 @@ func NewHandler(k Keeper) sdk.Handler { } // Handle MsgSend. -func handleMsgSend(ctx sdk.Context, k Keeper, msg MsgSend) sdk.Result { +func handleMsgSend(ctx sdk.Context, k Keeper, msg types.MsgSend) sdk.Result { if !k.GetSendEnabled(ctx) { - return ErrSendDisabled(k.Codespace()).Result() + return types.ErrSendDisabled(k.Codespace()).Result() } err := k.SendCoins(ctx, msg.FromAddress, msg.ToAddress, msg.Amount) if err != nil { @@ -46,10 +47,10 @@ func handleMsgSend(ctx sdk.Context, k Keeper, msg MsgSend) sdk.Result { } // Handle MsgMultiSend. -func handleMsgMultiSend(ctx sdk.Context, k Keeper, msg MsgMultiSend) sdk.Result { +func handleMsgMultiSend(ctx sdk.Context, k Keeper, msg types.MsgMultiSend) sdk.Result { // NOTE: totalIn == totalOut should already have been checked if !k.GetSendEnabled(ctx) { - return ErrSendDisabled(k.Codespace()).Result() + return types.ErrSendDisabled(k.Codespace()).Result() } resTags, err := k.InputOutputCoins(ctx, msg.Inputs, msg.Outputs) if err != nil { diff --git a/x/bank/invariants.go b/x/bank/invariants.go index a0e30db98372..bbdc345e59f3 100644 --- a/x/bank/invariants.go +++ b/x/bank/invariants.go @@ -6,11 +6,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank/types" ) // register bank invariants func RegisterInvariants(ir sdk.InvariantRouter, ak auth.AccountKeeper) { - ir.RegisterRoute(RouterKey, "nonnegative-outstanding", + ir.RegisterRoute(types.RouterKey, "nonnegative-outstanding", NonnegativeBalanceInvariant(ak)) } diff --git a/x/bank/keeper.go b/x/bank/keeper.go index 05a5b3d6e31d..730c96e070e7 100644 --- a/x/bank/keeper.go +++ b/x/bank/keeper.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank/tags" + "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/params" ) @@ -20,7 +21,7 @@ type Keeper interface { SetCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) sdk.Error SubtractCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Error) AddCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Error) - InputOutputCoins(ctx sdk.Context, inputs []Input, outputs []Output) (sdk.Tags, sdk.Error) + InputOutputCoins(ctx sdk.Context, inputs []types.Input, outputs []types.Output) (sdk.Tags, sdk.Error) DelegateCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Tags, sdk.Error) UndelegateCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Tags, sdk.Error) @@ -39,7 +40,7 @@ func NewBaseKeeper(ak auth.AccountKeeper, paramSpace params.Subspace, codespace sdk.CodespaceType) BaseKeeper { - ps := paramSpace.WithKeyTable(ParamKeyTable()) + ps := paramSpace.WithKeyTable(types.ParamKeyTable()) return BaseKeeper{ BaseSendKeeper: NewBaseSendKeeper(ak, ps, codespace), ak: ak, @@ -82,7 +83,7 @@ func (keeper BaseKeeper) AddCoins( // InputOutputCoins handles a list of inputs and outputs func (keeper BaseKeeper) InputOutputCoins( - ctx sdk.Context, inputs []Input, outputs []Output, + ctx sdk.Context, inputs []types.Input, outputs []types.Output, ) (sdk.Tags, sdk.Error) { return inputOutputCoins(ctx, keeper.ak, inputs, outputs) @@ -163,13 +164,13 @@ func (keeper BaseSendKeeper) SendCoins( // nolint: errcheck func (keeper BaseSendKeeper) GetSendEnabled(ctx sdk.Context) bool { var enabled bool - keeper.paramSpace.Get(ctx, ParamStoreKeySendEnabled, &enabled) + keeper.paramSpace.Get(ctx, types.ParamStoreKeySendEnabled, &enabled) return enabled } // SetSendEnabled sets the send enabled func (keeper BaseSendKeeper) SetSendEnabled(ctx sdk.Context, enabled bool) { - keeper.paramSpace.Set(ctx, ParamStoreKeySendEnabled, &enabled) + keeper.paramSpace.Set(ctx, types.ParamStoreKeySendEnabled, &enabled) } var _ ViewKeeper = (*BaseViewKeeper)(nil) @@ -323,10 +324,10 @@ func sendCoins(ctx sdk.Context, am auth.AccountKeeper, fromAddr sdk.AccAddress, // InputOutputCoins handles a list of inputs and outputs // NOTE: Make sure to revert state changes from tx on error -func inputOutputCoins(ctx sdk.Context, am auth.AccountKeeper, inputs []Input, outputs []Output) (sdk.Tags, sdk.Error) { +func inputOutputCoins(ctx sdk.Context, am auth.AccountKeeper, inputs []types.Input, outputs []types.Output) (sdk.Tags, sdk.Error) { // Safety check ensuring that when sending coins the keeper must maintain the // Check supply invariant and validity of Coins. - if err := ValidateInputsOutputs(inputs, outputs); err != nil { + if err := types.ValidateInputsOutputs(inputs, outputs); err != nil { return nil, err } diff --git a/x/bank/keeper_test.go b/x/bank/keeper_test.go index 7328b7af6e43..c658d5e46e9c 100644 --- a/x/bank/keeper_test.go +++ b/x/bank/keeper_test.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/params" ) @@ -56,7 +57,7 @@ func setupTestInput() testInput { func TestKeeper(t *testing.T) { input := setupTestInput() ctx := input.ctx - bankKeeper := NewBaseKeeper(input.ak, input.pk.Subspace(DefaultParamspace), DefaultCodespace) + bankKeeper := NewBaseKeeper(input.ak, input.pk.Subspace(types.DefaultParamspace), types.DefaultCodespace) bankKeeper.SetSendEnabled(ctx, true) addr := sdk.AccAddress([]byte("addr1")) @@ -112,18 +113,18 @@ func TestKeeper(t *testing.T) { require.True(t, bankKeeper.GetCoins(ctx, addr2).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("barcoin", 10), sdk.NewInt64Coin("foocoin", 10)))) // Test InputOutputCoins - input1 := NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 2))) - output1 := NewOutput(addr, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 2))) - bankKeeper.InputOutputCoins(ctx, []Input{input1}, []Output{output1}) + input1 := types.NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 2))) + output1 := types.NewOutput(addr, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 2))) + bankKeeper.InputOutputCoins(ctx, []types.Input{input1}, []types.Output{output1}) require.True(t, bankKeeper.GetCoins(ctx, addr).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("barcoin", 20), sdk.NewInt64Coin("foocoin", 7)))) require.True(t, bankKeeper.GetCoins(ctx, addr2).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("barcoin", 10), sdk.NewInt64Coin("foocoin", 8)))) - inputs := []Input{ + inputs := []types.Input{ NewInput(addr, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 3))), - NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin("barcoin", 3), sdk.NewInt64Coin("foocoin", 2))), + types.NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin("barcoin", 3), sdk.NewInt64Coin("foocoin", 2))), } - outputs := []Output{ + outputs := []types.Output{ NewOutput(addr, sdk.NewCoins(sdk.NewInt64Coin("barcoin", 1))), NewOutput(addr3, sdk.NewCoins(sdk.NewInt64Coin("barcoin", 2), sdk.NewInt64Coin("foocoin", 5))), } @@ -136,8 +137,8 @@ func TestKeeper(t *testing.T) { func TestSendKeeper(t *testing.T) { input := setupTestInput() ctx := input.ctx - paramSpace := input.pk.Subspace(DefaultParamspace) - bankKeeper := NewBaseKeeper(input.ak, paramSpace, DefaultCodespace) + paramSpace := input.pk.Subspace(types.DefaultParamspace) + bankKeeper := NewBaseKeeper(input.ak, paramSpace, types.DefaultCodespace) sendKeeper := NewBaseSendKeeper(input.ak, paramSpace, DefaultCodespace) bankKeeper.SetSendEnabled(ctx, true) diff --git a/x/bank/module.go b/x/bank/module.go index 84c15cb20d4a..2ccaae5041c4 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -3,26 +3,29 @@ package bank import ( "encoding/json" + "github.com/gorilla/mux" "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank/client/rest" "github.com/cosmos/cosmos-sdk/x/bank/types" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) // app module basics object type AppModuleBasic struct{} -var _ sdk.AppModuleBasic = AppModuleBasic{} +var _ module.AppModuleBasic = AppModuleBasic{} // module name func (AppModuleBasic) Name() string { @@ -36,13 +39,13 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { // default genesis state func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return moduleCdc.MustMarshalJSON(DefaultGenesisState()) + return types.ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } // module validate genesis func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) + err := types.ModuleCdc.UnmarshalJSON(bz, &data) if err != nil { return err } @@ -50,8 +53,8 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { } // register rest routes -func RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { - rest.RegisterRoutes(ctx, rtr, cdc, StoreKey) +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + rest.RegisterRoutes(ctx, rtr, cdc) } // TODO @@ -81,7 +84,7 @@ func NewAppModule(keeper Keeper, accountKeeper auth.AccountKeeper) AppModule { // module name func (AppModule) Name() string { - return ModuleName + return types.ModuleName } // register invariants @@ -91,7 +94,7 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRouter) { // module message route name func (AppModule) Route() string { - return RouterKey + return types.RouterKey } // module handler @@ -108,7 +111,7 @@ func (AppModule) NewQuerierHandler() sdk.Querier { return nil } // module init-genesis func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState - moduleCdc.MustUnmarshalJSON(data, &genesisState) + types.ModuleCdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.keeper, genesisState) return []abci.ValidatorUpdate{} } @@ -116,7 +119,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va // module export genesis func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) - return moduleCdc.MustMarshalJSON(gs) + return types.ModuleCdc.MustMarshalJSON(gs) } // module begin-block diff --git a/x/bank/types/codec.go b/x/bank/types/codec.go index 2d169d08fe66..2018e685f43d 100644 --- a/x/bank/types/codec.go +++ b/x/bank/types/codec.go @@ -10,8 +10,10 @@ func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(MsgMultiSend{}, "cosmos-sdk/MsgMultiSend", nil) } -var moduleCdc = codec.New() +// module codec +var ModuleCdc = codec.New() func init() { - RegisterCodec(moduleCdc) + RegisterCodec(ModuleCdc) + ModuleCdc.Seal() } diff --git a/x/bank/types/key.go b/x/bank/types/key.go index 57604b2ab8d4..b894b78ed913 100644 --- a/x/bank/types/key.go +++ b/x/bank/types/key.go @@ -1,5 +1,6 @@ package types const ( + // module name ModuleName = "bank" ) diff --git a/x/bank/types/msgs.go b/x/bank/types/msgs.go index 805873fb1443..0f3d8e1fef84 100644 --- a/x/bank/types/msgs.go +++ b/x/bank/types/msgs.go @@ -46,7 +46,7 @@ func (msg MsgSend) ValidateBasic() sdk.Error { // GetSignBytes Implements Msg. func (msg MsgSend) GetSignBytes() []byte { - return sdk.MustSortJSON(moduleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) } // GetSigners Implements Msg. @@ -89,7 +89,7 @@ func (msg MsgMultiSend) ValidateBasic() sdk.Error { // GetSignBytes Implements Msg. func (msg MsgMultiSend) GetSignBytes() []byte { - return sdk.MustSortJSON(moduleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) } // GetSigners Implements Msg. diff --git a/x/bank/params.go b/x/bank/types/params.go similarity index 97% rename from x/bank/params.go rename to x/bank/types/params.go index 01602e52cceb..d232a975f0cb 100644 --- a/x/bank/params.go +++ b/x/bank/types/params.go @@ -1,4 +1,4 @@ -package bank +package types import ( "github.com/cosmos/cosmos-sdk/x/params" diff --git a/x/crisis/alias.go b/x/crisis/alias.go new file mode 100644 index 000000000000..be9fd5c54a1d --- /dev/null +++ b/x/crisis/alias.go @@ -0,0 +1,38 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/crisis/types +package crisis + +import ( + "github.com/cosmos/cosmos-sdk/x/crisis/types" +) + +const ( + DefaultCodespace = types.DefaultCodespace + CodeInvalidInput = types.CodeInvalidInput + ModuleName = types.ModuleName + DefaultParamspace = types.DefaultParamspace +) + +var ( + // functions aliases + RegisterCodec = types.RegisterCodec + ErrNilSender = types.ErrNilSender + ErrUnknownInvariant = types.ErrUnknownInvariant + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + NewMsgVerifyInvariant = types.NewMsgVerifyInvariant + ParamKeyTable = types.ParamKeyTable + NewInvarRoute = types.NewInvarRoute + + // variable aliases + ModuleCdc = types.ModuleCdc + ParamStoreKeyConstantFee = types.ParamStoreKeyConstantFee +) + +type ( + GenesisState = types.GenesisState + MsgVerifyInvariant = types.MsgVerifyInvariant + InvarRoute = types.InvarRoute +) diff --git a/x/crisis/client/cli/tx.go b/x/crisis/client/cli/tx.go index 9c3b04dc7d85..b7d013060a7a 100644 --- a/x/crisis/client/cli/tx.go +++ b/x/crisis/client/cli/tx.go @@ -34,7 +34,7 @@ func GetCmdInvariantBroken(cdc *codec.Codec) *cobra.Command { } // GetTxCmd returns the transaction commands for this module -func GetTxCmd(cdc *amino.Codec) *cobra.Command { +func GetTxCmd(cdc *codec.Codec) *cobra.Command { txCmd := &cobra.Command{ Use: types.ModuleName, Short: "crisis transactions subcommands", diff --git a/x/crisis/genesis.go b/x/crisis/genesis.go index 29c8c9cb7291..58d2689e323f 100644 --- a/x/crisis/genesis.go +++ b/x/crisis/genesis.go @@ -13,5 +13,5 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) { // ExportGenesis returns a GenesisState for a given context and keeper. func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { constantFee := keeper.GetConstantFee(ctx) - return NewGenesisState(constantFee) + return types.NewGenesisState(constantFee) } diff --git a/x/crisis/handler.go b/x/crisis/handler.go index 475ca8535c99..012b82edde99 100644 --- a/x/crisis/handler.go +++ b/x/crisis/handler.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/crisis/tags" + "github.com/cosmos/cosmos-sdk/x/crisis/types" ) // RouterKey @@ -13,7 +14,7 @@ const RouterKey = ModuleName func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { switch msg := msg.(type) { - case MsgVerifyInvariant: + case types.MsgVerifyInvariant: return handleMsgVerifyInvariant(ctx, msg, k) default: @@ -23,7 +24,7 @@ func NewHandler(k Keeper) sdk.Handler { } } -func handleMsgVerifyInvariant(ctx sdk.Context, msg MsgVerifyInvariant, k Keeper) sdk.Result { +func handleMsgVerifyInvariant(ctx sdk.Context, msg types.MsgVerifyInvariant, k Keeper) sdk.Result { // remove the constant fee constantFee := sdk.NewCoins(k.GetConstantFee(ctx)) @@ -47,7 +48,7 @@ func handleMsgVerifyInvariant(ctx sdk.Context, msg MsgVerifyInvariant, k Keeper) } } if !found { - return ErrUnknownInvariant(DefaultCodespace).Result() + return types.ErrUnknownInvariant(types.DefaultCodespace).Result() } if invarianceErr != nil { diff --git a/x/crisis/keeper.go b/x/crisis/keeper.go index 51a5abf6ec2f..7bb9d4aaa035 100644 --- a/x/crisis/keeper.go +++ b/x/crisis/keeper.go @@ -7,12 +7,13 @@ import ( "github.com/tendermint/tendermint/libs/log" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/crisis/types" "github.com/cosmos/cosmos-sdk/x/params" ) // Keeper - crisis keeper type Keeper struct { - routes []InvarRoute + routes []types.InvarRoute paramSpace params.Subspace invCheckPeriod uint @@ -27,8 +28,8 @@ func NewKeeper(paramSpace params.Subspace, invCheckPeriod uint, feeCollectionKeeper FeeCollectionKeeper) Keeper { return Keeper{ - routes: []InvarRoute{}, - paramSpace: paramSpace.WithKeyTable(ParamKeyTable()), + routes: []types.InvarRoute{}, + paramSpace: paramSpace.WithKeyTable(types.ParamKeyTable()), invCheckPeriod: invCheckPeriod, distrKeeper: distrKeeper, bankKeeper: bankKeeper, @@ -38,12 +39,12 @@ func NewKeeper(paramSpace params.Subspace, invCheckPeriod uint, // register routes for the func (k *Keeper) RegisterRoute(moduleName, route string, invar sdk.Invariant) { - invarRoute := NewInvarRoute(moduleName, route, invar) + invarRoute := types.NewInvarRoute(moduleName, route, invar) k.routes = append(k.routes, invarRoute) } // Routes - return the keeper's invariant routes -func (k Keeper) Routes() []InvarRoute { +func (k Keeper) Routes() []types.InvarRoute { return k.routes } diff --git a/x/crisis/module.go b/x/crisis/module.go index 24eed5a08165..19e94554347f 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -3,29 +3,28 @@ package crisis import ( "encoding/json" + "github.com/gorilla/mux" "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/crisis/client/cli" - "github.com/cosmos/cosmos-sdk/x/crisis/types" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) -// name of this module -const ModuleName = types.ModuleName - // app module basics object type AppModuleBasic struct{} -var _ sdk.AppModuleBasic = AppModuleBasic{} +var _ module.AppModuleBasic = AppModuleBasic{} // module name func (AppModuleBasic) Name() string { @@ -39,17 +38,13 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { // default genesis state func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return moduleCdc.MustMarshalJSON(DefaultGenesisState()) + return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } // module validate genesis func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) - if err != nil { - return err - } - return ValidateGenesis(data) + //TODO + return nil } // register rest routes @@ -58,7 +53,7 @@ func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router // get the root tx command of this module func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd(moduleCdc) + return cli.GetTxCmd(ModuleCdc) } // get the root query command of this module @@ -110,7 +105,7 @@ func (AppModule) NewQuerierHandler() sdk.Querier { return nil } // module init-genesis func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState - moduleCdc.MustUnmarshalJSON(data, &genesisState) + ModuleCdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.keeper, genesisState) am.keeper.AssertInvariants(ctx, am.logger) @@ -120,7 +115,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va // module export genesis func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) - return moduleCdc.MustMarshalJSON(gs) + return ModuleCdc.MustMarshalJSON(gs) } // module begin-block diff --git a/x/crisis/types/codec.go b/x/crisis/types/codec.go index ccc690a4fd08..520cb3fedbe3 100644 --- a/x/crisis/types/codec.go +++ b/x/crisis/types/codec.go @@ -10,11 +10,10 @@ func RegisterCodec(cdc *codec.Codec) { } // generic sealed codec to be used throughout module -var moduleCdc *codec.Codec +var ModuleCdc *codec.Codec func init() { - cdc := codec.New() - RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - moduleCdc = cdc.Seal() + RegisterCodec(ModuleCdc) + codec.RegisterCrypto(ModuleCdc) + ModuleCdc.Seal() } diff --git a/x/crisis/types/msgs.go b/x/crisis/types/msgs.go index db37c9aed974..e14b1528303a 100644 --- a/x/crisis/types/msgs.go +++ b/x/crisis/types/msgs.go @@ -34,7 +34,7 @@ func (msg MsgVerifyInvariant) GetSigners() []sdk.AccAddress { return []sdk.AccAd // GetSignBytes gets the sign bytes for the msg MsgVerifyInvariant func (msg MsgVerifyInvariant) GetSignBytes() []byte { - bz := moduleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } diff --git a/x/distribution/alias.go b/x/distribution/alias.go index e00d0075979b..619ae1d89e7f 100644 --- a/x/distribution/alias.go +++ b/x/distribution/alias.go @@ -14,19 +14,6 @@ import ( const ( DefaultParamspace = keeper.DefaultParamspace - QueryParams = keeper.QueryParams - QueryValidatorOutstandingRewards = keeper.QueryValidatorOutstandingRewards - QueryValidatorCommission = keeper.QueryValidatorCommission - QueryValidatorSlashes = keeper.QueryValidatorSlashes - QueryDelegationRewards = keeper.QueryDelegationRewards - QueryDelegatorTotalRewards = keeper.QueryDelegatorTotalRewards - QueryDelegatorValidators = keeper.QueryDelegatorValidators - QueryWithdrawAddr = keeper.QueryWithdrawAddr - QueryCommunityPool = keeper.QueryCommunityPool - ParamCommunityTax = keeper.ParamCommunityTax - ParamBaseProposerReward = keeper.ParamBaseProposerReward - ParamBonusProposerReward = keeper.ParamBonusProposerReward - ParamWithdrawAddrEnabled = keeper.ParamWithdrawAddrEnabled DefaultCodespace = types.DefaultCodespace CodeInvalidInput = types.CodeInvalidInput CodeNoDistributionInfo = types.CodeNoDistributionInfo @@ -37,6 +24,20 @@ const ( TStoreKey = types.TStoreKey RouterKey = types.RouterKey QuerierRoute = types.QuerierRoute + ProposalTypeCommunityPoolSpend = types.ProposalTypeCommunityPoolSpend + QueryParams = types.QueryParams + QueryValidatorOutstandingRewards = types.QueryValidatorOutstandingRewards + QueryValidatorCommission = types.QueryValidatorCommission + QueryValidatorSlashes = types.QueryValidatorSlashes + QueryDelegationRewards = types.QueryDelegationRewards + QueryDelegatorTotalRewards = types.QueryDelegatorTotalRewards + QueryDelegatorValidators = types.QueryDelegatorValidators + QueryWithdrawAddr = types.QueryWithdrawAddr + QueryCommunityPool = types.QueryCommunityPool + ParamCommunityTax = types.ParamCommunityTax + ParamBaseProposerReward = types.ParamBaseProposerReward + ParamBonusProposerReward = types.ParamBonusProposerReward + ParamWithdrawAddrEnabled = types.ParamWithdrawAddrEnabled ) var ( @@ -64,13 +65,8 @@ var ( GetValidatorSlashEventPrefix = keeper.GetValidatorSlashEventPrefix GetValidatorSlashEventKey = keeper.GetValidatorSlashEventKey ParamKeyTable = keeper.ParamKeyTable + HandleCommunityPoolSpendProposal = keeper.HandleCommunityPoolSpendProposal NewQuerier = keeper.NewQuerier - NewQueryValidatorOutstandingRewardsParams = keeper.NewQueryValidatorOutstandingRewardsParams - NewQueryValidatorCommissionParams = keeper.NewQueryValidatorCommissionParams - NewQueryValidatorSlashesParams = keeper.NewQueryValidatorSlashesParams - NewQueryDelegationRewardsParams = keeper.NewQueryDelegationRewardsParams - NewQueryDelegatorParams = keeper.NewQueryDelegatorParams - NewQueryDelegatorWithdrawAddrParams = keeper.NewQueryDelegatorWithdrawAddrParams MakeTestCodec = keeper.MakeTestCodec CreateTestInputDefault = keeper.CreateTestInputDefault CreateTestInputAdvanced = keeper.CreateTestInputAdvanced @@ -84,6 +80,8 @@ var ( ErrNoValidatorCommission = types.ErrNoValidatorCommission ErrSetWithdrawAddrDisabled = types.ErrSetWithdrawAddrDisabled ErrBadDistribution = types.ErrBadDistribution + ErrInvalidProposalAmount = types.ErrInvalidProposalAmount + ErrEmptyProposalRecipient = types.ErrEmptyProposalRecipient InitialFeePool = types.InitialFeePool NewGenesisState = types.NewGenesisState DefaultGenesisState = types.DefaultGenesisState @@ -91,13 +89,19 @@ var ( NewMsgSetWithdrawAddress = types.NewMsgSetWithdrawAddress NewMsgWithdrawDelegatorReward = types.NewMsgWithdrawDelegatorReward NewMsgWithdrawValidatorCommission = types.NewMsgWithdrawValidatorCommission + NewCommunityPoolSpendProposal = types.NewCommunityPoolSpendProposal + NewQueryValidatorOutstandingRewardsParams = types.NewQueryValidatorOutstandingRewardsParams + NewQueryValidatorCommissionParams = types.NewQueryValidatorCommissionParams + NewQueryValidatorSlashesParams = types.NewQueryValidatorSlashesParams + NewQueryDelegationRewardsParams = types.NewQueryDelegationRewardsParams + NewQueryDelegatorParams = types.NewQueryDelegatorParams + NewQueryDelegatorWithdrawAddrParams = types.NewQueryDelegatorWithdrawAddrParams NewQueryDelegatorTotalRewardsResponse = types.NewQueryDelegatorTotalRewardsResponse NewDelegationDelegatorReward = types.NewDelegationDelegatorReward NewValidatorHistoricalRewards = types.NewValidatorHistoricalRewards NewValidatorCurrentRewards = types.NewValidatorCurrentRewards InitialValidatorAccumulatedCommission = types.InitialValidatorAccumulatedCommission NewValidatorSlashEvent = types.NewValidatorSlashEvent - NewCommunityPoolSpendProposal = types.NewCommunityPoolSpendProposal // variable aliases FeePoolKey = keeper.FeePoolKey @@ -126,12 +130,6 @@ var ( type ( Hooks = keeper.Hooks Keeper = keeper.Keeper - QueryValidatorOutstandingRewardsParams = keeper.QueryValidatorOutstandingRewardsParams - QueryValidatorCommissionParams = keeper.QueryValidatorCommissionParams - QueryValidatorSlashesParams = keeper.QueryValidatorSlashesParams - QueryDelegationRewardsParams = keeper.QueryDelegationRewardsParams - QueryDelegatorParams = keeper.QueryDelegatorParams - QueryDelegatorWithdrawAddrParams = keeper.QueryDelegatorWithdrawAddrParams DummyFeeCollectionKeeper = keeper.DummyFeeCollectionKeeper DelegatorStartingInfo = types.DelegatorStartingInfo CodeType = types.CodeType @@ -146,11 +144,17 @@ type ( ValidatorCurrentRewardsRecord = types.ValidatorCurrentRewardsRecord DelegatorStartingInfoRecord = types.DelegatorStartingInfoRecord ValidatorSlashEventRecord = types.ValidatorSlashEventRecord - CommunityPoolSpendProposal = types.CommunityPoolSpendProposal GenesisState = types.GenesisState MsgSetWithdrawAddress = types.MsgSetWithdrawAddress MsgWithdrawDelegatorReward = types.MsgWithdrawDelegatorReward MsgWithdrawValidatorCommission = types.MsgWithdrawValidatorCommission + CommunityPoolSpendProposal = types.CommunityPoolSpendProposal + QueryValidatorOutstandingRewardsParams = types.QueryValidatorOutstandingRewardsParams + QueryValidatorCommissionParams = types.QueryValidatorCommissionParams + QueryValidatorSlashesParams = types.QueryValidatorSlashesParams + QueryDelegationRewardsParams = types.QueryDelegationRewardsParams + QueryDelegatorParams = types.QueryDelegatorParams + QueryDelegatorWithdrawAddrParams = types.QueryDelegatorWithdrawAddrParams QueryDelegatorTotalRewardsResponse = types.QueryDelegatorTotalRewardsResponse DelegationDelegatorReward = types.DelegationDelegatorReward ValidatorHistoricalRewards = types.ValidatorHistoricalRewards diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index 317b565b6833..1e9a05aed93e 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -43,7 +43,7 @@ func GetTxCmd(storeKey string, cdc *amino.Codec) *cobra.Command { distTxCmd.AddCommand(client.PostCommands( GetCmdWithdrawRewards(cdc), GetCmdSetWithdrawAddr(cdc), - distCmds.GetCmdWithdrawAllRewards(cdc, storeKey), + GetCmdWithdrawAllRewards(cdc, storeKey), )...) return distTxCmd diff --git a/x/distribution/keeper/proposal_handler.go b/x/distribution/keeper/proposal_handler.go index a8c3a4f596f7..f2e11cad3031 100644 --- a/x/distribution/keeper/proposal_handler.go +++ b/x/distribution/keeper/proposal_handler.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/distribution/types" ) +// TODO func HandleCommunityPoolSpendProposal(ctx sdk.Context, k Keeper, p types.CommunityPoolSpendProposal) sdk.Error { feePool := k.GetFeePool(ctx) newPool, negative := feePool.CommunityPool.SafeSub(sdk.NewDecCoins(p.Amount)) diff --git a/x/distribution/keeper/querier.go b/x/distribution/keeper/querier.go index 6c172b8b7951..8d34bcbd1672 100644 --- a/x/distribution/keeper/querier.go +++ b/x/distribution/keeper/querier.go @@ -11,52 +11,34 @@ import ( "github.com/cosmos/cosmos-sdk/x/distribution/types" ) -// nolint -const ( - QueryParams = "params" - QueryValidatorOutstandingRewards = "validator_outstanding_rewards" - QueryValidatorCommission = "validator_commission" - QueryValidatorSlashes = "validator_slashes" - QueryDelegationRewards = "delegation_rewards" - QueryDelegatorTotalRewards = "delegator_total_rewards" - QueryDelegatorValidators = "delegator_validators" - QueryWithdrawAddr = "withdraw_addr" - QueryCommunityPool = "community_pool" - - ParamCommunityTax = "community_tax" - ParamBaseProposerReward = "base_proposer_reward" - ParamBonusProposerReward = "bonus_proposer_reward" - ParamWithdrawAddrEnabled = "withdraw_addr_enabled" -) - func NewQuerier(k Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { switch path[0] { - case QueryParams: + case types.QueryParams: return queryParams(ctx, path[1:], req, k) - case QueryValidatorOutstandingRewards: + case types.QueryValidatorOutstandingRewards: return queryValidatorOutstandingRewards(ctx, path[1:], req, k) - case QueryValidatorCommission: + case types.QueryValidatorCommission: return queryValidatorCommission(ctx, path[1:], req, k) - case QueryValidatorSlashes: + case types.QueryValidatorSlashes: return queryValidatorSlashes(ctx, path[1:], req, k) - case QueryDelegationRewards: + case types.QueryDelegationRewards: return queryDelegationRewards(ctx, path[1:], req, k) - case QueryDelegatorTotalRewards: + case types.QueryDelegatorTotalRewards: return queryDelegatorTotalRewards(ctx, path[1:], req, k) - case QueryDelegatorValidators: + case types.QueryDelegatorValidators: return queryDelegatorValidators(ctx, path[1:], req, k) - case QueryWithdrawAddr: + case types.QueryWithdrawAddr: return queryDelegatorWithdrawAddress(ctx, path[1:], req, k) - case QueryCommunityPool: + case types.QueryCommunityPool: return queryCommunityPool(ctx, path[1:], req, k) default: @@ -67,25 +49,25 @@ func NewQuerier(k Keeper) sdk.Querier { func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { switch path[0] { - case ParamCommunityTax: + case types.ParamCommunityTax: bz, err := codec.MarshalJSONIndent(k.cdc, k.GetCommunityTax(ctx)) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) } return bz, nil - case ParamBaseProposerReward: + case types.ParamBaseProposerReward: bz, err := codec.MarshalJSONIndent(k.cdc, k.GetBaseProposerReward(ctx)) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) } return bz, nil - case ParamBonusProposerReward: + case types.ParamBonusProposerReward: bz, err := codec.MarshalJSONIndent(k.cdc, k.GetBonusProposerReward(ctx)) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) } return bz, nil - case ParamWithdrawAddrEnabled: + case types.ParamWithdrawAddrEnabled: bz, err := codec.MarshalJSONIndent(k.cdc, k.GetWithdrawAddrEnabled(ctx)) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) @@ -96,20 +78,8 @@ func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper } } -// params for query 'custom/distr/validator_outstanding_rewards' -type QueryValidatorOutstandingRewardsParams struct { - ValidatorAddress sdk.ValAddress `json:"validator_address"` -} - -// creates a new instance of QueryValidatorOutstandingRewardsParams -func NewQueryValidatorOutstandingRewardsParams(validatorAddr sdk.ValAddress) QueryValidatorOutstandingRewardsParams { - return QueryValidatorOutstandingRewardsParams{ - ValidatorAddress: validatorAddr, - } -} - func queryValidatorOutstandingRewards(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { - var params QueryValidatorOutstandingRewardsParams + var params types.QueryValidatorOutstandingRewardsParams err := k.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -121,20 +91,8 @@ func queryValidatorOutstandingRewards(ctx sdk.Context, path []string, req abci.R return bz, nil } -// params for query 'custom/distr/validator_commission' -type QueryValidatorCommissionParams struct { - ValidatorAddress sdk.ValAddress `json:"validator_address"` -} - -// creates a new instance of QueryValidatorCommissionParams -func NewQueryValidatorCommissionParams(validatorAddr sdk.ValAddress) QueryValidatorCommissionParams { - return QueryValidatorCommissionParams{ - ValidatorAddress: validatorAddr, - } -} - func queryValidatorCommission(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { - var params QueryValidatorCommissionParams + var params types.QueryValidatorCommissionParams err := k.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -147,24 +105,8 @@ func queryValidatorCommission(ctx sdk.Context, path []string, req abci.RequestQu return bz, nil } -// params for query 'custom/distr/validator_slashes' -type QueryValidatorSlashesParams struct { - ValidatorAddress sdk.ValAddress `json:"validator_address"` - StartingHeight uint64 `json:"starting_height"` - EndingHeight uint64 `json:"ending_height"` -} - -// creates a new instance of QueryValidatorSlashesParams -func NewQueryValidatorSlashesParams(validatorAddr sdk.ValAddress, startingHeight uint64, endingHeight uint64) QueryValidatorSlashesParams { - return QueryValidatorSlashesParams{ - ValidatorAddress: validatorAddr, - StartingHeight: startingHeight, - EndingHeight: endingHeight, - } -} - func queryValidatorSlashes(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { - var params QueryValidatorSlashesParams + var params types.QueryValidatorSlashesParams err := k.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -183,22 +125,8 @@ func queryValidatorSlashes(ctx sdk.Context, path []string, req abci.RequestQuery return bz, nil } -// params for query 'custom/distr/delegation_rewards' -type QueryDelegationRewardsParams struct { - DelegatorAddress sdk.AccAddress `json:"delegator_address"` - ValidatorAddress sdk.ValAddress `json:"validator_address"` -} - -// creates a new instance of QueryDelegationRewardsParams -func NewQueryDelegationRewardsParams(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) QueryDelegationRewardsParams { - return QueryDelegationRewardsParams{ - DelegatorAddress: delegatorAddr, - ValidatorAddress: validatorAddr, - } -} - func queryDelegationRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { - var params QueryDelegationRewardsParams + var params types.QueryDelegationRewardsParams err := k.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -230,20 +158,8 @@ func queryDelegationRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, return bz, nil } -// params for query 'custom/distr/delegator_total_rewards' and 'custom/distr/delegator_validators' -type QueryDelegatorParams struct { - DelegatorAddress sdk.AccAddress `json:"delegator_address"` -} - -// creates a new instance of QueryDelegationRewardsParams -func NewQueryDelegatorParams(delegatorAddr sdk.AccAddress) QueryDelegatorParams { - return QueryDelegatorParams{ - DelegatorAddress: delegatorAddr, - } -} - func queryDelegatorTotalRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { - var params QueryDelegatorParams + var params types.QueryDelegatorParams err := k.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -279,7 +195,7 @@ func queryDelegatorTotalRewards(ctx sdk.Context, _ []string, req abci.RequestQue } func queryDelegatorValidators(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { - var params QueryDelegatorParams + var params types.QueryDelegatorParams err := k.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -305,18 +221,8 @@ func queryDelegatorValidators(ctx sdk.Context, _ []string, req abci.RequestQuery return bz, nil } -// params for query 'custom/distr/withdraw_addr' -type QueryDelegatorWithdrawAddrParams struct { - DelegatorAddress sdk.AccAddress `json:"delegator_address"` -} - -// NewQueryDelegatorWithdrawAddrParams creates a new instance of QueryDelegatorWithdrawAddrParams. -func NewQueryDelegatorWithdrawAddrParams(delegatorAddr sdk.AccAddress) QueryDelegatorWithdrawAddrParams { - return QueryDelegatorWithdrawAddrParams{DelegatorAddress: delegatorAddr} -} - func queryDelegatorWithdrawAddress(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { - var params QueryDelegatorWithdrawAddrParams + var params types.QueryDelegatorWithdrawAddrParams err := k.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) diff --git a/x/distribution/keeper/querier_test.go b/x/distribution/keeper/querier_test.go index fb0b6c3d4a10..ccb3d04a71e6 100644 --- a/x/distribution/keeper/querier_test.go +++ b/x/distribution/keeper/querier_test.go @@ -19,38 +19,38 @@ const custom = "custom" func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier) (communityTax sdk.Dec, baseProposerReward sdk.Dec, bonusProposerReward sdk.Dec, withdrawAddrEnabled bool) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryParams, ParamCommunityTax}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamCommunityTax}, "/"), Data: []byte{}, } - bz, err := querier(ctx, []string{QueryParams, ParamCommunityTax}, query) + bz, err := querier(ctx, []string{types.QueryParams, types.ParamCommunityTax}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &communityTax)) query = abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryParams, ParamBaseProposerReward}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamBaseProposerReward}, "/"), Data: []byte{}, } - bz, err = querier(ctx, []string{QueryParams, ParamBaseProposerReward}, query) + bz, err = querier(ctx, []string{types.QueryParams, types.ParamBaseProposerReward}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &baseProposerReward)) query = abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryParams, ParamBonusProposerReward}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamBonusProposerReward}, "/"), Data: []byte{}, } - bz, err = querier(ctx, []string{QueryParams, ParamBonusProposerReward}, query) + bz, err = querier(ctx, []string{types.QueryParams, types.ParamBonusProposerReward}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &bonusProposerReward)) query = abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryParams, ParamWithdrawAddrEnabled}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamWithdrawAddrEnabled}, "/"), Data: []byte{}, } - bz, err = querier(ctx, []string{QueryParams, ParamWithdrawAddrEnabled}, query) + bz, err = querier(ctx, []string{types.QueryParams, types.ParamWithdrawAddrEnabled}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &withdrawAddrEnabled)) @@ -59,11 +59,11 @@ func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier s func getQueriedValidatorOutstandingRewards(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, validatorAddr sdk.ValAddress) (outstandingRewards sdk.DecCoins) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryValidatorOutstandingRewards}, "/"), - Data: cdc.MustMarshalJSON(NewQueryValidatorOutstandingRewardsParams(validatorAddr)), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryValidatorOutstandingRewards}, "/"), + Data: cdc.MustMarshalJSON(types.NewQueryValidatorOutstandingRewardsParams(validatorAddr)), } - bz, err := querier(ctx, []string{QueryValidatorOutstandingRewards}, query) + bz, err := querier(ctx, []string{types.QueryValidatorOutstandingRewards}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &outstandingRewards)) @@ -72,11 +72,11 @@ func getQueriedValidatorOutstandingRewards(t *testing.T, ctx sdk.Context, cdc *c func getQueriedValidatorCommission(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, validatorAddr sdk.ValAddress) (validatorCommission sdk.DecCoins) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryValidatorCommission}, "/"), - Data: cdc.MustMarshalJSON(NewQueryValidatorCommissionParams(validatorAddr)), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryValidatorCommission}, "/"), + Data: cdc.MustMarshalJSON(types.NewQueryValidatorCommissionParams(validatorAddr)), } - bz, err := querier(ctx, []string{QueryValidatorCommission}, query) + bz, err := querier(ctx, []string{types.QueryValidatorCommission}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &validatorCommission)) @@ -85,11 +85,11 @@ func getQueriedValidatorCommission(t *testing.T, ctx sdk.Context, cdc *codec.Cod func getQueriedValidatorSlashes(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, validatorAddr sdk.ValAddress, startHeight uint64, endHeight uint64) (slashes []types.ValidatorSlashEvent) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryValidatorSlashes}, "/"), - Data: cdc.MustMarshalJSON(NewQueryValidatorSlashesParams(validatorAddr, startHeight, endHeight)), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryValidatorSlashes}, "/"), + Data: cdc.MustMarshalJSON(types.NewQueryValidatorSlashesParams(validatorAddr, startHeight, endHeight)), } - bz, err := querier(ctx, []string{QueryValidatorSlashes}, query) + bz, err := querier(ctx, []string{types.QueryValidatorSlashes}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &slashes)) @@ -98,11 +98,11 @@ func getQueriedValidatorSlashes(t *testing.T, ctx sdk.Context, cdc *codec.Codec, func getQueriedDelegationRewards(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) (rewards sdk.DecCoins) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryDelegationRewards}, "/"), - Data: cdc.MustMarshalJSON(NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr)), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDelegationRewards}, "/"), + Data: cdc.MustMarshalJSON(types.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr)), } - bz, err := querier(ctx, []string{QueryDelegationRewards}, query) + bz, err := querier(ctx, []string{types.QueryDelegationRewards}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &rewards)) @@ -111,11 +111,11 @@ func getQueriedDelegationRewards(t *testing.T, ctx sdk.Context, cdc *codec.Codec func getQueriedDelegatorTotalRewards(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, delegatorAddr sdk.AccAddress) (response types.QueryDelegatorTotalRewardsResponse) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryDelegatorTotalRewards}, "/"), - Data: cdc.MustMarshalJSON(NewQueryDelegatorParams(delegatorAddr)), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDelegatorTotalRewards}, "/"), + Data: cdc.MustMarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)), } - bz, err := querier(ctx, []string{QueryDelegatorTotalRewards}, query) + bz, err := querier(ctx, []string{types.QueryDelegatorTotalRewards}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &response)) @@ -124,11 +124,11 @@ func getQueriedDelegatorTotalRewards(t *testing.T, ctx sdk.Context, cdc *codec.C func getQueriedCommunityPool(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier) (ptr []byte) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryCommunityPool}, ""), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryCommunityPool}, ""), Data: []byte{}, } - cp, err := querier(ctx, []string{QueryCommunityPool}, query) + cp, err := querier(ctx, []string{types.QueryCommunityPool}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(cp, &ptr)) diff --git a/x/distribution/module.go b/x/distribution/module.go index dac75487684b..c157c5849101 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -3,19 +3,22 @@ package distribution import ( "encoding/json" + "github.com/gorilla/mux" "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" "github.com/cosmos/cosmos-sdk/x/distribution/client/rest" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) // app module basics object diff --git a/x/distribution/types/querier.go b/x/distribution/types/querier.go new file mode 100644 index 000000000000..1e4bf56dc6a0 --- /dev/null +++ b/x/distribution/types/querier.go @@ -0,0 +1,97 @@ +package types + +import sdk "github.com/cosmos/cosmos-sdk/types" + +// querier keys +const ( + QueryParams = "params" + QueryValidatorOutstandingRewards = "validator_outstanding_rewards" + QueryValidatorCommission = "validator_commission" + QueryValidatorSlashes = "validator_slashes" + QueryDelegationRewards = "delegation_rewards" + QueryDelegatorTotalRewards = "delegator_total_rewards" + QueryDelegatorValidators = "delegator_validators" + QueryWithdrawAddr = "withdraw_addr" + QueryCommunityPool = "community_pool" + + ParamCommunityTax = "community_tax" + ParamBaseProposerReward = "base_proposer_reward" + ParamBonusProposerReward = "bonus_proposer_reward" + ParamWithdrawAddrEnabled = "withdraw_addr_enabled" +) + +// params for query 'custom/distr/validator_outstanding_rewards' +type QueryValidatorOutstandingRewardsParams struct { + ValidatorAddress sdk.ValAddress `json:"validator_address"` +} + +// creates a new instance of QueryValidatorOutstandingRewardsParams +func NewQueryValidatorOutstandingRewardsParams(validatorAddr sdk.ValAddress) QueryValidatorOutstandingRewardsParams { + return QueryValidatorOutstandingRewardsParams{ + ValidatorAddress: validatorAddr, + } +} + +// params for query 'custom/distr/validator_commission' +type QueryValidatorCommissionParams struct { + ValidatorAddress sdk.ValAddress `json:"validator_address"` +} + +// creates a new instance of QueryValidatorCommissionParams +func NewQueryValidatorCommissionParams(validatorAddr sdk.ValAddress) QueryValidatorCommissionParams { + return QueryValidatorCommissionParams{ + ValidatorAddress: validatorAddr, + } +} + +// params for query 'custom/distr/validator_slashes' +type QueryValidatorSlashesParams struct { + ValidatorAddress sdk.ValAddress `json:"validator_address"` + StartingHeight uint64 `json:"starting_height"` + EndingHeight uint64 `json:"ending_height"` +} + +// creates a new instance of QueryValidatorSlashesParams +func NewQueryValidatorSlashesParams(validatorAddr sdk.ValAddress, startingHeight uint64, endingHeight uint64) QueryValidatorSlashesParams { + return QueryValidatorSlashesParams{ + ValidatorAddress: validatorAddr, + StartingHeight: startingHeight, + EndingHeight: endingHeight, + } +} + +// params for query 'custom/distr/delegation_rewards' +type QueryDelegationRewardsParams struct { + DelegatorAddress sdk.AccAddress `json:"delegator_address"` + ValidatorAddress sdk.ValAddress `json:"validator_address"` +} + +// creates a new instance of QueryDelegationRewardsParams +func NewQueryDelegationRewardsParams(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) QueryDelegationRewardsParams { + return QueryDelegationRewardsParams{ + DelegatorAddress: delegatorAddr, + ValidatorAddress: validatorAddr, + } +} + +// params for query 'custom/distr/delegator_total_rewards' and 'custom/distr/delegator_validators' +type QueryDelegatorParams struct { + DelegatorAddress sdk.AccAddress `json:"delegator_address"` +} + +// creates a new instance of QueryDelegationRewardsParams +func NewQueryDelegatorParams(delegatorAddr sdk.AccAddress) QueryDelegatorParams { + return QueryDelegatorParams{ + DelegatorAddress: delegatorAddr, + } +} + +// params for query 'custom/distr/withdraw_addr' +type QueryDelegatorWithdrawAddrParams struct { + DelegatorAddress sdk.AccAddress `json:"delegator_address"` +} + +// NewQueryDelegatorWithdrawAddrParams creates a new instance of QueryDelegatorWithdrawAddrParams. +func NewQueryDelegatorWithdrawAddrParams(delegatorAddr sdk.AccAddress) QueryDelegatorWithdrawAddrParams { + return QueryDelegatorWithdrawAddrParams{DelegatorAddress: delegatorAddr} +} diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 859104d6d73a..ca24341846e0 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -24,6 +24,7 @@ import ( kbkeys "github.com/cosmos/cosmos-sdk/crypto/keys" "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" @@ -39,7 +40,7 @@ type StakingMsgBuildingHelpers interface { // GenTxCmd builds the application's gentx command. // nolint: errcheck -func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm sdk.ModuleBasicManager, smbh StakingMsgBuildingHelpers, +func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, smbh StakingMsgBuildingHelpers, genAccIterator genutil.GenesisAccountsIterator, defaultNodeHome, defaultCLIHome string) *cobra.Command { ipDefault, _ := server.ExternalIP() diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 0c2f04834e81..57ed063a4f74 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -16,7 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/genutil" ) @@ -57,7 +57,7 @@ func displayInfo(cdc *codec.Codec, info printInfo) error { // InitCmd returns a command that initializes all files needed for Tendermint // and the respective application. -func InitCmd(ctx *server.Context, cdc *codec.Codec, mbm sdk.ModuleBasicManager, +func InitCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, defaultNodeHome string) *cobra.Command { // nolint: golint cmd := &cobra.Command{ Use: "init [moniker]", diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index f2f911db91d7..69d8b61c7fc5 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -20,10 +20,11 @@ import ( "github.com/cosmos/cosmos-sdk/server/mock" "github.com/cosmos/cosmos-sdk/tests" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/genutil" ) -var testMbm = sdk.NewModuleBasicManager(genutil.AppModuleBasic{}) +var testMbm = module.BasicManager(genutil.AppModuleBasic{}) func TestInitCmd(t *testing.T) { defer server.SetupViper(t)() diff --git a/x/genutil/client/cli/validate_genesis.go b/x/genutil/client/cli/validate_genesis.go index e7a1f850f572..f4baa5dc9df3 100644 --- a/x/genutil/client/cli/validate_genesis.go +++ b/x/genutil/client/cli/validate_genesis.go @@ -10,11 +10,11 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" ) // Validate genesis command takes -func ValidateGenesisCmd(ctx *server.Context, cdc *codec.Codec, mbm sdk.ModuleBasicManager) *cobra.Command { +func ValidateGenesisCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager) *cobra.Command { return &cobra.Command{ Use: "validate-genesis [file]", Args: cobra.RangeArgs(0, 1), diff --git a/x/genutil/module.go b/x/genutil/module.go index 5f87d6ae57cd..8afd4a5e7f96 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -3,17 +3,20 @@ package genutil import ( "encoding/json" + "github.com/gorilla/mux" "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" ) var ( - _ sdk.AppModuleGenesis = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleGenesis = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) // module name @@ -66,9 +69,9 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(accountKeeper AccountKeeper, - stakingKeeper StakingKeeper, deliverTx deliverTxfn) sdk.AppModule { + stakingKeeper StakingKeeper, deliverTx deliverTxfn) module.AppModule { - return sdk.NewGenesisOnlyAppModule(AppModule{ + return module.NewGenesisOnlyAppModule(AppModule{ AppModuleBasic: AppModuleBasic{}, accountKeeper: accountKeeper, stakingKeeper: stakingKeeper, diff --git a/x/gov/alias.go b/x/gov/alias.go index 84a437296495..4ee7d2a69cca 100644 --- a/x/gov/alias.go +++ b/x/gov/alias.go @@ -39,6 +39,17 @@ const ( StatusFailed = types.StatusFailed ProposalTypeText = types.ProposalTypeText ProposalTypeSoftwareUpgrade = types.ProposalTypeSoftwareUpgrade + QueryParams = types.QueryParams + QueryProposals = types.QueryProposals + QueryProposal = types.QueryProposal + QueryDeposits = types.QueryDeposits + QueryDeposit = types.QueryDeposit + QueryVotes = types.QueryVotes + QueryVote = types.QueryVote + QueryTally = types.QueryTally + ParamDeposit = types.ParamDeposit + ParamVoting = types.ParamVoting + ParamTallying = types.ParamTallying OptionEmpty = types.OptionEmpty OptionYes = types.OptionYes OptionAbstain = types.OptionAbstain @@ -85,6 +96,10 @@ var ( ContentFromProposalType = types.ContentFromProposalType IsValidProposalType = types.IsValidProposalType ProposalHandler = types.ProposalHandler + NewQueryProposalParams = types.NewQueryProposalParams + NewQueryDepositParams = types.NewQueryDepositParams + NewQueryVoteParams = types.NewQueryVoteParams + NewQueryProposalsParams = types.NewQueryProposalsParams VoteOptionFromString = types.VoteOptionFromString ValidVoteOption = types.ValidVoteOption @@ -111,6 +126,10 @@ type ( TallyResult = types.TallyResult TextProposal = types.TextProposal SoftwareUpgradeProposal = types.SoftwareUpgradeProposal + QueryProposalParams = types.QueryProposalParams + QueryDepositParams = types.QueryDepositParams + QueryVoteParams = types.QueryVoteParams + QueryProposalsParams = types.QueryProposalsParams Vote = types.Vote Votes = types.Votes VoteOption = types.VoteOption diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index d15cf7d9b4b8..10d2b5193636 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -18,7 +18,7 @@ import ( ) // GetQueryCmd returns the cli query commands for this module -func GetQueryCmd(storeKey string, cdc *amino.Codec) *cobra.Command { +func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { // Group gov queries under a subcommand govQueryCmd := &cobra.Command{ Use: gov.ModuleName, diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index c8c2ee4bccf4..6002ced7ac48 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -55,7 +55,7 @@ var ProposalFlags = []string{ // it contains a slice of "proposal" child commands. These commands are respective // to proposal type handlers that are implemented in other modules but are mounted // under the governance CLI (eg. parameter change proposals). -func GetTxCmd(storeKey string, cdc *amino.Codec, pcmds ...*cobra.Command) *cobra.Command { +func GetTxCmd(storeKey string, cdc *codec.Codec, pcmds ...*cobra.Command) *cobra.Command { govTxCmd := &cobra.Command{ Use: gov.ModuleName, Short: "Governance transactions subcommands", @@ -67,8 +67,8 @@ func GetTxCmd(storeKey string, cdc *amino.Codec, pcmds ...*cobra.Command) *cobra } govTxCmd.AddCommand(client.PostCommands( - GetCmdDeposit(storeKey, cdc), - GetCmdVote(storeKey, cdc), + GetCmdDeposit(cdc), + GetCmdVote(cdc), cmdSubmitProp, )...) diff --git a/x/gov/module.go b/x/gov/module.go index 131ebd961332..035c72fe2cb7 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -3,20 +3,23 @@ package gov import ( "encoding/json" + "github.com/gorilla/mux" "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" "github.com/cosmos/cosmos-sdk/x/gov/client/rest" "github.com/cosmos/cosmos-sdk/x/gov/types" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) // app module basics object @@ -31,7 +34,7 @@ func NewAppModuleBasic(proposalCmds []*cobra.Command) AppModuleBasic { } } -var _ sdk.AppModuleBasic = AppModuleBasic{} +var _ module.AppModuleBasic = AppModuleBasic{} // module name func (AppModuleBasic) Name() string { @@ -60,17 +63,19 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { // register rest routes func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { - rest.RegisterRoutes(ctx, rtr, cdc, StoreKey) + + // XXX include ProposalRESTHandler ?? + rest.RegisterRoutes(ctx, rtr, cdc) } // get the root tx command of this module func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd(StoreKey, moduleCdc) + return cli.GetTxCmd(StoreKey, ModuleCdc) } // get the root query command of this module func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(StoreKey, moduleCdc) + return cli.GetQueryCmd(StoreKey, ModuleCdc) } //___________________________ diff --git a/x/gov/querier.go b/x/gov/querier.go index 87202800daee..266127edae5f 100644 --- a/x/gov/querier.go +++ b/x/gov/querier.go @@ -7,28 +7,13 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" -) - -// query endpoints supported by the governance Querier -const ( - QueryParams = "params" - QueryProposals = "proposals" - QueryProposal = "proposal" - QueryDeposits = "deposits" - QueryDeposit = "deposit" - QueryVotes = "votes" - QueryVote = "vote" - QueryTally = "tally" - - ParamDeposit = "deposit" - ParamVoting = "voting" - ParamTallying = "tallying" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) func NewQuerier(keeper Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { switch path[0] { - case QueryParams: + case types.QueryParams: return queryParams(ctx, path[1:], req, keeper) case QueryProposals: return queryProposals(ctx, path[1:], req, keeper) @@ -75,22 +60,6 @@ func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, keeper K } } -// Params for queries: -// - 'custom/gov/proposal' -// - 'custom/gov/deposits' -// - 'custom/gov/tally' -// - 'custom/gov/votes' -type QueryProposalParams struct { - ProposalID uint64 -} - -// creates a new instance of QueryProposalParams -func NewQueryProposalParams(proposalID uint64) QueryProposalParams { - return QueryProposalParams{ - ProposalID: proposalID, - } -} - // nolint: unparam func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { var params QueryProposalParams @@ -111,20 +80,6 @@ func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// Params for query 'custom/gov/deposit' -type QueryDepositParams struct { - ProposalID uint64 - Depositor sdk.AccAddress -} - -// creates a new instance of QueryDepositParams -func NewQueryDepositParams(proposalID uint64, depositor sdk.AccAddress) QueryDepositParams { - return QueryDepositParams{ - ProposalID: proposalID, - Depositor: depositor, - } -} - // nolint: unparam func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { var params QueryDepositParams @@ -141,20 +96,6 @@ func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// Params for query 'custom/gov/vote' -type QueryVoteParams struct { - ProposalID uint64 - Voter sdk.AccAddress -} - -// creates a new instance of QueryVoteParams -func NewQueryVoteParams(proposalID uint64, voter sdk.AccAddress) QueryVoteParams { - return QueryVoteParams{ - ProposalID: proposalID, - Voter: voter, - } -} - // nolint: unparam func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { var params QueryVoteParams @@ -253,24 +194,6 @@ func queryVotes(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Ke return bz, nil } -// Params for query 'custom/gov/proposals' -type QueryProposalsParams struct { - Voter sdk.AccAddress - Depositor sdk.AccAddress - ProposalStatus ProposalStatus - Limit uint64 -} - -// creates a new instance of QueryProposalsParams -func NewQueryProposalsParams(status ProposalStatus, limit uint64, voter, depositor sdk.AccAddress) QueryProposalsParams { - return QueryProposalsParams{ - Voter: voter, - Depositor: depositor, - ProposalStatus: status, - Limit: limit, - } -} - // nolint: unparam func queryProposals(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { var params QueryProposalsParams diff --git a/x/gov/types/querier.go b/x/gov/types/querier.go new file mode 100644 index 000000000000..cfe0abc4d328 --- /dev/null +++ b/x/gov/types/querier.go @@ -0,0 +1,83 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// query endpoints supported by the governance Querier +const ( + QueryParams = "params" + QueryProposals = "proposals" + QueryProposal = "proposal" + QueryDeposits = "deposits" + QueryDeposit = "deposit" + QueryVotes = "votes" + QueryVote = "vote" + QueryTally = "tally" + + ParamDeposit = "deposit" + ParamVoting = "voting" + ParamTallying = "tallying" +) + +// Params for queries: +// - 'custom/gov/proposal' +// - 'custom/gov/deposits' +// - 'custom/gov/tally' +// - 'custom/gov/votes' +type QueryProposalParams struct { + ProposalID uint64 +} + +// creates a new instance of QueryProposalParams +func NewQueryProposalParams(proposalID uint64) QueryProposalParams { + return QueryProposalParams{ + ProposalID: proposalID, + } +} + +// Params for query 'custom/gov/deposit' +type QueryDepositParams struct { + ProposalID uint64 + Depositor sdk.AccAddress +} + +// creates a new instance of QueryDepositParams +func NewQueryDepositParams(proposalID uint64, depositor sdk.AccAddress) QueryDepositParams { + return QueryDepositParams{ + ProposalID: proposalID, + Depositor: depositor, + } +} + +// Params for query 'custom/gov/vote' +type QueryVoteParams struct { + ProposalID uint64 + Voter sdk.AccAddress +} + +// creates a new instance of QueryVoteParams +func NewQueryVoteParams(proposalID uint64, voter sdk.AccAddress) QueryVoteParams { + return QueryVoteParams{ + ProposalID: proposalID, + Voter: voter, + } +} + +// Params for query 'custom/gov/proposals' +type QueryProposalsParams struct { + Voter sdk.AccAddress + Depositor sdk.AccAddress + ProposalStatus ProposalStatus + Limit uint64 +} + +// creates a new instance of QueryProposalsParams +func NewQueryProposalsParams(status ProposalStatus, limit uint64, voter, depositor sdk.AccAddress) QueryProposalsParams { + return QueryProposalsParams{ + Voter: voter, + Depositor: depositor, + ProposalStatus: status, + Limit: limit, + } +} diff --git a/x/mint/alias.go b/x/mint/alias.go new file mode 100644 index 000000000000..5a4e708f92d4 --- /dev/null +++ b/x/mint/alias.go @@ -0,0 +1,39 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/mint/types +package mint + +import ( + "github.com/cosmos/cosmos-sdk/x/mint/types" +) + +const ( + ModuleName = types.ModuleName + DefaultParamspace = types.DefaultParamspace + StoreKey = types.StoreKey + QuerierRoute = types.QuerierRoute + QueryParameters = types.QueryParameters + QueryInflation = types.QueryInflation + QueryAnnualProvisions = types.QueryAnnualProvisions +) + +var ( + // functions aliases + ParamKeyTable = types.ParamKeyTable + NewParams = types.NewParams + DefaultParams = types.DefaultParams + + // variable aliases + ModuleCdc = types.ModuleCdc + KeyMintDenom = types.KeyMintDenom + KeyInflationRateChange = types.KeyInflationRateChange + KeyInflationMax = types.KeyInflationMax + KeyInflationMin = types.KeyInflationMin + KeyGoalBonded = types.KeyGoalBonded + KeyBlocksPerYear = types.KeyBlocksPerYear +) + +type ( + Params = types.Params +) diff --git a/x/mint/client/cli/query.go b/x/mint/client/cli/query.go index 424e79a52ce4..946e0f98e77f 100644 --- a/x/mint/client/cli/query.go +++ b/x/mint/client/cli/query.go @@ -5,6 +5,7 @@ import ( "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -19,7 +20,7 @@ func GetQueryCmd(cdc *codec.Codec) *cobra.Command { } mintingQueryCmd.AddCommand( - sdkclient.GetCommands( + client.GetCommands( GetCmdQueryParams(cdc), GetCmdQueryInflation(cdc), GetCmdQueryAnnualProvisions(cdc), diff --git a/x/mint/genesis.go b/x/mint/genesis.go index 11f96c6f90bb..c101bdaa7030 100644 --- a/x/mint/genesis.go +++ b/x/mint/genesis.go @@ -2,12 +2,13 @@ package mint import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/mint/types" ) // GenesisState - minter state type GenesisState struct { - Minter Minter `json:"minter"` // minter object - Params Params `json:"params"` // inflation params + Minter Minter `json:"minter"` // minter object + Params types.Params `json:"params"` // inflation params } // NewGenesisState creates a new GenesisState object diff --git a/x/mint/module.go b/x/mint/module.go index 7d6fad7d33e1..3cad7acce749 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -3,19 +3,22 @@ package mint import ( "encoding/json" + "github.com/gorilla/mux" "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/mint/client/cli" "github.com/cosmos/cosmos-sdk/x/mint/client/rest" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) // name of this module @@ -24,7 +27,7 @@ const ModuleName = "mint" // app module basics object type AppModuleBasic struct{} -var _ sdk.AppModuleBasic = AppModuleBasic{} +var _ module.AppModuleBasic = AppModuleBasic{} // module name func (AppModuleBasic) Name() string { diff --git a/x/mint/codec.go b/x/mint/types/codec.go similarity index 53% rename from x/mint/codec.go rename to x/mint/types/codec.go index e704d29f6054..1d48351a95a0 100644 --- a/x/mint/codec.go +++ b/x/mint/types/codec.go @@ -1,14 +1,13 @@ -package mint +package types import ( "github.com/cosmos/cosmos-sdk/codec" ) // generic sealed codec to be used throughout this module -var moduleCdc *codec.Codec +var ModuleCdc *codec.Codec func init() { - cdc := codec.New() - codec.RegisterCrypto(cdc) - moduleCdc = cdc.Seal() + codec.RegisterCrypto(ModuleCdc) + ModuleCdc.Seal() } diff --git a/x/params/module.go b/x/params/module.go index 275303cab076..36124b4156c2 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -3,6 +3,10 @@ package params import ( "encoding/json" + "github.com/gorilla/mux" + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/params/types" @@ -32,3 +36,12 @@ func (AppModuleBasic) DefaultGenesis() json.RawMessage { return nil } // module validate genesis func (AppModuleBasic) ValidateGenesis(_ json.RawMessage) error { return nil } + +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router, _ *codec.Codec) {} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } diff --git a/x/slashing/genesis.go b/x/slashing/genesis.go index e594ac6611d8..a20ea4870887 100644 --- a/x/slashing/genesis.go +++ b/x/slashing/genesis.go @@ -2,11 +2,13 @@ package slashing import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/slashing/keeper" ) // InitGenesis initialize default parameters // and the keeper's address to pubkey map -func InitGenesis(ctx sdk.Context, keeper Keeper, stakingKeeper StakingKeeper, data GenesisState) { +func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, stakingKeeper types.StakingKeeper, data types.GenesisState) { stakingKeeper.IterateValidators(ctx, func(index int64, validator sdk.Validator) bool { keeper.addPubkey(ctx, validator.GetConsPubKey()) @@ -38,7 +40,7 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, stakingKeeper StakingKeeper, da // ExportGenesis writes the current store values // to a genesis file, which can be imported again // with InitGenesis -func ExportGenesis(ctx sdk.Context, keeper Keeper) (data GenesisState) { +func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) (data types.GenesisState) { var params Params keeper.paramspace.GetParamSet(ctx, ¶ms) diff --git a/x/slashing/handler.go b/x/slashing/handler.go index d3562fe05d1b..f3716bfefea5 100644 --- a/x/slashing/handler.go +++ b/x/slashing/handler.go @@ -4,6 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/slashing/tags" ) @@ -23,7 +24,7 @@ func NewHandler(k Keeper) sdk.Handler { // Validators must submit a transaction to unjail itself after // having been jailed (and thus unbonded) for downtime -func handleMsgUnjail(ctx sdk.Context, msg MsgUnjail, k Keeper) sdk.Result { +func handleMsgUnjail(ctx sdk.Context, msg types.MsgUnjail, k Keeper) sdk.Result { validator := k.validatorSet.Validator(ctx, msg.ValidatorAddr) if validator == nil { return ErrNoValidatorForAddress(k.codespace).Result() diff --git a/x/slashing/keeper/hooks.go b/x/slashing/keeper/hooks.go index 8497d6ab83a4..ebb8d5a4a4fd 100644 --- a/x/slashing/keeper/hooks.go +++ b/x/slashing/keeper/hooks.go @@ -7,13 +7,14 @@ import ( "github.com/tendermint/tendermint/crypto" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) func (k Keeper) AfterValidatorBonded(ctx sdk.Context, address sdk.ConsAddress, _ sdk.ValAddress) { // Update the signing info start height or create a new signing info _, found := k.getValidatorSigningInfo(ctx, address) if !found { - signingInfo := NewValidatorSigningInfo( + signingInfo := types.NewValidatorSigningInfo( address, ctx.BlockHeight(), 0, diff --git a/x/slashing/keeper/keeper.go b/x/slashing/keeper/keeper.go index 8d927c05abd3..227320c51887 100644 --- a/x/slashing/keeper/keeper.go +++ b/x/slashing/keeper/keeper.go @@ -10,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) // Keeper of the slashing store @@ -29,7 +30,7 @@ func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, vs sdk.ValidatorSet, paramspa storeKey: key, cdc: cdc, validatorSet: vs, - paramspace: paramspace.WithKeyTable(ParamKeyTable()), + paramspace: paramspace.WithKeyTable(types.ParamKeyTable()), codespace: codespace, } return keeper @@ -120,7 +121,7 @@ func (k Keeper) handleDoubleSign(ctx sdk.Context, addr crypto.Address, infractio signInfo.Tombstoned = true // Set jailed until to be forever (max time) - signInfo.JailedUntil = DoubleSignJailEndTime + signInfo.JailedUntil = types.DoubleSignJailEndTime // Set validator signing info k.SetValidatorSigningInfo(ctx, consAddr, signInfo) @@ -215,7 +216,7 @@ func (k Keeper) addPubkey(ctx sdk.Context, pubkey crypto.PubKey) { func (k Keeper) getPubkey(ctx sdk.Context, address crypto.Address) (crypto.PubKey, error) { store := ctx.KVStore(k.storeKey) var pubkey crypto.PubKey - err := k.cdc.UnmarshalBinaryLengthPrefixed(store.Get(getAddrPubkeyRelationKey(address)), &pubkey) + err := k.cdc.UnmarshalBinaryLengthPrefixed(store.Get(types.GetAddrPubkeyRelationKey(address)), &pubkey) if err != nil { return nil, fmt.Errorf("address %v not found", address) } @@ -225,10 +226,10 @@ func (k Keeper) getPubkey(ctx sdk.Context, address crypto.Address) (crypto.PubKe func (k Keeper) setAddrPubkeyRelation(ctx sdk.Context, addr crypto.Address, pubkey crypto.PubKey) { store := ctx.KVStore(k.storeKey) bz := k.cdc.MustMarshalBinaryLengthPrefixed(pubkey) - store.Set(getAddrPubkeyRelationKey(addr), bz) + store.Set(types.GetAddrPubkeyRelationKey(addr), bz) } func (k Keeper) deleteAddrPubkeyRelation(ctx sdk.Context, addr crypto.Address) { store := ctx.KVStore(k.storeKey) - store.Delete(getAddrPubkeyRelationKey(addr)) + store.Delete(types.GetAddrPubkeyRelationKey(addr)) } diff --git a/x/slashing/keeper/keeper_test.go b/x/slashing/keeper/keeper_test.go index 0edb20db08a2..1dcbbebfd4b5 100644 --- a/x/slashing/keeper/keeper_test.go +++ b/x/slashing/keeper/keeper_test.go @@ -8,13 +8,14 @@ import ( abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/cosmos/cosmos-sdk/x/staking" ) // Have to change these parameters for tests // lest the tests take forever -func keeperTestParams() Params { - params := DefaultParams() +func keeperTestParams() types.Params { + params := types.DefaultParams() params.SignedBlocksWindow = 1000 params.DowntimeJailDuration = 60 * 60 return params @@ -67,7 +68,7 @@ func TestHandleDoubleSign(t *testing.T) { ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(1, 0).Add(sk.GetParams(ctx).UnbondingTime)}) // Still shouldn't be able to unjail - msgUnjail := NewMsgUnjail(operatorAddr) + msgUnjail := types.NewMsgUnjail(operatorAddr) res := handleMsgUnjail(ctx, msgUnjail, keeper) require.False(t, res.IsOK()) diff --git a/x/slashing/keeper/params.go b/x/slashing/keeper/params.go index af59bac29891..7a1c3174a8bb 100644 --- a/x/slashing/keeper/params.go +++ b/x/slashing/keeper/params.go @@ -4,24 +4,25 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) // MaxEvidenceAge - max age for evidence func (k Keeper) MaxEvidenceAge(ctx sdk.Context) (res time.Duration) { - k.paramspace.Get(ctx, KeyMaxEvidenceAge, &res) + k.paramspace.Get(ctx, types.KeyMaxEvidenceAge, &res) return } // SignedBlocksWindow - sliding window for downtime slashing func (k Keeper) SignedBlocksWindow(ctx sdk.Context) (res int64) { - k.paramspace.Get(ctx, KeySignedBlocksWindow, &res) + k.paramspace.Get(ctx, types.KeySignedBlocksWindow, &res) return } // Downtime slashing threshold func (k Keeper) MinSignedPerWindow(ctx sdk.Context) int64 { var minSignedPerWindow sdk.Dec - k.paramspace.Get(ctx, KeyMinSignedPerWindow, &minSignedPerWindow) + k.paramspace.Get(ctx, types.KeyMinSignedPerWindow, &minSignedPerWindow) signedBlocksWindow := k.SignedBlocksWindow(ctx) // NOTE: RoundInt64 will never panic as minSignedPerWindow is @@ -31,24 +32,24 @@ func (k Keeper) MinSignedPerWindow(ctx sdk.Context) int64 { // Downtime unbond duration func (k Keeper) DowntimeJailDuration(ctx sdk.Context) (res time.Duration) { - k.paramspace.Get(ctx, KeyDowntimeJailDuration, &res) + k.paramspace.Get(ctx, types.KeyDowntimeJailDuration, &res) return } // SlashFractionDoubleSign func (k Keeper) SlashFractionDoubleSign(ctx sdk.Context) (res sdk.Dec) { - k.paramspace.Get(ctx, KeySlashFractionDoubleSign, &res) + k.paramspace.Get(ctx, types.KeySlashFractionDoubleSign, &res) return } // SlashFractionDowntime func (k Keeper) SlashFractionDowntime(ctx sdk.Context) (res sdk.Dec) { - k.paramspace.Get(ctx, KeySlashFractionDowntime, &res) + k.paramspace.Get(ctx, types.KeySlashFractionDowntime, &res) return } // GetParams returns the total set of slashing parameters. -func (k Keeper) GetParams(ctx sdk.Context) (params Params) { +func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { k.paramspace.GetParamSet(ctx, ¶ms) return params } diff --git a/x/slashing/keeper/signing_info.go b/x/slashing/keeper/signing_info.go index a173cc2ad27a..47b60faa5d6b 100644 --- a/x/slashing/keeper/signing_info.go +++ b/x/slashing/keeper/signing_info.go @@ -2,12 +2,13 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) // Stored by *validator* address (not operator address) -func (k Keeper) getValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress) (info ValidatorSigningInfo, found bool) { +func (k Keeper) getValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress) (info types.ValidatorSigningInfo, found bool) { store := ctx.KVStore(k.storeKey) - bz := store.Get(GetValidatorSigningInfoKey(address)) + bz := store.Get(types.GetValidatorSigningInfoKey(address)) if bz == nil { found = false return @@ -19,14 +20,14 @@ func (k Keeper) getValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress // Stored by *validator* address (not operator address) func (k Keeper) IterateValidatorSigningInfos(ctx sdk.Context, - handler func(address sdk.ConsAddress, info ValidatorSigningInfo) (stop bool)) { + handler func(address sdk.ConsAddress, info types.ValidatorSigningInfo) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorSigningInfoKey) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorSigningInfoKey) defer iter.Close() for ; iter.Valid(); iter.Next() { - address := GetValidatorSigningInfoAddress(iter.Key()) - var info ValidatorSigningInfo + address := types.GetValidatorSigningInfoAddress(iter.Key()) + var info types.ValidatorSigningInfo k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &info) if handler(address, info) { break @@ -35,16 +36,16 @@ func (k Keeper) IterateValidatorSigningInfos(ctx sdk.Context, } // Stored by *validator* address (not operator address) -func (k Keeper) SetValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress, info ValidatorSigningInfo) { +func (k Keeper) SetValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress, info types.ValidatorSigningInfo) { store := ctx.KVStore(k.storeKey) bz := k.cdc.MustMarshalBinaryLengthPrefixed(info) - store.Set(GetValidatorSigningInfoKey(address), bz) + store.Set(types.GetValidatorSigningInfoKey(address), bz) } // Stored by *validator* address (not operator address) func (k Keeper) getValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.ConsAddress, index int64) (missed bool) { store := ctx.KVStore(k.storeKey) - bz := store.Get(GetValidatorMissedBlockBitArrayKey(address, index)) + bz := store.Get(types.GetValidatorMissedBlockBitArrayKey(address, index)) if bz == nil { // lazy: treat empty key as not missed missed = false @@ -63,7 +64,7 @@ func (k Keeper) IterateValidatorMissedBlockBitArray(ctx sdk.Context, // Array may be sparse for ; index < k.SignedBlocksWindow(ctx); index++ { var missed bool - bz := store.Get(GetValidatorMissedBlockBitArrayKey(address, index)) + bz := store.Get(types.GetValidatorMissedBlockBitArrayKey(address, index)) if bz == nil { continue } @@ -78,13 +79,13 @@ func (k Keeper) IterateValidatorMissedBlockBitArray(ctx sdk.Context, func (k Keeper) setValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.ConsAddress, index int64, missed bool) { store := ctx.KVStore(k.storeKey) bz := k.cdc.MustMarshalBinaryLengthPrefixed(missed) - store.Set(GetValidatorMissedBlockBitArrayKey(address, index), bz) + store.Set(types.GetValidatorMissedBlockBitArrayKey(address, index), bz) } // Stored by *validator* address (not operator address) func (k Keeper) clearValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.ConsAddress) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, GetValidatorMissedBlockBitArrayPrefixKey(address)) + iter := sdk.KVStorePrefixIterator(store, types.GetValidatorMissedBlockBitArrayPrefixKey(address)) defer iter.Close() for ; iter.Valid(); iter.Next() { store.Delete(iter.Key()) diff --git a/x/slashing/module.go b/x/slashing/module.go index 7e5d226c5103..3f60b6f6e24e 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -3,32 +3,33 @@ package slashing import ( "encoding/json" + "github.com/gorilla/mux" "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) -// name of this module -const ModuleName = "slashing" - // app module basics object type AppModuleBasic struct{} -var _ sdk.AppModuleBasic = AppModuleBasic{} +var _ module.AppModuleBasic = AppModuleBasic{} // module name func (AppModuleBasic) Name() string { - return ModuleName + return types.ModuleName } // register module codec diff --git a/x/slashing/querier.go b/x/slashing/querier.go index ebebb9162370..5a1a4d5c493e 100644 --- a/x/slashing/querier.go +++ b/x/slashing/querier.go @@ -36,16 +36,6 @@ func queryParams(ctx sdk.Context, k Keeper) ([]byte, sdk.Error) { return res, nil } -// QuerySigningInfoParams defines the params for the following queries: -// - 'custom/slashing/signingInfo' -type QuerySigningInfoParams struct { - ConsAddress sdk.ConsAddress -} - -func NewQuerySigningInfoParams(consAddr sdk.ConsAddress) QuerySigningInfoParams { - return QuerySigningInfoParams{consAddr} -} - func querySigningInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { var params QuerySigningInfoParams @@ -67,16 +57,6 @@ func querySigningInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, return res, nil } -// QuerySigningInfosParams defines the params for the following queries: -// - 'custom/slashing/signingInfos' -type QuerySigningInfosParams struct { - Page, Limit int -} - -func NewQuerySigningInfosParams(page, limit int) QuerySigningInfosParams { - return QuerySigningInfosParams{page, limit} -} - func querySigningInfos(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { var params QuerySigningInfosParams diff --git a/x/slashing/types/keys.go b/x/slashing/types/keys.go index 0b4f291f64e8..2051e8f14dd5 100644 --- a/x/slashing/types/keys.go +++ b/x/slashing/types/keys.go @@ -8,6 +8,8 @@ import ( // nolint const ( + ModuleName = "slashing" + // StoreKey is the store key string for slashing StoreKey = ModuleName @@ -70,6 +72,7 @@ func GetValidatorSlashingPeriodKey(v sdk.ConsAddress, startHeight int64) []byte return append(GetValidatorSlashingPeriodPrefix(v), b...) } -func getAddrPubkeyRelationKey(address []byte) []byte { +// TODO +func GetAddrPubkeyRelationKey(address []byte) []byte { return append(AddrPubkeyRelationKey, address...) } diff --git a/x/slashing/types/querier.go b/x/slashing/types/querier.go new file mode 100644 index 000000000000..d8850b0b2678 --- /dev/null +++ b/x/slashing/types/querier.go @@ -0,0 +1,25 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// QuerySigningInfoParams defines the params for the following queries: +// - 'custom/slashing/signingInfo' +type QuerySigningInfoParams struct { + ConsAddress sdk.ConsAddress +} + +func NewQuerySigningInfoParams(consAddr sdk.ConsAddress) QuerySigningInfoParams { + return QuerySigningInfoParams{consAddr} +} + +// QuerySigningInfosParams defines the params for the following queries: +// - 'custom/slashing/signingInfos' +type QuerySigningInfosParams struct { + Page, Limit int +} + +func NewQuerySigningInfosParams(page, limit int) QuerySigningInfosParams { + return QuerySigningInfosParams{page, limit} +} diff --git a/x/staking/client/cli/query.go b/x/staking/client/cli/query.go index b1548af4a00d..0c08cfded655 100644 --- a/x/staking/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -22,19 +22,19 @@ func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { Short: "Querying commands for the staking module", } stakingQueryCmd.AddCommand(client.GetCommands( - GetCmdQueryDelegation(mc.storeKey, mc.cdc), - GetCmdQueryDelegations(mc.storeKey, mc.cdc), - GetCmdQueryUnbondingDelegation(mc.storeKey, mc.cdc), - GetCmdQueryUnbondingDelegations(mc.storeKey, mc.cdc), - GetCmdQueryRedelegation(mc.storeKey, mc.cdc), - GetCmdQueryRedelegations(mc.storeKey, mc.cdc), - GetCmdQueryValidator(mc.storeKey, mc.cdc), - GetCmdQueryValidators(mc.storeKey, mc.cdc), - GetCmdQueryValidatorDelegations(mc.storeKey, mc.cdc), - GetCmdQueryValidatorUnbondingDelegations(mc.storeKey, mc.cdc), - GetCmdQueryValidatorRedelegations(mc.storeKey, mc.cdc), - GetCmdQueryParams(mc.storeKey, mc.cdc), - GetCmdQueryPool(mc.storeKey, mc.cdc))...) + GetCmdQueryDelegation(storeKey, cdc), + GetCmdQueryDelegations(storeKey, cdc), + GetCmdQueryUnbondingDelegation(storeKey, cdc), + GetCmdQueryUnbondingDelegations(storeKey, cdc), + GetCmdQueryRedelegation(storeKey, cdc), + GetCmdQueryRedelegations(storeKey, cdc), + GetCmdQueryValidator(storeKey, cdc), + GetCmdQueryValidators(storeKey, cdc), + GetCmdQueryValidatorDelegations(storeKey, cdc), + GetCmdQueryValidatorUnbondingDelegations(storeKey, cdc), + GetCmdQueryValidatorRedelegations(storeKey, cdc), + GetCmdQueryParams(storeKey, cdc), + GetCmdQueryPool(storeKey, cdc))...) return stakingQueryCmd diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index c091dce8ad12..acf15bec0b11 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -31,11 +31,11 @@ func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command { } stakingTxCmd.AddCommand(client.PostCommands( - GetCmdCreateValidator(mc.cdc), - GetCmdEditValidator(mc.cdc), - GetCmdDelegate(mc.cdc), - GetCmdRedelegate(mc.storeKey, mc.cdc), - GetCmdUnbond(mc.storeKey, mc.cdc), + GetCmdCreateValidator(cdc), + GetCmdEditValidator(cdc), + GetCmdDelegate(cdc), + GetCmdRedelegate(storeKey, cdc), + GetCmdUnbond(storeKey, cdc), )...) return stakingTxCmd diff --git a/x/staking/client/rest/query.go b/x/staking/client/rest/query.go index bee61a2c8f3a..869f1b0ab295 100644 --- a/x/staking/client/rest/query.go +++ b/x/staking/client/rest/query.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" + "github.com/cosmos/cosmos-sdk/x/staking/querier" "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/gorilla/mux" @@ -103,7 +104,7 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Co // HTTP request handler to query a delegator delegations func delegatorDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryDelegator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegatorDelegations)) + return queryDelegator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, querier.QueryDelegatorDelegations)) } // HTTP request handler to query a delegator unbonding delegations @@ -178,7 +179,7 @@ func unbondingDelegationHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) h // HTTP request handler to query redelegations func redelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var params types.QueryRedelegationParams + var params querier.QueryRedelegationParams bechDelegatorAddr := r.URL.Query().Get("delegator") bechSrcValidatorAddr := r.URL.Query().Get("validator_from") @@ -228,7 +229,7 @@ func redelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Ha // HTTP request handler to query a delegation func delegationHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryBonds(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegation)) + return queryBonds(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, querier.QueryDelegation)) } // HTTP request handler to query all delegator bonded validators @@ -255,14 +256,14 @@ func validatorsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Handl status = sdk.BondStatusBonded } - params := types.NewQueryValidatorsParams(page, limit, status) + params := querier.NewQueryValidatorsParams(page, limit, status) bz, err := cdc.MarshalJSON(params) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryValidators) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, querier.QueryValidators) res, err := cliCtx.QueryWithData(route, bz) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -279,7 +280,7 @@ func validatorHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Handle // HTTP request handler to query all unbonding delegations from a validator func validatorDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryValidator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryValidatorDelegations)) + return queryValidator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, querier.QueryValidatorDelegations)) } // HTTP request handler to query all unbonding delegations from a validator diff --git a/x/staking/client/rest/rest.go b/x/staking/client/rest/rest.go index d06cd719df20..d3bfc07350b9 100644 --- a/x/staking/client/rest/rest.go +++ b/x/staking/client/rest/rest.go @@ -5,11 +5,10 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" ) // RegisterRoutes registers staking-related REST handlers to a router -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, kb keys.Keybase) { +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { registerQueryRoutes(cliCtx, r, cdc) - registerTxRoutes(cliCtx, r, cdc, kb) + registerTxRoutes(cliCtx, r, cdc) } diff --git a/x/staking/client/rest/tx.go b/x/staking/client/rest/tx.go index 565cbae6afcf..84b7e4750bbc 100644 --- a/x/staking/client/rest/tx.go +++ b/x/staking/client/rest/tx.go @@ -9,24 +9,23 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" clientrest "github.com/cosmos/cosmos-sdk/client/rest" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/staking/types" ) -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, kb keys.Keybase) { +func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { r.HandleFunc( "/staking/delegators/{delegatorAddr}/delegations", - postDelegationsHandlerFn(cdc, kb, cliCtx), + postDelegationsHandlerFn(cdc, cliCtx), ).Methods("POST") r.HandleFunc( "/staking/delegators/{delegatorAddr}/unbonding_delegations", - postUnbondingDelegationsHandlerFn(cdc, kb, cliCtx), + postUnbondingDelegationsHandlerFn(cdc, cliCtx), ).Methods("POST") r.HandleFunc( "/staking/delegators/{delegatorAddr}/redelegations", - postRedelegationsHandlerFn(cdc, kb, cliCtx), + postRedelegationsHandlerFn(cdc, cliCtx), ).Methods("POST") } @@ -57,7 +56,7 @@ type ( } ) -func postDelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { +func postDelegationsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req DelegateRequest @@ -91,7 +90,7 @@ func postDelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context. } } -func postRedelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { +func postRedelegationsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req RedelegateRequest @@ -125,7 +124,7 @@ func postRedelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx contex } } -func postUnbondingDelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { +func postUnbondingDelegationsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req UndelegateRequest diff --git a/x/staking/client/rest/utils.go b/x/staking/client/rest/utils.go index d5ad533814f0..21f391dc4d41 100644 --- a/x/staking/client/rest/utils.go +++ b/x/staking/client/rest/utils.go @@ -11,8 +11,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" + "github.com/cosmos/cosmos-sdk/x/staking/querier" "github.com/cosmos/cosmos-sdk/x/staking/tags" - "github.com/cosmos/cosmos-sdk/x/staking/types" ) // contains checks if the a given query contains one of the tx types @@ -50,7 +50,7 @@ func queryBonds(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string) ht return } - params := types.NewQueryBondsParams(delegatorAddr, validatorAddr) + params := querier.NewQueryBondsParams(delegatorAddr, validatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -78,7 +78,7 @@ func queryDelegator(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string return } - params := types.NewQueryDelegatorParams(delegatorAddr) + params := querier.NewQueryDelegatorParams(delegatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -106,7 +106,7 @@ func queryValidator(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string return } - params := types.NewQueryValidatorParams(validatorAddr) + params := querier.NewQueryValidatorParams(validatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { diff --git a/x/staking/module.go b/x/staking/module.go index 3876f7ca5251..f77c87757616 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -3,6 +3,7 @@ package staking import ( "encoding/json" + "github.com/gorilla/mux" "github.com/spf13/cobra" flag "github.com/spf13/pflag" @@ -13,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" "github.com/cosmos/cosmos-sdk/x/staking/client/cli" "github.com/cosmos/cosmos-sdk/x/staking/client/rest" @@ -20,14 +22,14 @@ import ( ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) // app module basics object type AppModuleBasic struct{} -var _ sdk.AppModuleBasic = AppModuleBasic{} +var _ module.AppModuleBasic = AppModuleBasic{} // module name func (AppModuleBasic) Name() string { @@ -56,17 +58,17 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { // register rest routes func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { - rest.RegisterRoutes(ctx, rtr, cdc, StoreKey) + rest.RegisterRoutes(ctx, rtr, cdc) } // get the root tx command of this module func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd(moduleCdc, StoreKey) + return cli.GetTxCmd(StoreKey, ModuleCdc) } // get the root query command of this module func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(moduleCdc, StoreKey) + return cli.GetQueryCmd(StoreKey, ModuleCdc) } //_____________________________________ diff --git a/x/staking/types/expected_keepers.go b/x/staking/types/expected_keepers.go index 430a36905862..e3a799f9d3d7 100644 --- a/x/staking/types/expected_keepers.go +++ b/x/staking/types/expected_keepers.go @@ -2,7 +2,7 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) // expected coin keeper @@ -24,5 +24,5 @@ type BankKeeper interface { // expected bank keeper type AccountKeeper interface { - IterateAccounts(ctx sdk.Context, process func(auth.Account) (stop bool)) + IterateAccounts(ctx sdk.Context, process func(types.Account) (stop bool)) } From f6decfbed0a787bfbc3bb6c03b3e2013554fddb3 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 31 May 2019 13:58:27 -0400 Subject: [PATCH 08/23] resolve all compile errors --- simapp/app.go | 24 +- types/module/module.go | 4 +- types/module/module_test.go | 2 +- x/auth/alias.go | 7 + x/auth/ante_test.go | 247 +++++++++--------- x/auth/genaccounts/codec.go | 7 +- x/auth/querier_test.go | 2 +- x/auth/{test_utils.go => test_common.go} | 0 x/auth/types/account_test.go | 30 +-- x/auth/types/stdtx_test.go | 28 +- .../types/{test_utils.go => test_common.go} | 18 +- x/crisis/types/codec.go | 2 +- x/distribution/module.go | 4 +- x/distribution/types/codec.go | 9 +- x/genutil/client/cli/init_test.go | 2 +- x/genutil/codec.go | 18 +- x/gov/module.go | 2 +- x/gov/types/codec.go | 1 + x/mint/alias.go | 13 +- x/mint/genesis.go | 4 +- x/mint/keeper.go | 4 +- x/mint/module.go | 15 +- x/mint/test_common.go | 12 +- x/mint/types/codec.go | 2 +- x/mint/types/keys.go | 3 +- x/mint/{ => types}/minter.go | 5 +- x/mint/{ => types}/minter_test.go | 2 +- x/mint/types/params.go | 3 +- x/params/client/cli/tx.go | 12 +- x/params/types/codec.go | 6 +- x/slashing/abci_app.go | 4 +- x/slashing/alias.go | 89 +++++++ x/slashing/genesis.go | 21 +- x/slashing/handler.go | 3 +- x/slashing/{keeper => }/hooks.go | 2 +- x/slashing/{keeper => }/keeper.go | 6 +- x/slashing/{keeper => }/keeper_test.go | 46 ++-- x/slashing/module.go | 14 +- x/slashing/{keeper => }/params.go | 2 +- x/slashing/querier.go | 10 +- x/slashing/{keeper => }/signing_info.go | 2 +- x/slashing/{keeper => }/signing_info_test.go | 2 +- x/slashing/types/codec.go | 10 +- x/slashing/types/msg.go | 2 +- x/staking/types/codec.go | 9 +- 45 files changed, 407 insertions(+), 303 deletions(-) rename x/auth/{test_utils.go => test_common.go} (100%) rename x/auth/types/{test_utils.go => test_common.go} (87%) rename x/mint/{ => types}/minter.go (97%) rename x/mint/{ => types}/minter_test.go (99%) create mode 100644 x/slashing/alias.go rename x/slashing/{keeper => }/hooks.go (99%) rename x/slashing/{keeper => }/keeper.go (98%) rename x/slashing/{keeper => }/keeper_test.go (91%) rename x/slashing/{keeper => }/params.go (98%) rename x/slashing/{keeper => }/signing_info.go (99%) rename x/slashing/{keeper => }/signing_info_test.go (98%) diff --git a/simapp/app.go b/simapp/app.go index 7666988ae571..9173c3f5d3e0 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -4,9 +4,15 @@ import ( "io" "os" + abci "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" + bam "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/genaccounts" @@ -17,13 +23,9 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/params" + paramscli "github.com/cosmos/cosmos-sdk/x/params/client/cli" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/staking" - - abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" ) const appName = "SimApp" @@ -35,14 +37,14 @@ var ( // default home directories for the application daemon DefaultNodeHome = os.ExpandEnv("$HOME/.simapp") - // The ModuleBasicManager is in charge of setting up basic, + // The module BasicManager is in charge of setting up basic, // non-dependant module elements, such as codec registration // and genesis verification. - ModuleBasics sdk.ModuleBasicManager + ModuleBasics module.BasicManager ) func init() { - ModuleBasics = sdk.NewModuleBasicManager( + ModuleBasics = module.NewBasicManager( genaccounts.AppModuleBasic{}, genutil.AppModuleBasic{}, auth.AppModuleBasic{}, @@ -50,7 +52,7 @@ func init() { staking.AppModuleBasic{}, mint.AppModuleBasic{}, distr.AppModuleBasic{}, - gov.NewAppModuleBasic(paramcli.GetCmdSubmitProposal()), + gov.NewAppModuleBasic(paramscli.GetCmdSubmitProposal()), params.AppModuleBasic{}, crisis.AppModuleBasic{}, slashing.AppModuleBasic{}, @@ -100,7 +102,7 @@ type SimApp struct { paramsKeeper params.Keeper // the module manager - mm *sdk.ModuleManager + mm *module.Manager } // NewSimApp returns a reference to an initialized SimApp. @@ -169,7 +171,7 @@ func NewSimApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bo app.stakingKeeper = *stakingKeeper.SetHooks( staking.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks())) - app.mm = sdk.NewModuleManager( + app.mm = module.NewManager( genaccounts.NewAppModule(app.accountKeeper), genutil.NewAppModule(app.accountKeeper, app.stakingKeeper, app.BaseApp.DeliverTx), auth.NewAppModule(app.accountKeeper, app.feeCollectionKeeper), diff --git a/types/module/module.go b/types/module/module.go index ed052e067de4..bfa8d68ea7e2 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -52,7 +52,7 @@ type AppModuleBasic interface { // collections of AppModuleBasic type BasicManager []AppModuleBasic -func NewModuleBasicManager(modules ...AppModuleBasic) BasicManager { +func NewBasicManager(modules ...AppModuleBasic) BasicManager { return modules } @@ -184,7 +184,7 @@ type Manager struct { } // NewModuleManager creates a new Manager object -func NewModuleManager(modules ...AppModule) *Manager { +func NewManager(modules ...AppModule) *Manager { moduleMap := make(map[string]AppModule) var modulesStr []string diff --git a/types/module/module_test.go b/types/module/module_test.go index afcc3f4afb2c..4f24de5a185a 100644 --- a/types/module/module_test.go +++ b/types/module/module_test.go @@ -8,7 +8,7 @@ import ( ) func TestSetOrderBeginBlockers(t *testing.T) { - mm := NewModuleManager() + mm := NewManager() mm.SetOrderBeginBlockers("a", "b", "c") obb := mm.OrderBeginBlockers require.Equal(t, 3, len(obb)) diff --git a/x/auth/alias.go b/x/auth/alias.go index dd2c8c35ad9d..c2471b10d3a6 100644 --- a/x/auth/alias.go +++ b/x/auth/alias.go @@ -49,6 +49,13 @@ var ( StdSignBytes = types.StdSignBytes DefaultTxDecoder = types.DefaultTxDecoder DefaultTxEncoder = types.DefaultTxEncoder + NewTestMsg = types.NewTestMsg + NewTestStdFee = types.NewTestStdFee + NewTestCoins = types.NewTestCoins + KeyTestPubAddr = types.KeyTestPubAddr + NewTestTx = types.NewTestTx + NewTestTxWithMemo = types.NewTestTxWithMemo + NewTestTxWithSignBytes = types.NewTestTxWithSignBytes // variable aliases ModuleCdc = types.ModuleCdc diff --git a/x/auth/ante_test.go b/x/auth/ante_test.go index ae992408a7a8..f0c3125144ff 100644 --- a/x/auth/ante_test.go +++ b/x/auth/ante_test.go @@ -51,21 +51,21 @@ func TestAnteHandlerSigErrors(t *testing.T) { anteHandler := NewAnteHandler(input.ak, input.fck, DefaultSigVerificationGasConsumer) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() - priv3, _, addr3 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() + priv3, _, addr3 := KeyTestPubAddr() // msg and signatures var tx sdk.Tx - msg1 := newTestMsg(addr1, addr2) - msg2 := newTestMsg(addr1, addr3) - fee := newStdFee() + msg1 := NewTestMsg(addr1, addr2) + msg2 := NewTestMsg(addr1, addr3) + fee := NewTestStdFee() msgs := []sdk.Msg{msg1, msg2} // test no signatures privs, accNums, seqs := []crypto.PrivKey{}, []uint64{}, []uint64{} - tx = newTestTx(ctx, msgs, privs, accNums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accNums, seqs, fee) // tx.GetSigners returns addresses in correct order: addr1, addr2, addr3 expectedSigners := []sdk.AccAddress{addr1, addr2, addr3} @@ -77,12 +77,12 @@ func TestAnteHandlerSigErrors(t *testing.T) { // test num sigs dont match GetSigners privs, accNums, seqs = []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = newTestTx(ctx, msgs, privs, accNums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accNums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // test an unrecognized account privs, accNums, seqs = []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0} - tx = newTestTx(ctx, msgs, privs, accNums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accNums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnknownAddress) // save the first account, but second is still unrecognized @@ -100,50 +100,50 @@ func TestAnteHandlerAccountNumbers(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc1.SetCoins(newCoins()) + acc1.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) - acc2.SetCoins(newCoins()) + acc2.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc2) // msg and signatures var tx sdk.Tx - msg := newTestMsg(addr1) - fee := newStdFee() + msg := NewTestMsg(addr1) + fee := NewTestStdFee() msgs := []sdk.Msg{msg} // test good tx from one signer privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) // new tx from wrong account number seqs = []uint64{1} - tx = newTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // from correct account number seqs = []uint64{1} - tx = newTestTx(ctx, msgs, privs, []uint64{0}, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, []uint64{0}, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) // new tx with another signer and incorrect account numbers - msg1 := newTestMsg(addr1, addr2) - msg2 := newTestMsg(addr2, addr1) + msg1 := NewTestMsg(addr1, addr2) + msg2 := NewTestMsg(addr2, addr1) msgs = []sdk.Msg{msg1, msg2} privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{1, 0}, []uint64{2, 0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // correct account numbers privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{2, 0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) } @@ -155,50 +155,50 @@ func TestAnteHandlerAccountNumbersAtBlockHeightZero(t *testing.T) { ctx := input.ctx.WithBlockHeight(0) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc1.SetCoins(newCoins()) + acc1.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) - acc2.SetCoins(newCoins()) + acc2.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc2) // msg and signatures var tx sdk.Tx - msg := newTestMsg(addr1) - fee := newStdFee() + msg := NewTestMsg(addr1) + fee := NewTestStdFee() msgs := []sdk.Msg{msg} // test good tx from one signer privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) // new tx from wrong account number seqs = []uint64{1} - tx = newTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // from correct account number seqs = []uint64{1} - tx = newTestTx(ctx, msgs, privs, []uint64{0}, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, []uint64{0}, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) // new tx with another signer and incorrect account numbers - msg1 := newTestMsg(addr1, addr2) - msg2 := newTestMsg(addr2, addr1) + msg1 := NewTestMsg(addr1, addr2) + msg2 := NewTestMsg(addr2, addr1) msgs = []sdk.Msg{msg1, msg2} privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{1, 0}, []uint64{2, 0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // correct account numbers privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 0}, []uint64{2, 0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) } @@ -210,31 +210,31 @@ func TestAnteHandlerSequences(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() - priv3, _, addr3 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() + priv3, _, addr3 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc1.SetCoins(newCoins()) + acc1.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) - acc2.SetCoins(newCoins()) + acc2.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc2) acc3 := input.ak.NewAccountWithAddress(ctx, addr3) - acc3.SetCoins(newCoins()) + acc3.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc3) // msg and signatures var tx sdk.Tx - msg := newTestMsg(addr1) - fee := newStdFee() + msg := NewTestMsg(addr1) + fee := NewTestStdFee() msgs := []sdk.Msg{msg} // test good tx from one signer privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) // test sending it again fails (replay protection) @@ -242,37 +242,37 @@ func TestAnteHandlerSequences(t *testing.T) { // fix sequence, should pass seqs = []uint64{1} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) // new tx with another signer and correct sequences - msg1 := newTestMsg(addr1, addr2) - msg2 := newTestMsg(addr3, addr1) + msg1 := NewTestMsg(addr1, addr2) + msg2 := NewTestMsg(addr3, addr1) msgs = []sdk.Msg{msg1, msg2} privs, accnums, seqs = []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{2, 0, 0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) // replay fails checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // tx from just second signer with incorrect sequence fails - msg = newTestMsg(addr2) + msg = NewTestMsg(addr2) msgs = []sdk.Msg{msg} privs, accnums, seqs = []crypto.PrivKey{priv2}, []uint64{1}, []uint64{0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // fix the sequence and it passes - tx = newTestTx(ctx, msgs, []crypto.PrivKey{priv2}, []uint64{1}, []uint64{1}, fee) + tx = NewTestTx(ctx, msgs, []crypto.PrivKey{priv2}, []uint64{1}, []uint64{1}, fee) checkValidTx(t, anteHandler, ctx, tx, false) // another tx from both of them that passes - msg = newTestMsg(addr1, addr2) + msg = NewTestMsg(addr1, addr2) msgs = []sdk.Msg{msg} privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{3, 2} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) } @@ -284,7 +284,7 @@ func TestAnteHandlerFees(t *testing.T) { anteHandler := NewAnteHandler(input.ak, input.fck, DefaultSigVerificationGasConsumer) // keys and addresses - priv1, _, addr1 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) @@ -292,19 +292,20 @@ func TestAnteHandlerFees(t *testing.T) { // msg and signatures var tx sdk.Tx - msg := newTestMsg(addr1) + msg := NewTestMsg(addr1) privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - fee := newStdFee() + fee := NewTestStdFee() msgs := []sdk.Msg{msg} // signer does not have enough funds to pay the fee - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInsufficientFunds) acc1.SetCoins(sdk.NewCoins(sdk.NewInt64Coin("atom", 149))) input.ak.SetAccount(ctx, acc1) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInsufficientFunds) + emptyCoins := sdk.NewCoins() require.True(t, input.fck.GetCollectedFees(ctx).IsEqual(emptyCoins)) require.True(t, input.ak.GetAccount(ctx, addr1).GetCoins().AmountOf("atom").Equal(sdk.NewInt(149))) @@ -324,7 +325,7 @@ func TestAnteHandlerMemoGas(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) @@ -332,27 +333,27 @@ func TestAnteHandlerMemoGas(t *testing.T) { // msg and signatures var tx sdk.Tx - msg := newTestMsg(addr1) + msg := NewTestMsg(addr1) privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} fee := NewStdFee(0, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) // tx does not have enough gas - tx = newTestTx(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeOutOfGas) // tx with memo doesn't have enough gas fee = NewStdFee(801, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) - tx = newTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, "abcininasidniandsinasindiansdiansdinaisndiasndiadninsd") + tx = NewTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, "abcininasidniandsinasindiansdiansdinaisndiasndiadninsd") checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeOutOfGas) // memo too large fee = NewStdFee(9000, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) - tx = newTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("01234567890", 500)) + tx = NewTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("01234567890", 500)) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeMemoTooLarge) // tx with memo has enough gas fee = NewStdFee(9000, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) - tx = newTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("0123456789", 10)) + tx = NewTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("0123456789", 10)) checkValidTx(t, anteHandler, ctx, tx, false) } @@ -363,43 +364,43 @@ func TestAnteHandlerMultiSigner(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() - priv3, _, addr3 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() + priv3, _, addr3 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc1.SetCoins(newCoins()) + acc1.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) - acc2.SetCoins(newCoins()) + acc2.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc2) acc3 := input.ak.NewAccountWithAddress(ctx, addr3) - acc3.SetCoins(newCoins()) + acc3.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc3) // set up msgs and fee var tx sdk.Tx - msg1 := newTestMsg(addr1, addr2) - msg2 := newTestMsg(addr3, addr1) - msg3 := newTestMsg(addr2, addr3) + msg1 := NewTestMsg(addr1, addr2) + msg2 := NewTestMsg(addr3, addr1) + msg3 := NewTestMsg(addr2, addr3) msgs := []sdk.Msg{msg1, msg2, msg3} - fee := newStdFee() + fee := NewTestStdFee() // signers in order privs, accnums, seqs := []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0} - tx = newTestTxWithMemo(ctx, msgs, privs, accnums, seqs, fee, "Check signers are in expected order and different account numbers works") + tx = NewTestTxWithMemo(ctx, msgs, privs, accnums, seqs, fee, "Check signers are in expected order and different account numbers works") checkValidTx(t, anteHandler, ctx, tx, false) // change sequence numbers - tx = newTestTx(ctx, []sdk.Msg{msg1}, []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{1, 1}, fee) + tx = NewTestTx(ctx, []sdk.Msg{msg1}, []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{1, 1}, fee) checkValidTx(t, anteHandler, ctx, tx, false) - tx = newTestTx(ctx, []sdk.Msg{msg2}, []crypto.PrivKey{priv3, priv1}, []uint64{2, 0}, []uint64{1, 2}, fee) + tx = NewTestTx(ctx, []sdk.Msg{msg2}, []crypto.PrivKey{priv3, priv1}, []uint64{2, 0}, []uint64{1, 2}, fee) checkValidTx(t, anteHandler, ctx, tx, false) // expected seqs = [3, 2, 2] - tx = newTestTxWithMemo(ctx, msgs, privs, accnums, []uint64{3, 2, 2}, fee, "Check signers are in expected order and different account numbers and sequence numbers works") + tx = NewTestTxWithMemo(ctx, msgs, privs, accnums, []uint64{3, 2, 2}, fee, "Check signers are in expected order and different account numbers and sequence numbers works") checkValidTx(t, anteHandler, ctx, tx, false) } @@ -410,29 +411,29 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc1.SetCoins(newCoins()) + acc1.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) - acc2.SetCoins(newCoins()) + acc2.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc2) var tx sdk.Tx - msg := newTestMsg(addr1) + msg := NewTestMsg(addr1) msgs := []sdk.Msg{msg} - fee := newStdFee() - fee2 := newStdFee() + fee := NewTestStdFee() + fee2 := NewTestStdFee() fee2.Gas += 100 - fee3 := newStdFee() + fee3 := NewTestStdFee() fee3.Amount[0].Amount = fee3.Amount[0].Amount.AddRaw(100) // test good tx and signBytes privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) chainID := ctx.ChainID() @@ -450,14 +451,14 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { {chainID2, 0, 1, fee, msgs, codeUnauth}, // test wrong chain_id {chainID, 0, 2, fee, msgs, codeUnauth}, // test wrong seqs {chainID, 1, 1, fee, msgs, codeUnauth}, // test wrong accnum - {chainID, 0, 1, fee, []sdk.Msg{newTestMsg(addr2)}, codeUnauth}, // test wrong msg + {chainID, 0, 1, fee, []sdk.Msg{NewTestMsg(addr2)}, codeUnauth}, // test wrong msg {chainID, 0, 1, fee2, msgs, codeUnauth}, // test wrong fee {chainID, 0, 1, fee3, msgs, codeUnauth}, // test wrong fee } privs, seqs = []crypto.PrivKey{priv1}, []uint64{1} for _, cs := range cases { - tx := newTestTxWithSignBytes( + tx := NewTestTxWithSignBytes( msgs, privs, accnums, seqs, fee, StdSignBytes(cs.chainID, cs.accnum, cs.seq, cs.fee, cs.msgs, ""), "", @@ -467,14 +468,14 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { // test wrong signer if public key exist privs, accnums, seqs = []crypto.PrivKey{priv2}, []uint64{0}, []uint64{1} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // test wrong signer if public doesn't exist - msg = newTestMsg(addr2) + msg = NewTestMsg(addr2) msgs = []sdk.Msg{msg} privs, accnums, seqs = []crypto.PrivKey{priv1}, []uint64{1}, []uint64{0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInvalidPubKey) } @@ -485,34 +486,34 @@ func TestAnteHandlerSetPubKey(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := keyPubAddr() - _, _, addr2 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + _, _, addr2 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc1.SetCoins(newCoins()) + acc1.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) - acc2.SetCoins(newCoins()) + acc2.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc2) var tx sdk.Tx // test good tx and set public key - msg := newTestMsg(addr1) + msg := NewTestMsg(addr1) msgs := []sdk.Msg{msg} privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - fee := newStdFee() - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + fee := NewTestStdFee() + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) acc1 = input.ak.GetAccount(ctx, addr1) require.Equal(t, acc1.GetPubKey(), priv1.PubKey()) // test public key not found - msg = newTestMsg(addr2) + msg = NewTestMsg(addr2) msgs = []sdk.Msg{msg} - tx = newTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) sigs := tx.(types.StdTx).GetSignatures() sigs[0].PubKey = nil checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInvalidPubKey) @@ -521,7 +522,7 @@ func TestAnteHandlerSetPubKey(t *testing.T) { require.Nil(t, acc2.GetPubKey()) // test invalid signature and public key - tx = newTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInvalidPubKey) acc2 = input.ak.GetAccount(ctx, addr2) @@ -533,8 +534,8 @@ func TestProcessPubKey(t *testing.T) { ctx := input.ctx // keys - _, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() + _, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() acc1 := input.ak.NewAccountWithAddress(ctx, addr1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) @@ -679,32 +680,32 @@ func TestAnteHandlerSigLimitExceeded(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() - priv3, _, addr3 := keyPubAddr() - priv4, _, addr4 := keyPubAddr() - priv5, _, addr5 := keyPubAddr() - priv6, _, addr6 := keyPubAddr() - priv7, _, addr7 := keyPubAddr() - priv8, _, addr8 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() + priv3, _, addr3 := KeyTestPubAddr() + priv4, _, addr4 := KeyTestPubAddr() + priv5, _, addr5 := KeyTestPubAddr() + priv6, _, addr6 := KeyTestPubAddr() + priv7, _, addr7 := KeyTestPubAddr() + priv8, _, addr8 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc1.SetCoins(newCoins()) + acc1.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) - acc2.SetCoins(newCoins()) + acc2.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc2) var tx sdk.Tx - msg := newTestMsg(addr1, addr2, addr3, addr4, addr5, addr6, addr7, addr8) + msg := NewTestMsg(addr1, addr2, addr3, addr4, addr5, addr6, addr7, addr8) msgs := []sdk.Msg{msg} - fee := newStdFee() + fee := NewTestStdFee() // test rejection logic privs, accnums, seqs := []crypto.PrivKey{priv1, priv2, priv3, priv4, priv5, priv6, priv7, priv8}, []uint64{0, 0, 0, 0, 0, 0, 0, 0}, []uint64{0, 0, 0, 0, 0, 0, 0, 0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeTooManySignatures) } @@ -775,16 +776,16 @@ func TestCustomSignatureVerificationGasConsumer(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // verify that an secp256k1 account gets rejected - priv1, _, addr1 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() acc1 := input.ak.NewAccountWithAddress(ctx, addr1) _ = acc1.SetCoins(sdk.NewCoins(sdk.NewInt64Coin("atom", 150))) input.ak.SetAccount(ctx, acc1) var tx sdk.Tx - msg := newTestMsg(addr1) + msg := NewTestMsg(addr1) privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - fee := newStdFee() + fee := NewTestStdFee() msgs := []sdk.Msg{msg} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInvalidPubKey) // verify that an ed25519 account gets accepted @@ -794,10 +795,10 @@ func TestCustomSignatureVerificationGasConsumer(t *testing.T) { acc2 := input.ak.NewAccountWithAddress(ctx, addr2) _ = acc2.SetCoins(sdk.NewCoins(sdk.NewInt64Coin("atom", 150))) input.ak.SetAccount(ctx, acc2) - msg = newTestMsg(addr2) + msg = NewTestMsg(addr2) privs, accnums, seqs = []crypto.PrivKey{priv2}, []uint64{1}, []uint64{0} - fee = newStdFee() + fee = NewTestStdFee() msgs = []sdk.Msg{msg} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) } diff --git a/x/auth/genaccounts/codec.go b/x/auth/genaccounts/codec.go index ccdc8b19e553..184bfc94c168 100644 --- a/x/auth/genaccounts/codec.go +++ b/x/auth/genaccounts/codec.go @@ -5,10 +5,9 @@ import ( ) // generic sealed codec to be used throughout this module -var moduleCdc *codec.Codec +var moduleCdc = codec.New() func init() { - cdc := codec.New() - codec.RegisterCrypto(cdc) - moduleCdc = cdc.Seal() + codec.RegisterCrypto(moduleCdc) + moduleCdc.Seal() } diff --git a/x/auth/querier_test.go b/x/auth/querier_test.go index 6d9ec0e9630a..72e60b20868d 100644 --- a/x/auth/querier_test.go +++ b/x/auth/querier_test.go @@ -24,7 +24,7 @@ func Test_queryAccount(t *testing.T) { require.NotNil(t, err) require.Nil(t, res) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() req.Data = input.cdc.MustMarshalJSON(NewQueryAccountParams(addr)) res, err = queryAccount(input.ctx, req, input.ak) require.NotNil(t, err) diff --git a/x/auth/test_utils.go b/x/auth/test_common.go similarity index 100% rename from x/auth/test_utils.go rename to x/auth/test_common.go diff --git a/x/auth/types/account_test.go b/x/auth/types/account_test.go index 726ae08c96ee..581774c86fdd 100644 --- a/x/auth/types/account_test.go +++ b/x/auth/types/account_test.go @@ -18,8 +18,8 @@ var ( ) func TestBaseAddressPubKey(t *testing.T) { - _, pub1, addr1 := keyPubAddr() - _, pub2, addr2 := keyPubAddr() + _, pub1, addr1 := KeyTestPubAddr() + _, pub2, addr2 := KeyTestPubAddr() acc := NewBaseAccountWithAddress(addr1) // check the address (set) and pubkey (not set) @@ -51,7 +51,7 @@ func TestBaseAddressPubKey(t *testing.T) { } func TestBaseAccountCoins(t *testing.T) { - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() acc := NewBaseAccountWithAddress(addr) someCoins := sdk.Coins{sdk.NewInt64Coin("atom", 123), sdk.NewInt64Coin("eth", 246)} @@ -62,7 +62,7 @@ func TestBaseAccountCoins(t *testing.T) { } func TestBaseAccountSequence(t *testing.T) { - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() acc := NewBaseAccountWithAddress(addr) seq := uint64(7) @@ -73,7 +73,7 @@ func TestBaseAccountSequence(t *testing.T) { } func TestBaseAccountMarshal(t *testing.T) { - _, pub, addr := keyPubAddr() + _, pub, addr := KeyTestPubAddr() acc := NewBaseAccountWithAddress(addr) someCoins := sdk.Coins{sdk.NewInt64Coin("atom", 123), sdk.NewInt64Coin("eth", 246)} @@ -109,7 +109,7 @@ func TestGetVestedCoinsContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -136,7 +136,7 @@ func TestGetVestingCoinsContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -159,7 +159,7 @@ func TestSpendableCoinsContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -199,7 +199,7 @@ func TestTrackDelegationContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -246,7 +246,7 @@ func TestTrackUndelegationContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -302,7 +302,7 @@ func TestGetVestedCoinsDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -321,7 +321,7 @@ func TestGetVestingCoinsDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -340,7 +340,7 @@ func TestSpendableCoinsDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -381,7 +381,7 @@ func TestTrackDelegationDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -427,7 +427,7 @@ func TestTrackUndelegationDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) diff --git a/x/auth/types/stdtx_test.go b/x/auth/types/stdtx_test.go index e74c9429d697..d6315d5fb9f7 100644 --- a/x/auth/types/stdtx_test.go +++ b/x/auth/types/stdtx_test.go @@ -21,7 +21,7 @@ var ( func TestStdTx(t *testing.T) { msgs := []sdk.Msg{sdk.NewTestMsg(addr)} - fee := newStdFee() + fee := NewTestStdFee() sigs := []StdSignature{} tx := NewStdTx(msgs, fee, sigs, "") @@ -41,7 +41,7 @@ func TestStdSignBytes(t *testing.T) { msgs []sdk.Msg memo string } - defaultFee := newStdFee() + defaultFee := NewTestStdFee() tests := []struct { args args want string @@ -61,19 +61,19 @@ func TestTxValidateBasic(t *testing.T) { ctx := sdk.NewContext(nil, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() // msg and signatures - msg1 := newTestMsg(addr1, addr2) - fee := newStdFee() + msg1 := NewTestMsg(addr1, addr2) + fee := NewTestStdFee() msgs := []sdk.Msg{msg1} // require to fail validation upon invalid fee - badFee := newStdFee() + badFee := NewTestStdFee() badFee.Amount[0].Amount = sdk.NewInt(-5) - tx := newTestTx(ctx, nil, nil, nil, nil, badFee) + tx := NewTestTx(ctx, nil, nil, nil, nil, badFee) err := tx.ValidateBasic() require.Error(t, err) @@ -81,7 +81,7 @@ func TestTxValidateBasic(t *testing.T) { // require to fail validation when no signatures exist privs, accNums, seqs := []crypto.PrivKey{}, []uint64{}, []uint64{} - tx = newTestTx(ctx, msgs, privs, accNums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accNums, seqs, fee) err = tx.ValidateBasic() require.Error(t, err) @@ -89,16 +89,16 @@ func TestTxValidateBasic(t *testing.T) { // require to fail validation when signatures do not match expected signers privs, accNums, seqs = []crypto.PrivKey{priv1}, []uint64{0, 1}, []uint64{0, 0} - tx = newTestTx(ctx, msgs, privs, accNums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accNums, seqs, fee) err = tx.ValidateBasic() require.Error(t, err) require.Equal(t, sdk.CodeUnauthorized, err.Result().Code) // require to fail with invalid gas supplied - badFee = newStdFee() + badFee = NewTestStdFee() badFee.Gas = 9223372036854775808 - tx = newTestTx(ctx, nil, nil, nil, nil, badFee) + tx = NewTestTx(ctx, nil, nil, nil, nil, badFee) err = tx.ValidateBasic() require.Error(t, err) @@ -106,7 +106,7 @@ func TestTxValidateBasic(t *testing.T) { // require to pass when above criteria are matched privs, accNums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{0, 0} - tx = newTestTx(ctx, msgs, privs, accNums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accNums, seqs, fee) err = tx.ValidateBasic() require.NoError(t, err) @@ -120,7 +120,7 @@ func TestDefaultTxEncoder(t *testing.T) { encoder := DefaultTxEncoder(cdc) msgs := []sdk.Msg{sdk.NewTestMsg(addr)} - fee := newStdFee() + fee := NewTestStdFee() sigs := []StdSignature{} tx := NewStdTx(msgs, fee, sigs, "") diff --git a/x/auth/types/test_utils.go b/x/auth/types/test_common.go similarity index 87% rename from x/auth/types/test_utils.go rename to x/auth/types/test_common.go index 546b74cbd409..c6f4d26b1d62 100644 --- a/x/auth/types/test_utils.go +++ b/x/auth/types/test_common.go @@ -1,4 +1,4 @@ -// nolint +//nolint package types import ( @@ -13,6 +13,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +//DONTCOVER + type testInput struct { cdc *codec.Codec ctx sdk.Context @@ -43,31 +45,31 @@ func setupTestInput() testInput { return testInput{cdc: cdc, ctx: ctx, fck: fck} } -func newTestMsg(addrs ...sdk.AccAddress) *sdk.TestMsg { +func NewTestMsg(addrs ...sdk.AccAddress) *sdk.TestMsg { return sdk.NewTestMsg(addrs...) } -func newStdFee() StdFee { +func NewTestStdFee() StdFee { return NewStdFee(50000, sdk.NewCoins(sdk.NewInt64Coin("atom", 150)), ) } // coins to more than cover the fee -func newCoins() sdk.Coins { +func NewTestCoins() sdk.Coins { return sdk.Coins{ sdk.NewInt64Coin("atom", 10000000), } } -func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { +func KeyTestPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { key := secp256k1.GenPrivKey() pub := key.PubKey() addr := sdk.AccAddress(pub.Address()) return key, pub, addr } -func newTestTx(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee) sdk.Tx { +func NewTestTx(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee) sdk.Tx { sigs := make([]StdSignature, len(privs)) for i, priv := range privs { signBytes := StdSignBytes(ctx.ChainID(), accNums[i], seqs[i], fee, msgs, "") @@ -84,7 +86,7 @@ func newTestTx(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums return tx } -func newTestTxWithMemo(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee, memo string) sdk.Tx { +func NewTestTxWithMemo(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee, memo string) sdk.Tx { sigs := make([]StdSignature, len(privs)) for i, priv := range privs { signBytes := StdSignBytes(ctx.ChainID(), accNums[i], seqs[i], fee, msgs, memo) @@ -101,7 +103,7 @@ func newTestTxWithMemo(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, return tx } -func newTestTxWithSignBytes(msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee, signBytes []byte, memo string) sdk.Tx { +func NewTestTxWithSignBytes(msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee, signBytes []byte, memo string) sdk.Tx { sigs := make([]StdSignature, len(privs)) for i, priv := range privs { sig, err := priv.Sign(signBytes) diff --git a/x/crisis/types/codec.go b/x/crisis/types/codec.go index 520cb3fedbe3..6347228282c4 100644 --- a/x/crisis/types/codec.go +++ b/x/crisis/types/codec.go @@ -10,7 +10,7 @@ func RegisterCodec(cdc *codec.Codec) { } // generic sealed codec to be used throughout module -var ModuleCdc *codec.Codec +var ModuleCdc = codec.New() func init() { RegisterCodec(ModuleCdc) diff --git a/x/distribution/module.go b/x/distribution/module.go index c157c5849101..37169043d872 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -56,12 +56,12 @@ func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router // get the root tx command of this module func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd(StoreKey, moduleCdc) + return cli.GetTxCmd(StoreKey, ModuleCdc) } // get the root query command of this module func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(StoreKey, moduleCdc) + return cli.GetQueryCmd(StoreKey, ModuleCdc) } // app module diff --git a/x/distribution/types/codec.go b/x/distribution/types/codec.go index 269e01c4efbd..95c624dd6ff6 100644 --- a/x/distribution/types/codec.go +++ b/x/distribution/types/codec.go @@ -13,11 +13,10 @@ func RegisterCodec(cdc *codec.Codec) { } // generic sealed codec to be used throughout module -var ModuleCdc *codec.Codec +var ModuleCdc = codec.New() func init() { - cdc := codec.New() - RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - ModuleCdc = cdc.Seal() + RegisterCodec(ModuleCdc) + codec.RegisterCrypto(ModuleCdc) + ModuleCdc.Seal() } diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index 69d8b61c7fc5..242646853279 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -24,7 +24,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/genutil" ) -var testMbm = module.BasicManager(genutil.AppModuleBasic{}) +var testMbm = module.NewBasicManager(genutil.AppModuleBasic{}) func TestInitCmd(t *testing.T) { defer server.SetupViper(t)() diff --git a/x/genutil/codec.go b/x/genutil/codec.go index 80a3f6951ce4..656578a2a64a 100644 --- a/x/genutil/codec.go +++ b/x/genutil/codec.go @@ -8,16 +8,14 @@ import ( ) // generic sealed codec to be used throughout this module -var moduleCdc *codec.Codec +var moduleCdc = codec.New() +// TODO abstract genesis transactions registration back to staking +// required for genesis transactions func init() { - cdc := codec.New() - - // TODO abstract genesis transactions registration back to staking - // required for genesis transactions - staking.RegisterCodec(cdc) - auth.RegisterCodec(cdc) - sdk.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - moduleCdc = cdc.Seal() + staking.RegisterCodec(moduleCdc) + auth.RegisterCodec(moduleCdc) + sdk.RegisterCodec(moduleCdc) + codec.RegisterCrypto(moduleCdc) + moduleCdc.Seal() } diff --git a/x/gov/module.go b/x/gov/module.go index 035c72fe2cb7..e5fb297b0bc5 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -28,7 +28,7 @@ type AppModuleBasic struct { } // NewAppModuleBasic creates a new AppModuleBasic object -func NewAppModuleBasic(proposalCmds []*cobra.Command) AppModuleBasic { +func NewAppModuleBasic(proposalCmds ...*cobra.Command) AppModuleBasic { return AppModuleBasic{ proposalCmds: proposalCmds, } diff --git a/x/gov/types/codec.go b/x/gov/types/codec.go index bec23cce0c5b..32d4900785af 100644 --- a/x/gov/types/codec.go +++ b/x/gov/types/codec.go @@ -27,6 +27,7 @@ func RegisterProposalTypeCodec(o interface{}, name string) { ModuleCdc.RegisterConcrete(o, name, nil) } +// TODO determine a good place to seal this codec func init() { RegisterCodec(ModuleCdc) } diff --git a/x/mint/alias.go b/x/mint/alias.go index 5a4e708f92d4..c285c6a7e182 100644 --- a/x/mint/alias.go +++ b/x/mint/alias.go @@ -20,12 +20,18 @@ const ( var ( // functions aliases - ParamKeyTable = types.ParamKeyTable - NewParams = types.NewParams - DefaultParams = types.DefaultParams + NewMinter = types.NewMinter + InitialMinter = types.InitialMinter + DefaultInitialMinter = types.DefaultInitialMinter + ValidateMinter = types.ValidateMinter + ParamKeyTable = types.ParamKeyTable + NewParams = types.NewParams + DefaultParams = types.DefaultParams + ValidateParams = types.ValidateParams // variable aliases ModuleCdc = types.ModuleCdc + MinterKey = types.MinterKey KeyMintDenom = types.KeyMintDenom KeyInflationRateChange = types.KeyInflationRateChange KeyInflationMax = types.KeyInflationMax @@ -35,5 +41,6 @@ var ( ) type ( + Minter = types.Minter Params = types.Params ) diff --git a/x/mint/genesis.go b/x/mint/genesis.go index c101bdaa7030..a2e66da3ed0e 100644 --- a/x/mint/genesis.go +++ b/x/mint/genesis.go @@ -44,11 +44,11 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) GenesisState { // ValidateGenesis validates the provided genesis state to ensure the // expected invariants holds. func ValidateGenesis(data GenesisState) error { - err := validateParams(data.Params) + err := ValidateParams(data.Params) if err != nil { return err } - err = validateMinter(data.Minter) + err = ValidateMinter(data.Minter) if err != nil { return err } diff --git a/x/mint/keeper.go b/x/mint/keeper.go index b4815923166e..798c64765e09 100644 --- a/x/mint/keeper.go +++ b/x/mint/keeper.go @@ -33,7 +33,7 @@ func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, // get the minter func (k Keeper) GetMinter(ctx sdk.Context) (minter Minter) { store := ctx.KVStore(k.storeKey) - b := store.Get(minterKey) + b := store.Get(MinterKey) if b == nil { panic("stored minter should not have been nil") } @@ -45,7 +45,7 @@ func (k Keeper) GetMinter(ctx sdk.Context) (minter Minter) { func (k Keeper) SetMinter(ctx sdk.Context, minter Minter) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(minter) - store.Set(minterKey, b) + store.Set(MinterKey, b) } //______________________________________________________________________ diff --git a/x/mint/module.go b/x/mint/module.go index 3cad7acce749..adf42d497433 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -21,9 +21,6 @@ var ( _ module.AppModuleBasic = AppModuleBasic{} ) -// name of this module -const ModuleName = "mint" - // app module basics object type AppModuleBasic struct{} @@ -39,13 +36,13 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {} // default genesis state func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return moduleCdc.MustMarshalJSON(DefaultGenesisState()) + return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } // module validate genesis func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) + err := ModuleCdc.UnmarshalJSON(bz, &data) if err != nil { return err } @@ -54,7 +51,7 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { // register rest routes func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { - rest.RegisterRoutes(ctx, rtr, cdc, StoreKey) + rest.RegisterRoutes(ctx, rtr, cdc) } // get the root tx command of this module @@ -64,7 +61,7 @@ func (AppModuleBasic) GetTxCmd() *cobra.Command { // get the root query command of this module func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(moduleCdc) + return cli.GetQueryCmd(ModuleCdc) } //___________________________ @@ -109,7 +106,7 @@ func (am AppModule) NewQuerierHandler() sdk.Querier { // module init-genesis func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState - moduleCdc.MustUnmarshalJSON(data, &genesisState) + ModuleCdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.keeper, genesisState) return []abci.ValidatorUpdate{} } @@ -117,7 +114,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va // module export genesis func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) - return moduleCdc.MustMarshalJSON(gs) + return ModuleCdc.MustMarshalJSON(gs) } // module begin-block diff --git a/x/mint/test_common.go b/x/mint/test_common.go index d3615bdb3db5..71dddc01fc46 100644 --- a/x/mint/test_common.go +++ b/x/mint/test_common.go @@ -49,15 +49,15 @@ func newTestInput(t *testing.T) testInput { err := ms.LoadLatestVersion() require.Nil(t, err) - paramsKeeper := params.NewKeeper(moduleCdc, keyParams, tkeyParams, params.DefaultCodespace) - feeCollectionKeeper := auth.NewFeeCollectionKeeper(moduleCdc, keyFeeCollection) - accountKeeper := auth.NewAccountKeeper(moduleCdc, keyAcc, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) + paramsKeeper := params.NewKeeper(ModuleCdc, keyParams, tkeyParams, params.DefaultCodespace) + feeCollectionKeeper := auth.NewFeeCollectionKeeper(ModuleCdc, keyFeeCollection) + accountKeeper := auth.NewAccountKeeper(ModuleCdc, keyAcc, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) bankKeeper := bank.NewBaseKeeper(accountKeeper, paramsKeeper.Subspace(bank.DefaultParamspace), bank.DefaultCodespace) stakingKeeper := staking.NewKeeper( - moduleCdc, keyStaking, tkeyStaking, bankKeeper, paramsKeeper.Subspace(staking.DefaultParamspace), staking.DefaultCodespace, + ModuleCdc, keyStaking, tkeyStaking, bankKeeper, paramsKeeper.Subspace(staking.DefaultParamspace), staking.DefaultCodespace, ) mintKeeper := NewKeeper( - moduleCdc, keyMint, paramsKeeper.Subspace(DefaultParamspace), &stakingKeeper, feeCollectionKeeper, + ModuleCdc, keyMint, paramsKeeper.Subspace(DefaultParamspace), &stakingKeeper, feeCollectionKeeper, ) ctx := sdk.NewContext(ms, abci.Header{Time: time.Unix(0, 0)}, false, log.NewTMLogger(os.Stdout)) @@ -65,5 +65,5 @@ func newTestInput(t *testing.T) testInput { mintKeeper.SetParams(ctx, DefaultParams()) mintKeeper.SetMinter(ctx, DefaultInitialMinter()) - return testInput{ctx, moduleCdc, mintKeeper} + return testInput{ctx, ModuleCdc, mintKeeper} } diff --git a/x/mint/types/codec.go b/x/mint/types/codec.go index 1d48351a95a0..189205827bf5 100644 --- a/x/mint/types/codec.go +++ b/x/mint/types/codec.go @@ -5,7 +5,7 @@ import ( ) // generic sealed codec to be used throughout this module -var ModuleCdc *codec.Codec +var ModuleCdc = codec.New() func init() { codec.RegisterCrypto(ModuleCdc) diff --git a/x/mint/types/keys.go b/x/mint/types/keys.go index 6ed2ca5e4333..cf395bc44ee3 100644 --- a/x/mint/types/keys.go +++ b/x/mint/types/keys.go @@ -1,6 +1,7 @@ package types -var minterKey = []byte{0x00} // the one key to use for the keeper store +// the one key to use for the keeper store +var MinterKey = []byte{0x00} // nolint const ( diff --git a/x/mint/minter.go b/x/mint/types/minter.go similarity index 97% rename from x/mint/minter.go rename to x/mint/types/minter.go index eff30785faf1..ee7ca7c662b0 100644 --- a/x/mint/minter.go +++ b/x/mint/types/minter.go @@ -1,4 +1,4 @@ -package mint +package types import ( "fmt" @@ -37,7 +37,8 @@ func DefaultInitialMinter() Minter { ) } -func validateMinter(minter Minter) error { +// validate minter +func ValidateMinter(minter Minter) error { if minter.Inflation.LT(sdk.ZeroDec()) { return fmt.Errorf("mint parameter Inflation should be positive, is %s", minter.Inflation.String()) diff --git a/x/mint/minter_test.go b/x/mint/types/minter_test.go similarity index 99% rename from x/mint/minter_test.go rename to x/mint/types/minter_test.go index 0245c71972fb..8760a66f4466 100644 --- a/x/mint/minter_test.go +++ b/x/mint/types/minter_test.go @@ -1,4 +1,4 @@ -package mint +package types import ( "math/rand" diff --git a/x/mint/types/params.go b/x/mint/types/params.go index 480e60bbdc09..28e07300069c 100644 --- a/x/mint/types/params.go +++ b/x/mint/types/params.go @@ -57,7 +57,8 @@ func DefaultParams() Params { } } -func validateParams(params Params) error { +// validate params +func ValidateParams(params Params) error { if params.GoalBonded.LT(sdk.ZeroDec()) { return fmt.Errorf("mint parameter GoalBonded should be positive, is %s ", params.GoalBonded.String()) } diff --git a/x/params/client/cli/tx.go b/x/params/client/cli/tx.go index 71c1d797388b..b601aad8a741 100644 --- a/x/params/client/cli/tx.go +++ b/x/params/client/cli/tx.go @@ -8,18 +8,18 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/params" paramscutils "github.com/cosmos/cosmos-sdk/x/params/client/utils" ) // GetCmdSubmitProposal implements a command handler for submitting a parameter // change proposal transaction. -func GetCmdSubmitProposal(cdc *codec.Codec) *cobra.Command { +func GetCmdSubmitProposal() *cobra.Command { cmd := &cobra.Command{ Use: "param-change [proposal-file]", Args: cobra.ExactArgs(1), @@ -64,12 +64,12 @@ Where proposal.json contains: ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(types.ModuleCdc)) cliCtx := context.NewCLIContext(). - WithCodec(cdc). - WithAccountDecoder(cdc) + WithCodec(types.ModuleCdc). + WithAccountDecoder(types.ModuleCdc) - proposal, err := paramscutils.ParseParamChangeProposalJSON(cdc, args[0]) + proposal, err := paramscutils.ParseParamChangeProposalJSON(types.ModuleCdc, args[0]) if err != nil { return err } diff --git a/x/params/types/codec.go b/x/params/types/codec.go index fbbc5ffd7da3..78e1e1940f72 100644 --- a/x/params/types/codec.go +++ b/x/params/types/codec.go @@ -4,10 +4,12 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -var msgCdc = codec.New() +// module codec +var ModuleCdc = codec.New() func init() { - RegisterCodec(msgCdc) + RegisterCodec(ModuleCdc) + ModuleCdc.Seal() } // RegisterCodec registers all necessary param module types with a given codec. diff --git a/x/slashing/abci_app.go b/x/slashing/abci_app.go index 14e07d6509a8..c9ca3116babe 100644 --- a/x/slashing/abci_app.go +++ b/x/slashing/abci_app.go @@ -16,7 +16,7 @@ func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, sk Keeper) sdk.Ta // store whether or not they have actually signed it and slash/unbond any // which have missed too many blocks in a row (downtime slashing) for _, voteInfo := range req.LastCommitInfo.GetVotes() { - sk.handleValidatorSignature(ctx, voteInfo.Validator.Address, voteInfo.Validator.Power, voteInfo.SignedLastBlock) + sk.HandleValidatorSignature(ctx, voteInfo.Validator.Address, voteInfo.Validator.Power, voteInfo.SignedLastBlock) } // Iterate through any newly discovered evidence of infraction @@ -25,7 +25,7 @@ func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, sk Keeper) sdk.Ta for _, evidence := range req.ByzantineValidators { switch evidence.Type { case tmtypes.ABCIEvidenceTypeDuplicateVote: - sk.handleDoubleSign(ctx, evidence.Validator.Address, evidence.Height, evidence.Time, evidence.Validator.Power) + sk.HandleDoubleSign(ctx, evidence.Validator.Address, evidence.Height, evidence.Time, evidence.Validator.Power) default: sk.Logger(ctx).Error(fmt.Sprintf("ignored unknown evidence type: %s", evidence.Type)) } diff --git a/x/slashing/alias.go b/x/slashing/alias.go new file mode 100644 index 000000000000..a3129e7fae93 --- /dev/null +++ b/x/slashing/alias.go @@ -0,0 +1,89 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/slashing/types +package slashing + +import ( + "github.com/cosmos/cosmos-sdk/x/slashing/types" +) + +const ( + DefaultCodespace = types.DefaultCodespace + CodeInvalidValidator = types.CodeInvalidValidator + CodeValidatorJailed = types.CodeValidatorJailed + CodeValidatorNotJailed = types.CodeValidatorNotJailed + CodeMissingSelfDelegation = types.CodeMissingSelfDelegation + CodeSelfDelegationTooLow = types.CodeSelfDelegationTooLow + CodeMissingSigningInfo = types.CodeMissingSigningInfo + ModuleName = types.ModuleName + StoreKey = types.StoreKey + RouterKey = types.RouterKey + QuerierRoute = types.QuerierRoute + QueryParameters = types.QueryParameters + QuerySigningInfo = types.QuerySigningInfo + QuerySigningInfos = types.QuerySigningInfos + DefaultParamspace = types.DefaultParamspace + DefaultMaxEvidenceAge = types.DefaultMaxEvidenceAge + DefaultSignedBlocksWindow = types.DefaultSignedBlocksWindow + DefaultDowntimeJailDuration = types.DefaultDowntimeJailDuration +) + +var ( + // functions aliases + RegisterCodec = types.RegisterCodec + ErrNoValidatorForAddress = types.ErrNoValidatorForAddress + ErrBadValidatorAddr = types.ErrBadValidatorAddr + ErrValidatorJailed = types.ErrValidatorJailed + ErrValidatorNotJailed = types.ErrValidatorNotJailed + ErrMissingSelfDelegation = types.ErrMissingSelfDelegation + ErrSelfDelegationTooLowToUnjail = types.ErrSelfDelegationTooLowToUnjail + ErrNoSigningInfoFound = types.ErrNoSigningInfoFound + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + ValidateGenesis = types.ValidateGenesis + GetValidatorSigningInfoKey = types.GetValidatorSigningInfoKey + GetValidatorSigningInfoAddress = types.GetValidatorSigningInfoAddress + GetValidatorMissedBlockBitArrayPrefixKey = types.GetValidatorMissedBlockBitArrayPrefixKey + GetValidatorMissedBlockBitArrayKey = types.GetValidatorMissedBlockBitArrayKey + GetValidatorSlashingPeriodPrefix = types.GetValidatorSlashingPeriodPrefix + GetValidatorSlashingPeriodKey = types.GetValidatorSlashingPeriodKey + GetAddrPubkeyRelationKey = types.GetAddrPubkeyRelationKey + NewMsgUnjail = types.NewMsgUnjail + ParamKeyTable = types.ParamKeyTable + NewParams = types.NewParams + DefaultParams = types.DefaultParams + NewQuerySigningInfoParams = types.NewQuerySigningInfoParams + NewQuerySigningInfosParams = types.NewQuerySigningInfosParams + NewValidatorSigningInfo = types.NewValidatorSigningInfo + + // variable aliases + ModuleCdc = types.ModuleCdc + ValidatorSigningInfoKey = types.ValidatorSigningInfoKey + ValidatorMissedBlockBitArrayKey = types.ValidatorMissedBlockBitArrayKey + ValidatorSlashingPeriodKey = types.ValidatorSlashingPeriodKey + AddrPubkeyRelationKey = types.AddrPubkeyRelationKey + DoubleSignJailEndTime = types.DoubleSignJailEndTime + DefaultMinSignedPerWindow = types.DefaultMinSignedPerWindow + DefaultSlashFractionDoubleSign = types.DefaultSlashFractionDoubleSign + DefaultSlashFractionDowntime = types.DefaultSlashFractionDowntime + KeyMaxEvidenceAge = types.KeyMaxEvidenceAge + KeySignedBlocksWindow = types.KeySignedBlocksWindow + KeyMinSignedPerWindow = types.KeyMinSignedPerWindow + KeyDowntimeJailDuration = types.KeyDowntimeJailDuration + KeySlashFractionDoubleSign = types.KeySlashFractionDoubleSign + KeySlashFractionDowntime = types.KeySlashFractionDowntime +) + +type ( + CodeType = types.CodeType + StakingKeeper = types.StakingKeeper + AccountKeeper = types.AccountKeeper + GenesisState = types.GenesisState + MissedBlock = types.MissedBlock + MsgUnjail = types.MsgUnjail + Params = types.Params + QuerySigningInfoParams = types.QuerySigningInfoParams + QuerySigningInfosParams = types.QuerySigningInfosParams + ValidatorSigningInfo = types.ValidatorSigningInfo +) diff --git a/x/slashing/genesis.go b/x/slashing/genesis.go index a20ea4870887..784f2408d9a3 100644 --- a/x/slashing/genesis.go +++ b/x/slashing/genesis.go @@ -2,13 +2,12 @@ package slashing import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/slashing/keeper" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) // InitGenesis initialize default parameters // and the keeper's address to pubkey map -func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, stakingKeeper types.StakingKeeper, data types.GenesisState) { +func InitGenesis(ctx sdk.Context, keeper Keeper, stakingKeeper types.StakingKeeper, data types.GenesisState) { stakingKeeper.IterateValidators(ctx, func(index int64, validator sdk.Validator) bool { keeper.addPubkey(ctx, validator.GetConsPubKey()) @@ -40,19 +39,19 @@ func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, stakingKeeper types.Stak // ExportGenesis writes the current store values // to a genesis file, which can be imported again // with InitGenesis -func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) (data types.GenesisState) { - var params Params +func ExportGenesis(ctx sdk.Context, keeper Keeper) (data types.GenesisState) { + var params types.Params keeper.paramspace.GetParamSet(ctx, ¶ms) - signingInfos := make(map[string]ValidatorSigningInfo) - missedBlocks := make(map[string][]MissedBlock) - keeper.IterateValidatorSigningInfos(ctx, func(address sdk.ConsAddress, info ValidatorSigningInfo) (stop bool) { + signingInfos := make(map[string]types.ValidatorSigningInfo) + missedBlocks := make(map[string][]types.MissedBlock) + keeper.IterateValidatorSigningInfos(ctx, func(address sdk.ConsAddress, info types.ValidatorSigningInfo) (stop bool) { bechAddr := address.String() signingInfos[bechAddr] = info - localMissedBlocks := []MissedBlock{} + localMissedBlocks := []types.MissedBlock{} keeper.IterateValidatorMissedBlockBitArray(ctx, address, func(index int64, missed bool) (stop bool) { - localMissedBlocks = append(localMissedBlocks, MissedBlock{index, missed}) + localMissedBlocks = append(localMissedBlocks, types.MissedBlock{index, missed}) return false }) missedBlocks[bechAddr] = localMissedBlocks @@ -60,7 +59,7 @@ func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) (data types.GenesisSta return false }) - return GenesisState{ + return types.GenesisState{ Params: params, SigningInfos: signingInfos, MissedBlocks: missedBlocks, diff --git a/x/slashing/handler.go b/x/slashing/handler.go index f3716bfefea5..d3562fe05d1b 100644 --- a/x/slashing/handler.go +++ b/x/slashing/handler.go @@ -4,7 +4,6 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/slashing/tags" ) @@ -24,7 +23,7 @@ func NewHandler(k Keeper) sdk.Handler { // Validators must submit a transaction to unjail itself after // having been jailed (and thus unbonded) for downtime -func handleMsgUnjail(ctx sdk.Context, msg types.MsgUnjail, k Keeper) sdk.Result { +func handleMsgUnjail(ctx sdk.Context, msg MsgUnjail, k Keeper) sdk.Result { validator := k.validatorSet.Validator(ctx, msg.ValidatorAddr) if validator == nil { return ErrNoValidatorForAddress(k.codespace).Result() diff --git a/x/slashing/keeper/hooks.go b/x/slashing/hooks.go similarity index 99% rename from x/slashing/keeper/hooks.go rename to x/slashing/hooks.go index ebb8d5a4a4fd..192399d3dd00 100644 --- a/x/slashing/keeper/hooks.go +++ b/x/slashing/hooks.go @@ -1,5 +1,5 @@ // nolint -package keeper +package slashing import ( "time" diff --git a/x/slashing/keeper/keeper.go b/x/slashing/keeper.go similarity index 98% rename from x/slashing/keeper/keeper.go rename to x/slashing/keeper.go index 227320c51887..ddc004eb7386 100644 --- a/x/slashing/keeper/keeper.go +++ b/x/slashing/keeper.go @@ -1,4 +1,4 @@ -package keeper +package slashing import ( "fmt" @@ -41,7 +41,7 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("m // handle a validator signing two blocks at the same height // power: power of the double-signing validator at the height of infraction -func (k Keeper) handleDoubleSign(ctx sdk.Context, addr crypto.Address, infractionHeight int64, timestamp time.Time, power int64) { +func (k Keeper) HandleDoubleSign(ctx sdk.Context, addr crypto.Address, infractionHeight int64, timestamp time.Time, power int64) { logger := k.Logger(ctx) // calculate the age of the evidence @@ -129,7 +129,7 @@ func (k Keeper) handleDoubleSign(ctx sdk.Context, addr crypto.Address, infractio // handle a validator signature, must be called once per validator per block // TODO refactor to take in a consensus address, additionally should maybe just take in the pubkey too -func (k Keeper) handleValidatorSignature(ctx sdk.Context, addr crypto.Address, power int64, signed bool) { +func (k Keeper) HandleValidatorSignature(ctx sdk.Context, addr crypto.Address, power int64, signed bool) { logger := k.Logger(ctx) height := ctx.BlockHeight() consAddr := sdk.ConsAddress(addr) diff --git a/x/slashing/keeper/keeper_test.go b/x/slashing/keeper_test.go similarity index 91% rename from x/slashing/keeper/keeper_test.go rename to x/slashing/keeper_test.go index 1dcbbebfd4b5..96d6d288f243 100644 --- a/x/slashing/keeper/keeper_test.go +++ b/x/slashing/keeper_test.go @@ -1,4 +1,4 @@ -package keeper +package slashing import ( "testing" @@ -44,12 +44,12 @@ func TestHandleDoubleSign(t *testing.T) { require.Equal(t, amt, sk.Validator(ctx, operatorAddr).GetBondedTokens()) // handle a signature to set signing info - keeper.handleValidatorSignature(ctx, val.Address(), amt.Int64(), true) + keeper.HandleValidatorSignature(ctx, val.Address(), amt.Int64(), true) oldTokens := sk.Validator(ctx, operatorAddr).GetTokens() // double sign less than max age - keeper.handleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), power) + keeper.HandleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), power) // should be jailed require.True(t, sk.Validator(ctx, operatorAddr).IsJailed()) @@ -59,7 +59,7 @@ func TestHandleDoubleSign(t *testing.T) { require.True(t, newTokens.LT(oldTokens)) // New evidence - keeper.handleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), power) + keeper.HandleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), power) // tokens should be the same (capped slash) require.True(t, sk.Validator(ctx, operatorAddr).GetTokens().Equal(newTokens)) @@ -105,14 +105,14 @@ func TestPastMaxEvidenceAge(t *testing.T) { require.Equal(t, amt, sk.Validator(ctx, operatorAddr).GetBondedTokens()) // handle a signature to set signing info - keeper.handleValidatorSignature(ctx, val.Address(), power, true) + keeper.HandleValidatorSignature(ctx, val.Address(), power, true) ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(1, 0).Add(keeper.MaxEvidenceAge(ctx))}) oldPower := sk.Validator(ctx, operatorAddr).GetTendermintPower() // double sign past max age - keeper.handleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), power) + keeper.HandleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), power) // should still be bonded require.True(t, sk.Validator(ctx, operatorAddr).GetStatus() == sdk.Bonded) @@ -154,7 +154,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 1000 first blocks OK for ; height < keeper.SignedBlocksWindow(ctx); height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, true) + keeper.HandleValidatorSignature(ctx, val.Address(), power, true) } info, found = keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) @@ -164,7 +164,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 500 blocks missed for ; height < keeper.SignedBlocksWindow(ctx)+(keeper.SignedBlocksWindow(ctx)-keeper.MinSignedPerWindow(ctx)); height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) } info, found = keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) @@ -179,7 +179,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 501st block missed ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) info, found = keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) @@ -201,7 +201,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 502nd block *also* missed (since the LastCommit would have still included the just-unbonded validator) height++ ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) info, found = keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) @@ -244,7 +244,7 @@ func TestHandleAbsentValidator(t *testing.T) { // validator should not be immediately jailed again height++ ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) require.Equal(t, sdk.Bonded, validator.GetStatus()) @@ -252,7 +252,7 @@ func TestHandleAbsentValidator(t *testing.T) { nextHeight := height + keeper.MinSignedPerWindow(ctx) + 1 for ; height < nextHeight; height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) } // end block @@ -262,7 +262,7 @@ func TestHandleAbsentValidator(t *testing.T) { nextHeight = height + keeper.MinSignedPerWindow(ctx) + 1 for ; height <= nextHeight; height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) } // end block @@ -297,9 +297,9 @@ func TestHandleNewValidator(t *testing.T) { require.Equal(t, amt, sk.Validator(ctx, addr).GetBondedTokens()) // Now a validator, for two blocks - keeper.handleValidatorSignature(ctx, val.Address(), 100, true) + keeper.HandleValidatorSignature(ctx, val.Address(), 100, true) ctx = ctx.WithBlockHeight(keeper.SignedBlocksWindow(ctx) + 2) - keeper.handleValidatorSignature(ctx, val.Address(), 100, false) + keeper.HandleValidatorSignature(ctx, val.Address(), 100, false) info, found := keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) @@ -334,13 +334,13 @@ func TestHandleAlreadyJailed(t *testing.T) { height := int64(0) for ; height < keeper.SignedBlocksWindow(ctx); height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, true) + keeper.HandleValidatorSignature(ctx, val.Address(), power, true) } // 501 blocks missed for ; height < keeper.SignedBlocksWindow(ctx)+(keeper.SignedBlocksWindow(ctx)-keeper.MinSignedPerWindow(ctx))+1; height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) } // end block @@ -356,7 +356,7 @@ func TestHandleAlreadyJailed(t *testing.T) { // another block missed ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) // validator should not have been slashed twice validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) @@ -388,7 +388,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { height := int64(0) for ; height < int64(100); height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, true) + keeper.HandleValidatorSignature(ctx, val.Address(), power, true) } // validator kicked out of validator set @@ -415,7 +415,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { newPower := int64(103) // validator misses a block - keeper.handleValidatorSignature(ctx, val.Address(), newPower, false) + keeper.HandleValidatorSignature(ctx, val.Address(), newPower, false) height++ // shouldn't be jailed/kicked yet @@ -426,7 +426,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { latest := height for ; height < latest+500; height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), newPower, false) + keeper.HandleValidatorSignature(ctx, val.Address(), newPower, false) } // should now be jailed & kicked @@ -451,7 +451,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { // validator rejoins and starts signing again sk.Unjail(ctx, consAddr) - keeper.handleValidatorSignature(ctx, val.Address(), newPower, true) + keeper.HandleValidatorSignature(ctx, val.Address(), newPower, true) height++ // validator should not be kicked since we reset counter/array when it was jailed @@ -463,7 +463,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { latest = height for ; height < latest+501; height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), newPower, false) + keeper.HandleValidatorSignature(ctx, val.Address(), newPower, false) } // validator should now be jailed & kicked diff --git a/x/slashing/module.go b/x/slashing/module.go index 3f60b6f6e24e..65ee9d8fa68c 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -39,13 +39,13 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { // default genesis state func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return moduleCdc.MustMarshalJSON(DefaultGenesisState()) + return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } // module validate genesis func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) + err := ModuleCdc.UnmarshalJSON(bz, &data) if err != nil { return err } @@ -54,17 +54,17 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { // register rest routes func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { - rest.RegisterRoutes(ctx, rtr, cdc, StoreKey) + rest.RegisterRoutes(ctx, rtr, cdc) } // get the root tx command of this module func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd(StoreKey, moduleCdc) + return cli.GetTxCmd(ModuleCdc) } // get the root query command of this module func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(moduleCdc) + return cli.GetQueryCmd(StoreKey, ModuleCdc) } //___________________________ @@ -115,7 +115,7 @@ func (am AppModule) NewQuerierHandler() sdk.Querier { // module init-genesis func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState - moduleCdc.MustUnmarshalJSON(data, &genesisState) + ModuleCdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.keeper, am.stakingKeeper, genesisState) return []abci.ValidatorUpdate{} } @@ -123,7 +123,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va // module export genesis func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) - return moduleCdc.MustMarshalJSON(gs) + return ModuleCdc.MustMarshalJSON(gs) } // module begin-block diff --git a/x/slashing/keeper/params.go b/x/slashing/params.go similarity index 98% rename from x/slashing/keeper/params.go rename to x/slashing/params.go index 7a1c3174a8bb..dfe676a88a0d 100644 --- a/x/slashing/keeper/params.go +++ b/x/slashing/params.go @@ -1,4 +1,4 @@ -package keeper +package slashing import ( "time" diff --git a/x/slashing/querier.go b/x/slashing/querier.go index 5a1a4d5c493e..c59b457b9179 100644 --- a/x/slashing/querier.go +++ b/x/slashing/querier.go @@ -28,7 +28,7 @@ func NewQuerier(k Keeper) sdk.Querier { func queryParams(ctx sdk.Context, k Keeper) ([]byte, sdk.Error) { params := k.GetParams(ctx) - res, err := codec.MarshalJSONIndent(moduleCdc, params) + res, err := codec.MarshalJSONIndent(ModuleCdc, params) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("failed to marshal JSON", err.Error())) } @@ -39,7 +39,7 @@ func queryParams(ctx sdk.Context, k Keeper) ([]byte, sdk.Error) { func querySigningInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { var params QuerySigningInfoParams - err := moduleCdc.UnmarshalJSON(req.Data, ¶ms) + err := ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } @@ -49,7 +49,7 @@ func querySigningInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, return nil, ErrNoSigningInfoFound(DefaultCodespace, params.ConsAddress) } - res, err := codec.MarshalJSONIndent(moduleCdc, signingInfo) + res, err := codec.MarshalJSONIndent(ModuleCdc, signingInfo) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("failed to JSON marshal result: %s", err.Error())) } @@ -60,7 +60,7 @@ func querySigningInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, func querySigningInfos(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { var params QuerySigningInfosParams - err := moduleCdc.UnmarshalJSON(req.Data, ¶ms) + err := ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } @@ -91,7 +91,7 @@ func querySigningInfos(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte signingInfos = signingInfos[start:end] } - res, err := codec.MarshalJSONIndent(moduleCdc, signingInfos) + res, err := codec.MarshalJSONIndent(ModuleCdc, signingInfos) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("failed to JSON marshal result: %s", err.Error())) } diff --git a/x/slashing/keeper/signing_info.go b/x/slashing/signing_info.go similarity index 99% rename from x/slashing/keeper/signing_info.go rename to x/slashing/signing_info.go index 47b60faa5d6b..f9cce43ac85e 100644 --- a/x/slashing/keeper/signing_info.go +++ b/x/slashing/signing_info.go @@ -1,4 +1,4 @@ -package keeper +package slashing import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/slashing/keeper/signing_info_test.go b/x/slashing/signing_info_test.go similarity index 98% rename from x/slashing/keeper/signing_info_test.go rename to x/slashing/signing_info_test.go index 91967edd6815..d6803af8da48 100644 --- a/x/slashing/keeper/signing_info_test.go +++ b/x/slashing/signing_info_test.go @@ -1,4 +1,4 @@ -package keeper +package slashing import ( "testing" diff --git a/x/slashing/types/codec.go b/x/slashing/types/codec.go index cebd46890557..52542aac04fe 100644 --- a/x/slashing/types/codec.go +++ b/x/slashing/types/codec.go @@ -9,11 +9,11 @@ func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(MsgUnjail{}, "cosmos-sdk/MsgUnjail", nil) } -var moduleCdc = codec.New() +// module codec +var ModuleCdc = codec.New() func init() { - cdc := codec.New() - RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - moduleCdc = cdc.Seal() + RegisterCodec(ModuleCdc) + codec.RegisterCrypto(ModuleCdc) + ModuleCdc.Seal() } diff --git a/x/slashing/types/msg.go b/x/slashing/types/msg.go index aa0aac534388..2988cb7dcc36 100644 --- a/x/slashing/types/msg.go +++ b/x/slashing/types/msg.go @@ -27,7 +27,7 @@ func (msg MsgUnjail) GetSigners() []sdk.AccAddress { // get the bytes for the message signer to sign on func (msg MsgUnjail) GetSignBytes() []byte { - bz := moduleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } diff --git a/x/staking/types/codec.go b/x/staking/types/codec.go index d4f3ad594aff..4444f81c00f0 100644 --- a/x/staking/types/codec.go +++ b/x/staking/types/codec.go @@ -14,11 +14,10 @@ func RegisterCodec(cdc *codec.Codec) { } // generic sealed codec to be used throughout this module -var ModuleCdc *codec.Codec +var ModuleCdc = codec.New() func init() { - cdc := codec.New() - RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - ModuleCdc = cdc.Seal() + RegisterCodec(ModuleCdc) + codec.RegisterCrypto(ModuleCdc) + ModuleCdc.Seal() } From abfbe47e058f850ad5d6a725ff4b0cd8ba3331c7 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 31 May 2019 16:20:21 -0400 Subject: [PATCH 09/23] fix bugs --- simapp/app_test.go | 19 ++++++------------- x/params/client/cli/tx.go | 5 ++--- x/slashing/module.go | 2 +- 3 files changed, 9 insertions(+), 17 deletions(-) diff --git a/simapp/app_test.go b/simapp/app_test.go index d93a80734246..e5b6e5a10859 100644 --- a/simapp/app_test.go +++ b/simapp/app_test.go @@ -16,20 +16,10 @@ import ( func TestSimAppExport(t *testing.T) { db := db.NewMemDB() app := NewSimApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0) - setGenesis(app) - // Making a new app object with the db, so that initchain hasn't been called - app2 := NewSimApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0) - _, _, err := app2.ExportAppStateAndValidators(false, []string{}) - require.NoError(t, err, "ExportAppStateAndValidators should not have an error") -} - -func setGenesis(app *SimApp) error { genesisState := NewDefaultGenesisState() stateBytes, err := codec.MarshalJSONIndent(app.cdc, genesisState) - if err != nil { - return err - } + require.NoError(t, err) // Initialize the chain app.InitChain( @@ -38,7 +28,10 @@ func setGenesis(app *SimApp) error { AppStateBytes: stateBytes, }, ) - app.Commit() - return nil + + // Making a new app object with the db, so that initchain hasn't been called + app2 := NewSimApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0) + _, _, err = app2.ExportAppStateAndValidators(false, []string{}) + require.NoError(t, err, "ExportAppStateAndValidators should not have an error") } diff --git a/x/params/client/cli/tx.go b/x/params/client/cli/tx.go index b601aad8a741..06c011e74445 100644 --- a/x/params/client/cli/tx.go +++ b/x/params/client/cli/tx.go @@ -12,9 +12,8 @@ import ( "github.com/cosmos/cosmos-sdk/version" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/params" paramscutils "github.com/cosmos/cosmos-sdk/x/params/client/utils" + "github.com/cosmos/cosmos-sdk/x/params/types" ) // GetCmdSubmitProposal implements a command handler for submitting a parameter @@ -75,7 +74,7 @@ Where proposal.json contains: } from := cliCtx.GetFromAddress() - content := params.NewParameterChangeProposal(proposal.Title, proposal.Description, proposal.Changes.ToParamChanges()) + content := types.NewParameterChangeProposal(proposal.Title, proposal.Description, proposal.Changes.ToParamChanges()) msg := gov.NewMsgSubmitProposal(content, proposal.Deposit, from) if err := msg.ValidateBasic(); err != nil { diff --git a/x/slashing/module.go b/x/slashing/module.go index 65ee9d8fa68c..fc3e5bcc25e4 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -12,9 +12,9 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) var ( From 5c62e49bc9b7e903b539b677a2157826e8de993d Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 31 May 2019 18:40:56 -0400 Subject: [PATCH 10/23] gov proposal handler type --- simapp/app.go | 5 +- types/context.go | 2 +- x/auth/module.go | 1 - x/distribution/client/cli/tx.go | 10 ++-- x/distribution/client/proposal_handler.go | 10 ++++ x/genutil/client/cli/gentx.go | 2 +- x/gov/alias.go | 12 +++++ x/gov/client/cli/parse.go | 4 +- x/gov/client/cli/query.go | 56 +++++++++++------------ x/gov/client/cli/tx.go | 26 +++++------ x/gov/client/proposal_handler.go | 26 +++++++++++ x/gov/client/rest/rest.go | 2 +- x/gov/module.go | 29 ++++++++---- x/gov/{ => types}/params.go | 4 +- x/params/client/proposal_handler.go | 10 ++++ 15 files changed, 133 insertions(+), 66 deletions(-) create mode 100644 x/distribution/client/proposal_handler.go create mode 100644 x/gov/client/proposal_handler.go rename x/gov/{ => types}/params.go (97%) create mode 100644 x/params/client/proposal_handler.go diff --git a/simapp/app.go b/simapp/app.go index 9173c3f5d3e0..1ef058b8e139 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -19,11 +19,12 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/crisis" distr "github.com/cosmos/cosmos-sdk/x/distribution" + distrclient "github.com/cosmos/cosmos-sdk/x/distribution/client" "github.com/cosmos/cosmos-sdk/x/genutil" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/params" - paramscli "github.com/cosmos/cosmos-sdk/x/params/client/cli" + paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/staking" ) @@ -52,7 +53,7 @@ func init() { staking.AppModuleBasic{}, mint.AppModuleBasic{}, distr.AppModuleBasic{}, - gov.NewAppModuleBasic(paramscli.GetCmdSubmitProposal()), + gov.NewAppModuleBasic(paramsclient.ProposalHandler, distrclient.ProposalHandler), params.AppModuleBasic{}, crisis.AppModuleBasic{}, slashing.AppModuleBasic{}, diff --git a/types/context.go b/types/context.go index 1663a94e65ac..f626fc40caa6 100644 --- a/types/context.go +++ b/types/context.go @@ -257,7 +257,7 @@ type cloner interface { Clone() interface{} // deep copy } -// XXX add description +// TODO add description type Op struct { // type is always 'with' gen int diff --git a/x/auth/module.go b/x/auth/module.go index 6c47c9367681..bb28ceb0a9fe 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -48,7 +48,6 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return types.ValidateGenesis(data) } -// XXX // register rest routes func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { rest.RegisterRoutes(ctx, rtr, cdc, types.StoreKey) diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index 1e9a05aed93e..b1ba8a0d20c0 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -193,7 +193,7 @@ $ %s tx set-withdraw-addr cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p --from m } // GetCmdSubmitProposal implements the command to submit a community-pool-spend proposal -func GetCmdSubmitProposal(cdc *codec.Codec) *cobra.Command { +func GetCmdSubmitProposal() *cobra.Command { cmd := &cobra.Command{ Use: "community-pool-spend [proposal-file]", Args: cobra.ExactArgs(1), @@ -229,12 +229,12 @@ Where proposal.json contains: ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(types.ModuleCdc)) cliCtx := context.NewCLIContext(). - WithCodec(cdc). - WithAccountDecoder(cdc) + WithCodec(types.ModuleCdc). + WithAccountDecoder(types.ModuleCdc) - proposal, err := ParseCommunityPoolSpendProposalJSON(cdc, args[0]) + proposal, err := ParseCommunityPoolSpendProposalJSON(types.ModuleCdc, args[0]) if err != nil { return err } diff --git a/x/distribution/client/proposal_handler.go b/x/distribution/client/proposal_handler.go new file mode 100644 index 000000000000..f7d8fdf4f7dd --- /dev/null +++ b/x/distribution/client/proposal_handler.go @@ -0,0 +1,10 @@ +package client + +import ( + "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" + "github.com/cosmos/cosmos-sdk/x/distribution/client/rest" + govclient "github.com/cosmos/cosmos-sdk/x/gov/client" +) + +// param change proposal handler +var ProposalHandler = govclient.NewProposalHandler(cli.GetCmdSubmitProposal(), rest.ProposalRESTHandler) diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index ca24341846e0..350b579e9ada 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -121,7 +121,7 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, sm txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(client.GetTxEncoder(cdc)) cliCtx := client.NewCLIContext().WithCodec(cdc) - // XXX: Set the generate-only flag here after the CLI context has + // Set the generate-only flag here after the CLI context has // been created. This allows the from name/key to be correctly populated. // // TODO: Consider removing the manual setting of generate-only in diff --git a/x/gov/alias.go b/x/gov/alias.go index 4ee7d2a69cca..e713059c6307 100644 --- a/x/gov/alias.go +++ b/x/gov/alias.go @@ -84,6 +84,11 @@ var ( NewMsgSubmitProposal = types.NewMsgSubmitProposal NewMsgDeposit = types.NewMsgDeposit NewMsgVote = types.NewMsgVote + ParamKeyTable = types.ParamKeyTable + NewDepositParams = types.NewDepositParams + NewTallyParams = types.NewTallyParams + NewVotingParams = types.NewVotingParams + NewParams = types.NewParams NewProposal = types.NewProposal ProposalStatusFromString = types.ProposalStatusFromString ValidProposalStatus = types.ValidProposalStatus @@ -109,6 +114,9 @@ var ( KeyNextProposalID = types.KeyNextProposalID PrefixActiveProposalQueue = types.PrefixActiveProposalQueue PrefixInactiveProposalQueue = types.PrefixInactiveProposalQueue + ParamStoreKeyDepositParams = types.ParamStoreKeyDepositParams + ParamStoreKeyVotingParams = types.ParamStoreKeyVotingParams + ParamStoreKeyTallyParams = types.ParamStoreKeyTallyParams ) type ( @@ -119,6 +127,10 @@ type ( MsgSubmitProposal = types.MsgSubmitProposal MsgDeposit = types.MsgDeposit MsgVote = types.MsgVote + DepositParams = types.DepositParams + TallyParams = types.TallyParams + VotingParams = types.VotingParams + Params = types.Params Proposal = types.Proposal Proposals = types.Proposals ProposalQueue = types.ProposalQueue diff --git a/x/gov/client/cli/parse.go b/x/gov/client/cli/parse.go index f48aa34c5230..dd9415f18d19 100644 --- a/x/gov/client/cli/parse.go +++ b/x/gov/client/cli/parse.go @@ -7,7 +7,7 @@ import ( "github.com/spf13/viper" - govClientUtils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" + govutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" ) func parseSubmitProposalFlags() (*proposal, error) { @@ -17,7 +17,7 @@ func parseSubmitProposalFlags() (*proposal, error) { if proposalFile == "" { proposal.Title = viper.GetString(FlagTitle) proposal.Description = viper.GetString(FlagDescription) - proposal.Type = govClientUtils.NormalizeProposalType(viper.GetString(flagProposalType)) + proposal.Type = govutils.NormalizeProposalType(viper.GetString(flagProposalType)) proposal.Deposit = viper.GetString(FlagDeposit) return proposal, nil } diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index 10d2b5193636..23c653eb5710 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -13,15 +13,15 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/gov" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // GetQueryCmd returns the cli query commands for this module func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { // Group gov queries under a subcommand govQueryCmd := &cobra.Command{ - Use: gov.ModuleName, + Use: types.ModuleName, Short: "Querying commands for the governance module", } @@ -71,7 +71,7 @@ $ %s query gov proposal 1 return err } - var proposal gov.Proposal + var proposal types.Proposal cdc.MustUnmarshalJSON(res, &proposal) return cliCtx.PrintOutput(proposal) // nolint:errcheck }, @@ -102,9 +102,9 @@ $ %s query gov proposals --status (DepositPeriod|VotingPeriod|Passed|Rejected) var depositorAddr sdk.AccAddress var voterAddr sdk.AccAddress - var proposalStatus gov.ProposalStatus + var proposalStatus types.ProposalStatus - params := gov.NewQueryProposalsParams(proposalStatus, numLimit, voterAddr, depositorAddr) + params := types.NewQueryProposalsParams(proposalStatus, numLimit, voterAddr, depositorAddr) if len(bechDepositorAddr) != 0 { depositorAddr, err := sdk.AccAddressFromBech32(bechDepositorAddr) @@ -123,7 +123,7 @@ $ %s query gov proposals --status (DepositPeriod|VotingPeriod|Passed|Rejected) } if len(strProposalStatus) != 0 { - proposalStatus, err := gov.ProposalStatusFromString(gcutils.NormalizeProposalStatus(strProposalStatus)) + proposalStatus, err := types.ProposalStatusFromString(gcutils.NormalizeProposalStatus(strProposalStatus)) if err != nil { return err } @@ -142,7 +142,7 @@ $ %s query gov proposals --status (DepositPeriod|VotingPeriod|Passed|Rejected) return err } - var matchingProposals gov.Proposals + var matchingProposals types.Proposals err = cdc.UnmarshalJSON(res, &matchingProposals) if err != nil { return err @@ -200,7 +200,7 @@ $ %s query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return err } - params := gov.NewQueryVoteParams(proposalID, voterAddr) + params := types.NewQueryVoteParams(proposalID, voterAddr) bz, err := cdc.MarshalJSON(params) if err != nil { return err @@ -211,7 +211,7 @@ $ %s query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return err } - var vote gov.Vote + var vote types.Vote if err := cdc.UnmarshalJSON(res, &vote); err != nil { return err } @@ -255,7 +255,7 @@ $ %s query gov votes 1 return fmt.Errorf("proposal-id %s not a valid int, please input a valid proposal-id", args[0]) } - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { return err @@ -267,11 +267,11 @@ $ %s query gov votes 1 return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) } - var proposal gov.Proposal + var proposal types.Proposal cdc.MustUnmarshalJSON(res, &proposal) propStatus := proposal.Status - if !(propStatus == gov.StatusVotingPeriod || propStatus == gov.StatusDepositPeriod) { + if !(propStatus == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { res, err = gcutils.QueryVotesByTxQuery(cdc, cliCtx, params) } else { res, err = cliCtx.QueryWithData(fmt.Sprintf("custom/%s/votes", queryRoute), bz) @@ -281,7 +281,7 @@ $ %s query gov votes 1 return err } - var votes gov.Votes + var votes types.Votes cdc.MustUnmarshalJSON(res, &votes) return cliCtx.PrintOutput(votes) }, @@ -324,7 +324,7 @@ $ %s query gov deposit 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return err } - params := gov.NewQueryDepositParams(proposalID, depositorAddr) + params := types.NewQueryDepositParams(proposalID, depositorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { return err @@ -335,7 +335,7 @@ $ %s query gov deposit 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return err } - var deposit gov.Deposit + var deposit types.Deposit cdc.MustUnmarshalJSON(res, &deposit) if deposit.Empty() { @@ -376,7 +376,7 @@ $ %s query gov deposits 1 return fmt.Errorf("proposal-id %s not a valid uint, please input a valid proposal-id", args[0]) } - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { return err @@ -388,11 +388,11 @@ $ %s query gov deposits 1 return fmt.Errorf("failed to fetch proposal with id %d: %s", proposalID, err) } - var proposal gov.Proposal + var proposal types.Proposal cdc.MustUnmarshalJSON(res, &proposal) propStatus := proposal.Status - if !(propStatus == gov.StatusVotingPeriod || propStatus == gov.StatusDepositPeriod) { + if !(propStatus == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { res, err = gcutils.QueryDepositsByTxQuery(cdc, cliCtx, params) } else { res, err = cliCtx.QueryWithData(fmt.Sprintf("custom/%s/deposits", queryRoute), bz) @@ -402,7 +402,7 @@ $ %s query gov deposits 1 return err } - var dep gov.Deposits + var dep types.Deposits cdc.MustUnmarshalJSON(res, &dep) return cliCtx.PrintOutput(dep) }, @@ -441,7 +441,7 @@ $ %s query gov tally 1 } // Construct query - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { return err @@ -453,7 +453,7 @@ $ %s query gov tally 1 return err } - var tally gov.TallyResult + var tally types.TallyResult cdc.MustUnmarshalJSON(res, &tally) return cliCtx.PrintOutput(tally) }, @@ -490,14 +490,14 @@ $ %s query gov params return err } - var tallyParams gov.TallyParams + var tallyParams types.TallyParams cdc.MustUnmarshalJSON(tp, &tallyParams) - var depositParams gov.DepositParams + var depositParams types.DepositParams cdc.MustUnmarshalJSON(dp, &depositParams) - var votingParams gov.VotingParams + var votingParams types.VotingParams cdc.MustUnmarshalJSON(vp, &votingParams) - return cliCtx.PrintOutput(gov.NewParams(votingParams, tallyParams, depositParams)) + return cliCtx.PrintOutput(types.NewParams(votingParams, tallyParams, depositParams)) }, } } @@ -530,15 +530,15 @@ $ %s query gov param deposit var out fmt.Stringer switch args[0] { case "voting": - var param gov.VotingParams + var param types.VotingParams cdc.MustUnmarshalJSON(res, ¶m) out = param case "tallying": - var param gov.TallyParams + var param types.TallyParams cdc.MustUnmarshalJSON(res, ¶m) out = param case "deposit": - var param gov.DepositParams + var param types.DepositParams cdc.MustUnmarshalJSON(res, ¶m) out = param default: diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index 6002ced7ac48..277b32cf2b9f 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -3,6 +3,9 @@ package cli import ( "fmt" "strconv" + "strings" + + "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" @@ -11,13 +14,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/gov" - - "strings" - - "github.com/spf13/cobra" - - govClientUtils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" + govutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // Proposal flags @@ -55,9 +53,9 @@ var ProposalFlags = []string{ // it contains a slice of "proposal" child commands. These commands are respective // to proposal type handlers that are implemented in other modules but are mounted // under the governance CLI (eg. parameter change proposals). -func GetTxCmd(storeKey string, cdc *codec.Codec, pcmds ...*cobra.Command) *cobra.Command { +func GetTxCmd(storeKey string, cdc *codec.Codec, pcmds []*cobra.Command) *cobra.Command { govTxCmd := &cobra.Command{ - Use: gov.ModuleName, + Use: types.ModuleName, Short: "Governance transactions subcommands", } @@ -119,9 +117,9 @@ $ %s tx gov submit-proposal --title="Test Proposal" --description="My awesome pr return err } - content := gov.ContentFromProposalType(proposal.Title, proposal.Description, proposal.Type) + content := types.ContentFromProposalType(proposal.Title, proposal.Description, proposal.Type) - msg := gov.NewMsgSubmitProposal(content, amount, cliCtx.GetFromAddress()) + msg := types.NewMsgSubmitProposal(content, amount, cliCtx.GetFromAddress()) if err := msg.ValidateBasic(); err != nil { return err } @@ -176,7 +174,7 @@ $ %s tx gov deposit 1 10stake --from mykey return err } - msg := gov.NewMsgDeposit(from, proposalID, amount) + msg := types.NewMsgDeposit(from, proposalID, amount) err = msg.ValidateBasic() if err != nil { return err @@ -220,13 +218,13 @@ $ %s tx gov vote 1 yes --from mykey } // Find out which vote option user chose - byteVoteOption, err := gov.VoteOptionFromString(govClientUtils.NormalizeVoteOption(args[1])) + byteVoteOption, err := types.VoteOptionFromString(govutils.NormalizeVoteOption(args[1])) if err != nil { return err } // Build vote message and run basic validation - msg := gov.NewMsgVote(from, proposalID, byteVoteOption) + msg := types.NewMsgVote(from, proposalID, byteVoteOption) err = msg.ValidateBasic() if err != nil { return err diff --git a/x/gov/client/proposal_handler.go b/x/gov/client/proposal_handler.go new file mode 100644 index 000000000000..88bd94bb0bf3 --- /dev/null +++ b/x/gov/client/proposal_handler.go @@ -0,0 +1,26 @@ +package client + +import ( + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/gov/client/rest" +) + +// function to create the rest handler +type RESTHandlerFn func(context.CLIContext, *codec.Codec) rest.ProposalRESTHandler + +// The combined type for a proposal handler for both cli and rest +type ProposalHandler struct { + CLIHandler *cobra.Command + RESTHandler RESTHandlerFn +} + +// NewProposalHandler creates a new ProposalHandler object +func NewProposalHandler(cliHandler *cobra.Command, restHandler RESTHandlerFn) ProposalHandler { + return ProposalHandler{ + CLIHandler: cliHandler, + RESTHandler: restHandler, + } +} diff --git a/x/gov/client/rest/rest.go b/x/gov/client/rest/rest.go index 227898ad31d2..d62bcacc1ccd 100644 --- a/x/gov/client/rest/rest.go +++ b/x/gov/client/rest/rest.go @@ -35,7 +35,7 @@ type ProposalRESTHandler struct { } // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, phs ...ProposalRESTHandler) { +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, phs []ProposalRESTHandler) { propSubRtr := r.PathPrefix("/gov/proposals").Subrouter() for _, ph := range phs { propSubRtr.HandleFunc(fmt.Sprintf("/%s", ph.SubRoute), ph.Handler).Methods("POST") diff --git a/x/gov/module.go b/x/gov/module.go index e5fb297b0bc5..672a7742cf0e 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -12,7 +12,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" + "github.com/cosmos/cosmos-sdk/x/gov/client" + "github.com/cosmos/cosmos-sdk/x/gov/client/cli" "github.com/cosmos/cosmos-sdk/x/gov/client/rest" "github.com/cosmos/cosmos-sdk/x/gov/types" ) @@ -24,13 +25,13 @@ var ( // app module basics object type AppModuleBasic struct { - proposalCmds []*cobra.Command // proposal subcommands which live in governance + proposalHandlers []client.ProposalHandler // proposal handlers which live in governance cli and rest } // NewAppModuleBasic creates a new AppModuleBasic object -func NewAppModuleBasic(proposalCmds ...*cobra.Command) AppModuleBasic { +func NewAppModuleBasic(proposalHandlers ...client.ProposalHandler) AppModuleBasic { return AppModuleBasic{ - proposalCmds: proposalCmds, + proposalHandlers: proposalHandlers, } } @@ -62,15 +63,25 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { } // register rest routes -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { +func (a AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { - // XXX include ProposalRESTHandler ?? - rest.RegisterRoutes(ctx, rtr, cdc) + var proposalRESTHandlers []rest.ProposalRESTHandler + for _, proposalHandler := range a.proposalHandlers { + proposalRESTHandlers = append(proposalRESTHandlers, proposalHandler.RESTHandler(ctx, cdc)) + } + + rest.RegisterRoutes(ctx, rtr, cdc, proposalRESTHandlers) } // get the root tx command of this module -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd(StoreKey, ModuleCdc) +func (a AppModuleBasic) GetTxCmd() *cobra.Command { + + var proposalCLIHandlers []*cobra.Command + for _, proposalHandler := range a.proposalHandlers { + proposalCLIHandlers = append(proposalCLIHandlers, proposalHandler.CLIHandler) + } + + return cli.GetTxCmd(StoreKey, ModuleCdc, proposalCLIHandlers) } // get the root query command of this module diff --git a/x/gov/params.go b/x/gov/types/params.go similarity index 97% rename from x/gov/params.go rename to x/gov/types/params.go index d12658967a6f..9a766452b54f 100644 --- a/x/gov/params.go +++ b/x/gov/types/params.go @@ -1,11 +1,11 @@ -package gov +package types import ( "fmt" "time" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params" + params "github.com/cosmos/cosmos-sdk/x/params/subspace" ) // Parameter store key diff --git a/x/params/client/proposal_handler.go b/x/params/client/proposal_handler.go new file mode 100644 index 000000000000..bc953e601ecf --- /dev/null +++ b/x/params/client/proposal_handler.go @@ -0,0 +1,10 @@ +package client + +import ( + govclient "github.com/cosmos/cosmos-sdk/x/gov/client" + "github.com/cosmos/cosmos-sdk/x/params/client/cli" + "github.com/cosmos/cosmos-sdk/x/params/client/rest" +) + +// param change proposal handler +var ProposalHandler = govclient.NewProposalHandler(cli.GetCmdSubmitProposal(), rest.ProposalRESTHandler) From d010ed7959d1c5f9af22d88363c140009ccc5c3f Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 31 May 2019 18:59:09 -0400 Subject: [PATCH 11/23] client routes --- client/routes.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 client/routes.go diff --git a/client/routes.go b/client/routes.go new file mode 100644 index 000000000000..99d52d0ac8a4 --- /dev/null +++ b/client/routes.go @@ -0,0 +1,14 @@ +package client + +import ( + "github.com/gorilla/mux" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" +) + +// Register routes +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { + RegisterRPCRoutes(cliCtx, r) + RegisterTxRoutes(cliCtx, r, cdc) +} From f7246b660176c6e130d4ce9e85f19ae814d33a9b Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 31 May 2019 19:05:24 -0400 Subject: [PATCH 12/23] cl --- .pending/improvements/sdk/4451-RegisterRoutes- | 1 + 1 file changed, 1 insertion(+) create mode 100644 .pending/improvements/sdk/4451-RegisterRoutes- diff --git a/.pending/improvements/sdk/4451-RegisterRoutes- b/.pending/improvements/sdk/4451-RegisterRoutes- new file mode 100644 index 000000000000..8d638c3c3441 --- /dev/null +++ b/.pending/improvements/sdk/4451-RegisterRoutes- @@ -0,0 +1 @@ +#4451 RegisterRoutes and ModuleClient to BasicModule pattern \ No newline at end of file From 27a52d4be9e259d1cf7fc7ab721cf3f99a7af10c Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Mon, 3 Jun 2019 15:29:13 -0400 Subject: [PATCH 13/23] @jleni comments --- client/keys/codec.go | 1 + crypto/keys/codec.go | 6 +- crypto/ledger_secp256k1.go | 2 +- types/config.go | 8 +-- types/module/module.go | 85 ++++++++++++----------- x/auth/genaccounts/codec.go | 3 +- x/auth/types/codec.go | 3 +- x/bank/module.go | 2 - x/bank/types/codec.go | 3 +- x/crisis/types/codec.go | 3 +- x/distribution/keeper/proposal_handler.go | 2 +- x/distribution/types/codec.go | 3 +- x/genutil/codec.go | 3 +- x/mint/types/codec.go | 3 +- x/params/types/codec.go | 3 +- x/slashing/types/codec.go | 3 +- x/slashing/types/keys.go | 8 ++- x/staking/types/codec.go | 3 +- 18 files changed, 79 insertions(+), 65 deletions(-) diff --git a/client/keys/codec.go b/client/keys/codec.go index 6bbb16850711..eae45446e784 100644 --- a/client/keys/codec.go +++ b/client/keys/codec.go @@ -9,6 +9,7 @@ var cdc *codec.Codec func init() { cdc = codec.New() codec.RegisterCrypto(cdc) + cdc.Seal() } // marshal keys diff --git a/crypto/keys/codec.go b/crypto/keys/codec.go index d85eeb3427ea..3181a9ef3e60 100644 --- a/crypto/keys/codec.go +++ b/crypto/keys/codec.go @@ -1,15 +1,16 @@ package keys import ( - amino "github.com/tendermint/go-amino" cryptoAmino "github.com/tendermint/tendermint/crypto/encoding/amino" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/hd" ) -var cdc = amino.NewCodec() +var cdc *codec.Codec func init() { + cdc = codec.New() cryptoAmino.RegisterAmino(cdc) cdc.RegisterInterface((*Info)(nil), nil) cdc.RegisterConcrete(hd.BIP44Params{}, "crypto/keys/hd/BIP44Params", nil) @@ -17,4 +18,5 @@ func init() { cdc.RegisterConcrete(ledgerInfo{}, "crypto/keys/ledgerInfo", nil) cdc.RegisterConcrete(offlineInfo{}, "crypto/keys/offlineInfo", nil) cdc.RegisterConcrete(multiInfo{}, "crypto/keys/multiInfo", nil) + cdc.Seal() } diff --git a/crypto/ledger_secp256k1.go b/crypto/ledger_secp256k1.go index f2070f6657a9..ba3b2e8e2bce 100644 --- a/crypto/ledger_secp256k1.go +++ b/crypto/ledger_secp256k1.go @@ -102,7 +102,7 @@ func (pkl PrivKeyLedgerSecp256k1) Sign(message []byte) ([]byte, error) { return sign(device, pkl, message) } -// LedgerShowAddress triggers a ledger device to show the corresponding sdk. +// LedgerShowAddress triggers a ledger device to show the corresponding address. func LedgerShowAddress(path hd.BIP44Params, expectedPubKey tmcrypto.PubKey) error { device, err := getLedgerDevice() if err != nil { diff --git a/types/config.go b/types/config.go index 9b6812d9c0d4..ce116352f2bb 100644 --- a/types/config.go +++ b/types/config.go @@ -85,13 +85,13 @@ func (config *Config) SetAddressVerifier(addressVerifier func([]byte) error) { config.addressVerifier = addressVerifier } -// TODO +// Set the BIP-0044 CoinType code on the config func (config *Config) SetCoinType(coinType uint32) { config.assertNotSealed() config.coinType = coinType } -// TODO +// Set the FullFundraiserPath (BIP44Prefix) on the config func (config *Config) SetFullFundraiserPath(fullFundraiserPath string) { config.assertNotSealed() config.fullFundraiserPath = fullFundraiserPath @@ -146,12 +146,12 @@ func (config *Config) GetAddressVerifier() func([]byte) error { return config.addressVerifier } -// TODO +// Get the BIP-0044 CoinType code on the config func (config *Config) GetCoinType() uint32 { return config.coinType } -// TODO +// Get the FullFundraiserPath (BIP44Prefix) on the config func (config *Config) GetFullFundraiserPath() string { return config.fullFundraiserPath } diff --git a/types/module/module.go b/types/module/module.go index bfa8d68ea7e2..d5cc27b36f1a 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -26,6 +26,7 @@ import ( "github.com/gorilla/mux" "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/client/context" @@ -57,25 +58,25 @@ func NewBasicManager(modules ...AppModuleBasic) BasicManager { } // RegisterCodecs registers all module codecs -func (mbm BasicManager) RegisterCodec(cdc *codec.Codec) { - for _, mb := range mbm { - mb.RegisterCodec(cdc) +func (bm BasicManager) RegisterCodec(cdc *codec.Codec) { + for _, b := range bm { + b.RegisterCodec(cdc) } } // Provided default genesis information for all modules -func (mbm BasicManager) DefaultGenesis() map[string]json.RawMessage { +func (bm BasicManager) DefaultGenesis() map[string]json.RawMessage { genesis := make(map[string]json.RawMessage) - for _, mb := range mbm { - genesis[mb.Name()] = mb.DefaultGenesis() + for _, b := range bm { + genesis[b.Name()] = b.DefaultGenesis() } return genesis } // Provided default genesis information for all modules -func (mbm BasicManager) ValidateGenesis(genesis map[string]json.RawMessage) error { - for _, mb := range mbm { - if err := mb.ValidateGenesis(genesis[mb.Name()]); err != nil { +func (bm BasicManager) ValidateGenesis(genesis map[string]json.RawMessage) error { + for _, b := range bm { + if err := b.ValidateGenesis(genesis[b.Name()]); err != nil { return err } } @@ -83,27 +84,27 @@ func (mbm BasicManager) ValidateGenesis(genesis map[string]json.RawMessage) erro } // RegisterRestRoutes registers all module rest routes -func (mbm BasicManager) RegisterRESTRoutes( +func (bm BasicManager) RegisterRESTRoutes( ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { - for _, mb := range mbm { - mb.RegisterRESTRoutes(ctx, rtr, cdc) + for _, b := range bm { + b.RegisterRESTRoutes(ctx, rtr, cdc) } } // add all tx commands to the rootTxCmd -func (mbm BasicManager) AddTxCommands(rootTxCmd *cobra.Command) { - for _, mb := range mbm { - if cmd := mb.GetTxCmd(); cmd != nil { +func (bm BasicManager) AddTxCommands(rootTxCmd *cobra.Command) { + for _, b := range bm { + if cmd := b.GetTxCmd(); cmd != nil { rootTxCmd.AddCommand(cmd) } } } // add all query commands to the rootQueryCmd -func (mbm BasicManager) AddQueryCommands(rootQueryCmd *cobra.Command) { - for _, mb := range mbm { - if cmd := mb.GetQueryCmd(); cmd != nil { +func (bm BasicManager) AddQueryCommands(rootQueryCmd *cobra.Command) { + for _, b := range bm { + if cmd := b.GetQueryCmd(); cmd != nil { rootQueryCmd.AddCommand(cmd) } } @@ -203,35 +204,35 @@ func NewManager(modules ...AppModule) *Manager { } // set the order of init genesis calls -func (mm *Manager) SetOrderInitGenesis(moduleNames ...string) { - mm.OrderInitGenesis = moduleNames +func (m *Manager) SetOrderInitGenesis(moduleNames ...string) { + m.OrderInitGenesis = moduleNames } // set the order of export genesis calls -func (mm *Manager) SetOrderExportGenesis(moduleNames ...string) { - mm.OrderExportGenesis = moduleNames +func (m *Manager) SetOrderExportGenesis(moduleNames ...string) { + m.OrderExportGenesis = moduleNames } // set the order of set begin-blocker calls -func (mm *Manager) SetOrderBeginBlockers(moduleNames ...string) { - mm.OrderBeginBlockers = moduleNames +func (m *Manager) SetOrderBeginBlockers(moduleNames ...string) { + m.OrderBeginBlockers = moduleNames } // set the order of set end-blocker calls -func (mm *Manager) SetOrderEndBlockers(moduleNames ...string) { - mm.OrderEndBlockers = moduleNames +func (m *Manager) SetOrderEndBlockers(moduleNames ...string) { + m.OrderEndBlockers = moduleNames } // register all module routes and module querier routes -func (mm *Manager) RegisterInvariants(invarRouter sdk.InvariantRouter) { - for _, module := range mm.Modules { +func (m *Manager) RegisterInvariants(invarRouter sdk.InvariantRouter) { + for _, module := range m.Modules { module.RegisterInvariants(invarRouter) } } // register all module routes and module querier routes -func (mm *Manager) RegisterRoutes(router sdk.Router, queryRouter sdk.QueryRouter) { - for _, module := range mm.Modules { +func (m *Manager) RegisterRoutes(router sdk.Router, queryRouter sdk.QueryRouter) { + for _, module := range m.Modules { if module.Route() != "" { router.AddRoute(module.Route(), module.NewHandler()) } @@ -242,13 +243,13 @@ func (mm *Manager) RegisterRoutes(router sdk.Router, queryRouter sdk.QueryRouter } // perform init genesis functionality for modules -func (mm *Manager) InitGenesis(ctx sdk.Context, genesisData map[string]json.RawMessage) abci.ResponseInitChain { +func (m *Manager) InitGenesis(ctx sdk.Context, genesisData map[string]json.RawMessage) abci.ResponseInitChain { var validatorUpdates []abci.ValidatorUpdate - for _, moduleName := range mm.OrderInitGenesis { + for _, moduleName := range m.OrderInitGenesis { if genesisData[moduleName] == nil { continue } - moduleValUpdates := mm.Modules[moduleName].InitGenesis(ctx, genesisData[moduleName]) + moduleValUpdates := m.Modules[moduleName].InitGenesis(ctx, genesisData[moduleName]) // use these validator updates if provided, the module manager assumes // only one module will update the validator set @@ -265,19 +266,19 @@ func (mm *Manager) InitGenesis(ctx sdk.Context, genesisData map[string]json.RawM } // perform export genesis functionality for modules -func (mm *Manager) ExportGenesis(ctx sdk.Context) map[string]json.RawMessage { +func (m *Manager) ExportGenesis(ctx sdk.Context) map[string]json.RawMessage { genesisData := make(map[string]json.RawMessage) - for _, moduleName := range mm.OrderExportGenesis { - genesisData[moduleName] = mm.Modules[moduleName].ExportGenesis(ctx) + for _, moduleName := range m.OrderExportGenesis { + genesisData[moduleName] = m.Modules[moduleName].ExportGenesis(ctx) } return genesisData } // perform begin block functionality for modules -func (mm *Manager) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { +func (m *Manager) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { tags := sdk.EmptyTags() - for _, moduleName := range mm.OrderBeginBlockers { - moduleTags := mm.Modules[moduleName].BeginBlock(ctx, req) + for _, moduleName := range m.OrderBeginBlockers { + moduleTags := m.Modules[moduleName].BeginBlock(ctx, req) tags = tags.AppendTags(moduleTags) } @@ -287,11 +288,11 @@ func (mm *Manager) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) abci. } // perform end block functionality for modules -func (mm *Manager) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { +func (m *Manager) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { validatorUpdates := []abci.ValidatorUpdate{} tags := sdk.EmptyTags() - for _, moduleName := range mm.OrderEndBlockers { - moduleValUpdates, moduleTags := mm.Modules[moduleName].EndBlock(ctx, req) + for _, moduleName := range m.OrderEndBlockers { + moduleValUpdates, moduleTags := m.Modules[moduleName].EndBlock(ctx, req) tags = tags.AppendTags(moduleTags) // use these validator updates if provided, the module manager assumes diff --git a/x/auth/genaccounts/codec.go b/x/auth/genaccounts/codec.go index 184bfc94c168..70edd800e3d1 100644 --- a/x/auth/genaccounts/codec.go +++ b/x/auth/genaccounts/codec.go @@ -5,9 +5,10 @@ import ( ) // generic sealed codec to be used throughout this module -var moduleCdc = codec.New() +var moduleCdc *codec.Codec func init() { + moduleCdc = codec.New() codec.RegisterCrypto(moduleCdc) moduleCdc.Seal() } diff --git a/x/auth/types/codec.go b/x/auth/types/codec.go index 6cb924687aed..296c2b148356 100644 --- a/x/auth/types/codec.go +++ b/x/auth/types/codec.go @@ -27,9 +27,10 @@ func RegisterBaseAccount(cdc *codec.Codec) { } // module wide codec -var ModuleCdc = codec.New() +var ModuleCdc *codec.Codec func init() { + ModuleCdc = codec.New() RegisterCodec(ModuleCdc) codec.RegisterCrypto(ModuleCdc) ModuleCdc.Seal() diff --git a/x/bank/module.go b/x/bank/module.go index 2ccaae5041c4..c50cb56a64e2 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -57,11 +57,9 @@ func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router rest.RegisterRoutes(ctx, rtr, cdc) } -// TODO // get the root tx command of this module func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } -// TODO // get the root query command of this module func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } diff --git a/x/bank/types/codec.go b/x/bank/types/codec.go index 2018e685f43d..6d4d49adc118 100644 --- a/x/bank/types/codec.go +++ b/x/bank/types/codec.go @@ -11,9 +11,10 @@ func RegisterCodec(cdc *codec.Codec) { } // module codec -var ModuleCdc = codec.New() +var ModuleCdc *codec.Codec func init() { + ModuleCdc = codec.New() RegisterCodec(ModuleCdc) ModuleCdc.Seal() } diff --git a/x/crisis/types/codec.go b/x/crisis/types/codec.go index 6347228282c4..92aeb130bce8 100644 --- a/x/crisis/types/codec.go +++ b/x/crisis/types/codec.go @@ -10,9 +10,10 @@ func RegisterCodec(cdc *codec.Codec) { } // generic sealed codec to be used throughout module -var ModuleCdc = codec.New() +var ModuleCdc *codec.Codec func init() { + ModuleCdc = codec.New() RegisterCodec(ModuleCdc) codec.RegisterCrypto(ModuleCdc) ModuleCdc.Seal() diff --git a/x/distribution/keeper/proposal_handler.go b/x/distribution/keeper/proposal_handler.go index f2e11cad3031..70b0bebaa309 100644 --- a/x/distribution/keeper/proposal_handler.go +++ b/x/distribution/keeper/proposal_handler.go @@ -7,7 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/distribution/types" ) -// TODO +// Handler for executing a passed community spend proposal func HandleCommunityPoolSpendProposal(ctx sdk.Context, k Keeper, p types.CommunityPoolSpendProposal) sdk.Error { feePool := k.GetFeePool(ctx) newPool, negative := feePool.CommunityPool.SafeSub(sdk.NewDecCoins(p.Amount)) diff --git a/x/distribution/types/codec.go b/x/distribution/types/codec.go index 95c624dd6ff6..a2d4bf11eaae 100644 --- a/x/distribution/types/codec.go +++ b/x/distribution/types/codec.go @@ -13,9 +13,10 @@ func RegisterCodec(cdc *codec.Codec) { } // generic sealed codec to be used throughout module -var ModuleCdc = codec.New() +var ModuleCdc *codec.Codec func init() { + ModuleCdc = codec.New() RegisterCodec(ModuleCdc) codec.RegisterCrypto(ModuleCdc) ModuleCdc.Seal() diff --git a/x/genutil/codec.go b/x/genutil/codec.go index 656578a2a64a..a9752fa223c5 100644 --- a/x/genutil/codec.go +++ b/x/genutil/codec.go @@ -8,11 +8,12 @@ import ( ) // generic sealed codec to be used throughout this module -var moduleCdc = codec.New() +var moduleCdc *codec.Codec // TODO abstract genesis transactions registration back to staking // required for genesis transactions func init() { + moduleCdc = codec.New() staking.RegisterCodec(moduleCdc) auth.RegisterCodec(moduleCdc) sdk.RegisterCodec(moduleCdc) diff --git a/x/mint/types/codec.go b/x/mint/types/codec.go index 189205827bf5..5787f242adfe 100644 --- a/x/mint/types/codec.go +++ b/x/mint/types/codec.go @@ -5,9 +5,10 @@ import ( ) // generic sealed codec to be used throughout this module -var ModuleCdc = codec.New() +var ModuleCdc *codec.Codec func init() { + ModuleCdc = codec.New() codec.RegisterCrypto(ModuleCdc) ModuleCdc.Seal() } diff --git a/x/params/types/codec.go b/x/params/types/codec.go index 78e1e1940f72..525836346f90 100644 --- a/x/params/types/codec.go +++ b/x/params/types/codec.go @@ -5,9 +5,10 @@ import ( ) // module codec -var ModuleCdc = codec.New() +var ModuleCdc *codec.Codec func init() { + ModuleCdc = codec.New() RegisterCodec(ModuleCdc) ModuleCdc.Seal() } diff --git a/x/slashing/types/codec.go b/x/slashing/types/codec.go index 52542aac04fe..1a4d62c4e190 100644 --- a/x/slashing/types/codec.go +++ b/x/slashing/types/codec.go @@ -10,9 +10,10 @@ func RegisterCodec(cdc *codec.Codec) { } // module codec -var ModuleCdc = codec.New() +var ModuleCdc *codec.Codec func init() { + ModuleCdc = codec.New() RegisterCodec(ModuleCdc) codec.RegisterCrypto(ModuleCdc) ModuleCdc.Seal() diff --git a/x/slashing/types/keys.go b/x/slashing/types/keys.go index 2051e8f14dd5..65e52a12786a 100644 --- a/x/slashing/types/keys.go +++ b/x/slashing/types/keys.go @@ -6,8 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// nolint const ( + // module name ModuleName = "slashing" // StoreKey is the store key string for slashing @@ -18,8 +18,10 @@ const ( // QuerierRoute is the querier route for slashing QuerierRoute = ModuleName +) - // Query endpoints supported by the slashing querier +// Query endpoints supported by the slashing querier +const ( QueryParameters = "parameters" QuerySigningInfo = "signingInfo" QuerySigningInfos = "signingInfos" @@ -72,7 +74,7 @@ func GetValidatorSlashingPeriodKey(v sdk.ConsAddress, startHeight int64) []byte return append(GetValidatorSlashingPeriodPrefix(v), b...) } -// TODO +// get pubkey relation key used to get the pubkey from the address func GetAddrPubkeyRelationKey(address []byte) []byte { return append(AddrPubkeyRelationKey, address...) } diff --git a/x/staking/types/codec.go b/x/staking/types/codec.go index 4444f81c00f0..6fadfd9a68f9 100644 --- a/x/staking/types/codec.go +++ b/x/staking/types/codec.go @@ -14,9 +14,10 @@ func RegisterCodec(cdc *codec.Codec) { } // generic sealed codec to be used throughout this module -var ModuleCdc = codec.New() +var ModuleCdc *codec.Codec func init() { + ModuleCdc = codec.New() RegisterCodec(ModuleCdc) codec.RegisterCrypto(ModuleCdc) ModuleCdc.Seal() From 71bf69250de7b2d0bf72f654cbe227ecc8d3a196 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Mon, 3 Jun 2019 16:30:52 -0400 Subject: [PATCH 14/23] @fedekunze pr comments int int --- crypto/ledger_test.go | 3 +- x/auth/ante.go | 53 ++-- x/auth/module.go | 2 - x/staking/alias.go | 52 ++-- x/staking/client/cli/query.go | 31 ++- x/staking/client/rest/query.go | 17 +- x/staking/client/rest/utils.go | 8 +- x/staking/{querier => keeper}/querier.go | 229 ++++++++---------- x/staking/{querier => keeper}/querier_test.go | 155 ++++++------ x/staking/querier/utils.go | 71 ------ x/staking/types/expected_keepers.go | 4 +- x/staking/types/querier.go | 98 ++++++++ 12 files changed, 358 insertions(+), 365 deletions(-) rename x/staking/{querier => keeper}/querier.go (65%) rename x/staking/{querier => keeper}/querier_test.go (68%) delete mode 100644 x/staking/querier/utils.go create mode 100644 x/staking/types/querier.go diff --git a/crypto/ledger_test.go b/crypto/ledger_test.go index 24407d00e838..0f726b410d55 100644 --- a/crypto/ledger_test.go +++ b/crypto/ledger_test.go @@ -9,9 +9,8 @@ import ( tmcrypto "github.com/tendermint/tendermint/crypto" cryptoAmino "github.com/tendermint/tendermint/crypto/encoding/amino" - "github.com/cosmos/cosmos-sdk/tests" - "github.com/cosmos/cosmos-sdk/crypto/keys/hd" + "github.com/cosmos/cosmos-sdk/tests" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/auth/ante.go b/x/auth/ante.go index 71662ed15024..28a16821e9ac 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -14,7 +14,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( @@ -30,24 +29,24 @@ func init() { } // SignatureVerificationGasConsumer is the type of function that is used to both consume gas when verifying signatures -// and also to accept or reject different types of PubKey's. This is where apps can define their own PubKey types. -type SignatureVerificationGasConsumer = func(meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params types.Params) sdk.Result +// and also to accept or reject different types of PubKey's. This is where apps can define their own PubKey +type SignatureVerificationGasConsumer = func(meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params Params) sdk.Result // NewAnteHandler returns an AnteHandler that checks and increments sequence // numbers, checks signatures & account numbers, and deducts fees from the first // signer. -func NewAnteHandler(ak AccountKeeper, fck types.FeeCollectionKeeper, sigGasConsumer SignatureVerificationGasConsumer) sdk.AnteHandler { +func NewAnteHandler(ak AccountKeeper, fck FeeCollectionKeeper, sigGasConsumer SignatureVerificationGasConsumer) sdk.AnteHandler { return func( ctx sdk.Context, tx sdk.Tx, simulate bool, ) (newCtx sdk.Context, res sdk.Result, abort bool) { - // all transactions must be of type auth.types.StdTx - stdTx, ok := tx.(types.StdTx) + // all transactions must be of type auth.StdTx + stdTx, ok := tx.(StdTx) if !ok { // Set a gas meter with limit 0 as to prevent an infinite gas meter attack // during runTx. newCtx = SetGasMeter(simulate, ctx, 0) - return newCtx, sdk.ErrInternal("tx must be types.StdTx").Result(), true + return newCtx, sdk.ErrInternal("tx must be StdTx").Result(), true } params := ak.GetParams(ctx) @@ -104,7 +103,7 @@ func NewAnteHandler(ak AccountKeeper, fck types.FeeCollectionKeeper, sigGasConsu // stdSigs contains the sequence number, account number, and signatures. // When simulating, this would just be a 0-length slice. signerAddrs := stdTx.GetSigners() - signerAccs := make([]types.Account, len(signerAddrs)) + signerAccs := make([]Account, len(signerAddrs)) isGenesis := ctx.BlockHeight() == 0 // fetch first signer, who's going to pay the fees @@ -152,7 +151,7 @@ func NewAnteHandler(ak AccountKeeper, fck types.FeeCollectionKeeper, sigGasConsu // GetSignerAcc returns an account for a given address that is expected to sign // a transaction. -func GetSignerAcc(ctx sdk.Context, ak AccountKeeper, addr sdk.AccAddress) (types.Account, sdk.Result) { +func GetSignerAcc(ctx sdk.Context, ak AccountKeeper, addr sdk.AccAddress) (Account, sdk.Result) { if acc := ak.GetAccount(ctx, addr); acc != nil { return acc, sdk.Result{} } @@ -161,12 +160,12 @@ func GetSignerAcc(ctx sdk.Context, ak AccountKeeper, addr sdk.AccAddress) (types // ValidateSigCount validates that the transaction has a valid cumulative total // amount of signatures. -func ValidateSigCount(stdTx types.StdTx, params types.Params) sdk.Result { +func ValidateSigCount(stdTx StdTx, params Params) sdk.Result { stdSigs := stdTx.GetSignatures() sigCount := 0 for i := 0; i < len(stdSigs); i++ { - sigCount += types.CountSubKeys(stdSigs[i].PubKey) + sigCount += CountSubKeys(stdSigs[i].PubKey) if uint64(sigCount) > params.TxSigLimit { return sdk.ErrTooManySignatures( fmt.Sprintf("signatures: %d, limit: %d", sigCount, params.TxSigLimit), @@ -178,7 +177,7 @@ func ValidateSigCount(stdTx types.StdTx, params types.Params) sdk.Result { } // ValidateMemo validates the memo size. -func ValidateMemo(stdTx types.StdTx, params types.Params) sdk.Result { +func ValidateMemo(stdTx StdTx, params Params) sdk.Result { memoLength := len(stdTx.GetMemo()) if uint64(memoLength) > params.MaxMemoCharacters { return sdk.ErrMemoTooLarge( @@ -195,9 +194,9 @@ func ValidateMemo(stdTx types.StdTx, params types.Params) sdk.Result { // verify the signature and increment the sequence. If the account doesn't have // a pubkey, set it. func processSig( - ctx sdk.Context, acc types.Account, sig types.StdSignature, signBytes []byte, simulate bool, params types.Params, + ctx sdk.Context, acc Account, sig StdSignature, signBytes []byte, simulate bool, params Params, sigGasConsumer SignatureVerificationGasConsumer, -) (updatedAcc types.Account, res sdk.Result) { +) (updatedAcc Account, res sdk.Result) { pubKey, res := ProcessPubKey(acc, sig, simulate) if !res.IsOK() { @@ -212,7 +211,7 @@ func processSig( if simulate { // Simulated txs should not contain a signature and are not required to // contain a pubkey, so we must account for tx size of including a - // types.StdSignature (Amino encoding) and simulate gas consumption + // StdSignature (Amino encoding) and simulate gas consumption // (assuming a SECP256k1 simulation key). consumeSimSigGas(ctx.GasMeter(), pubKey, sig, params) } @@ -232,13 +231,13 @@ func processSig( return acc, res } -func consumeSimSigGas(gasmeter sdk.GasMeter, pubkey crypto.PubKey, sig types.StdSignature, params types.Params) { - simSig := types.StdSignature{PubKey: pubkey} +func consumeSimSigGas(gasmeter sdk.GasMeter, pubkey crypto.PubKey, sig StdSignature, params Params) { + simSig := StdSignature{PubKey: pubkey} if len(sig.Signature) == 0 { simSig.Signature = simSecp256k1Sig[:] } - sigBz := types.ModuleCdc.MustMarshalBinaryLengthPrefixed(simSig) + sigBz := ModuleCdc.MustMarshalBinaryLengthPrefixed(simSig) cost := sdk.Gas(len(sigBz) + 6) // If the pubkey is a multi-signature pubkey, then we estimate for the maximum @@ -251,10 +250,10 @@ func consumeSimSigGas(gasmeter sdk.GasMeter, pubkey crypto.PubKey, sig types.Std } // ProcessPubKey verifies that the given account address matches that of the -// types.StdSignature. In addition, it will set the public key of the account if it +// StdSignature. In addition, it will set the public key of the account if it // has not been set. -func ProcessPubKey(acc types.Account, sig types.StdSignature, simulate bool) (crypto.PubKey, sdk.Result) { - // If pubkey is not known for account, set it from the types.StdSignature. +func ProcessPubKey(acc Account, sig StdSignature, simulate bool) (crypto.PubKey, sdk.Result) { + // If pubkey is not known for account, set it from the StdSignature. pubKey := acc.GetPubKey() if simulate { // In simulate mode the transaction comes with no signatures, thus if the @@ -287,7 +286,7 @@ func ProcessPubKey(acc types.Account, sig types.StdSignature, simulate bool) (cr // for signature verification based upon the public key type. The cost is fetched from the given params and is matched // by the concrete type. func DefaultSigVerificationGasConsumer( - meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params types.Params, + meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params Params, ) sdk.Result { switch pubkey := pubkey.(type) { case ed25519.PubKeyEd25519: @@ -312,7 +311,7 @@ func DefaultSigVerificationGasConsumer( func consumeMultisignatureVerificationGas(meter sdk.GasMeter, sig multisig.Multisignature, pubkey multisig.PubKeyMultisigThreshold, - params types.Params) { + params Params) { size := sig.BitArray.Size() sigIndex := 0 @@ -328,7 +327,7 @@ func consumeMultisignatureVerificationGas(meter sdk.GasMeter, // // NOTE: We could use the CoinKeeper (in addition to the AccountKeeper, because // the CoinKeeper doesn't give us accounts), but it seems easier to do this. -func DeductFees(blockTime time.Time, acc types.Account, fee types.StdFee) (types.Account, sdk.Result) { +func DeductFees(blockTime time.Time, acc Account, fee StdFee) (Account, sdk.Result) { coins := acc.GetCoins() feeAmount := fee.Amount @@ -366,7 +365,7 @@ func DeductFees(blockTime time.Time, acc types.Account, fee types.StdFee) (types // // Contract: This should only be called during CheckTx as it cannot be part of // consensus. -func EnsureSufficientMempoolFees(ctx sdk.Context, stdFee types.StdFee) sdk.Result { +func EnsureSufficientMempoolFees(ctx sdk.Context, stdFee StdFee) sdk.Result { minGasPrices := ctx.MinGasPrices() if !minGasPrices.IsZero() { requiredFees := make(sdk.Coins, len(minGasPrices)) @@ -404,13 +403,13 @@ func SetGasMeter(simulate bool, ctx sdk.Context, gasLimit uint64) sdk.Context { // GetSignBytes returns a slice of bytes to sign over for a given transaction // and an account. -func GetSignBytes(chainID string, stdTx types.StdTx, acc types.Account, genesis bool) []byte { +func GetSignBytes(chainID string, stdTx StdTx, acc Account, genesis bool) []byte { var accNum uint64 if !genesis { accNum = acc.GetAccountNumber() } - return types.StdSignBytes( + return StdSignBytes( chainID, accNum, acc.GetSequence(), stdTx.Fee, stdTx.Msgs, stdTx.Memo, ) } diff --git a/x/auth/module.go b/x/auth/module.go index bb28ceb0a9fe..ca66d6e8e036 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -53,11 +53,9 @@ func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router rest.RegisterRoutes(ctx, rtr, cdc, types.StoreKey) } -// TODO // get the root tx command of this module func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } -// TODO // get the root query command of this module func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } diff --git a/x/staking/alias.go b/x/staking/alias.go index b4cd13044c3f..78ea9cb84e8a 100644 --- a/x/staking/alias.go +++ b/x/staking/alias.go @@ -2,32 +2,16 @@ // autogenerated code using github.com/rigelrozanski/multitool // aliases generated for the following subdirectories: // ALIASGEN: github.com/cosmos/cosmos-sdk/x/staking/keeper -// ALIASGEN: github.com/cosmos/cosmos-sdk/x/staking/querier // ALIASGEN: github.com/cosmos/cosmos-sdk/x/staking/types package staking import ( "github.com/cosmos/cosmos-sdk/x/staking/keeper" - "github.com/cosmos/cosmos-sdk/x/staking/querier" "github.com/cosmos/cosmos-sdk/x/staking/types" ) const ( DefaultParamspace = keeper.DefaultParamspace - QueryValidators = querier.QueryValidators - QueryValidator = querier.QueryValidator - QueryDelegatorDelegations = querier.QueryDelegatorDelegations - QueryDelegatorUnbondingDelegations = querier.QueryDelegatorUnbondingDelegations - QueryRedelegations = querier.QueryRedelegations - QueryValidatorDelegations = querier.QueryValidatorDelegations - QueryValidatorRedelegations = querier.QueryValidatorRedelegations - QueryValidatorUnbondingDelegations = querier.QueryValidatorUnbondingDelegations - QueryDelegation = querier.QueryDelegation - QueryUnbondingDelegation = querier.QueryUnbondingDelegation - QueryDelegatorValidators = querier.QueryDelegatorValidators - QueryDelegatorValidator = querier.QueryDelegatorValidator - QueryPool = querier.QueryPool - QueryParameters = querier.QueryParameters DefaultCodespace = types.DefaultCodespace CodeInvalidValidator = types.CodeInvalidValidator CodeInvalidDelegation = types.CodeInvalidDelegation @@ -45,6 +29,20 @@ const ( DefaultUnbondingTime = types.DefaultUnbondingTime DefaultMaxValidators = types.DefaultMaxValidators DefaultMaxEntries = types.DefaultMaxEntries + QueryValidators = types.QueryValidators + QueryValidator = types.QueryValidator + QueryDelegatorDelegations = types.QueryDelegatorDelegations + QueryDelegatorUnbondingDelegations = types.QueryDelegatorUnbondingDelegations + QueryRedelegations = types.QueryRedelegations + QueryValidatorDelegations = types.QueryValidatorDelegations + QueryValidatorRedelegations = types.QueryValidatorRedelegations + QueryValidatorUnbondingDelegations = types.QueryValidatorUnbondingDelegations + QueryDelegation = types.QueryDelegation + QueryUnbondingDelegation = types.QueryUnbondingDelegation + QueryDelegatorValidators = types.QueryDelegatorValidators + QueryDelegatorValidator = types.QueryDelegatorValidator + QueryPool = types.QueryPool + QueryParameters = types.QueryParameters MaxMonikerLength = types.MaxMonikerLength MaxIdentityLength = types.MaxIdentityLength MaxWebsiteLength = types.MaxWebsiteLength @@ -62,6 +60,7 @@ var ( DelegatorSharesInvariant = keeper.DelegatorSharesInvariant NewKeeper = keeper.NewKeeper ParamKeyTable = keeper.ParamKeyTable + NewQuerier = keeper.NewQuerier ValEq = keeper.ValEq MakeTestCodec = keeper.MakeTestCodec CreateTestInput = keeper.CreateTestInput @@ -71,12 +70,6 @@ var ( TestingUpdateValidator = keeper.TestingUpdateValidator RandomValidator = keeper.RandomValidator RandomBondedValidator = keeper.RandomBondedValidator - NewQuerier = querier.NewQuerier - NewQueryDelegatorParams = querier.NewQueryDelegatorParams - NewQueryValidatorParams = querier.NewQueryValidatorParams - NewQueryBondsParams = querier.NewQueryBondsParams - NewQueryRedelegationParams = querier.NewQueryRedelegationParams - NewQueryValidatorsParams = querier.NewQueryValidatorsParams RegisterCodec = types.RegisterCodec NewCommissionMsg = types.NewCommissionMsg NewCommission = types.NewCommission @@ -183,6 +176,11 @@ var ( InitialPool = types.InitialPool MustUnmarshalPool = types.MustUnmarshalPool UnmarshalPool = types.UnmarshalPool + NewQueryDelegatorParams = types.NewQueryDelegatorParams + NewQueryValidatorParams = types.NewQueryValidatorParams + NewQueryBondsParams = types.NewQueryBondsParams + NewQueryRedelegationParams = types.NewQueryRedelegationParams + NewQueryValidatorsParams = types.NewQueryValidatorsParams NewValidator = types.NewValidator MustMarshalValidator = types.MustMarshalValidator MustUnmarshalValidator = types.MustUnmarshalValidator @@ -216,11 +214,6 @@ var ( type ( Keeper = keeper.Keeper - QueryDelegatorParams = querier.QueryDelegatorParams - QueryValidatorParams = querier.QueryValidatorParams - QueryBondsParams = querier.QueryBondsParams - QueryRedelegationParams = querier.QueryRedelegationParams - QueryValidatorsParams = querier.QueryValidatorsParams Commission = types.Commission CommissionMsg = types.CommissionMsg DVPair = types.DVPair @@ -253,6 +246,11 @@ type ( MsgUndelegate = types.MsgUndelegate Params = types.Params Pool = types.Pool + QueryDelegatorParams = types.QueryDelegatorParams + QueryValidatorParams = types.QueryValidatorParams + QueryBondsParams = types.QueryBondsParams + QueryRedelegationParams = types.QueryRedelegationParams + QueryValidatorsParams = types.QueryValidatorsParams Validator = types.Validator Validators = types.Validators Description = types.Description diff --git a/x/staking/client/cli/query.go b/x/staking/client/cli/query.go index 0c08cfded655..cb9dd5c3b6bb 100644 --- a/x/staking/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -11,7 +11,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/staking/querier" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -133,12 +132,12 @@ $ %s query staking unbonding-delegations-from cosmosvaloper1gghjut3ccd8ay0zduzj6 return err } - bz, err := cdc.MarshalJSON(querier.NewQueryValidatorParams(valAddr)) + bz, err := cdc.MarshalJSON(types.NewQueryValidatorParams(valAddr)) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryValidatorUnbondingDelegations) + route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryValidatorUnbondingDelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -175,12 +174,12 @@ $ %s query staking redelegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fx return err } - bz, err := cdc.MarshalJSON(querier.QueryRedelegationParams{SrcValidatorAddr: valSrcAddr}) + bz, err := cdc.MarshalJSON(types.QueryRedelegationParams{SrcValidatorAddr: valSrcAddr}) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryRedelegations) + route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryRedelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -224,12 +223,12 @@ $ %s query staking delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosm return err } - bz, err := cdc.MarshalJSON(querier.NewQueryBondsParams(delAddr, valAddr)) + bz, err := cdc.MarshalJSON(types.NewQueryBondsParams(delAddr, valAddr)) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryDelegation) + route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryDelegation) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -269,12 +268,12 @@ $ %s query staking delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p return err } - bz, err := cdc.MarshalJSON(querier.NewQueryDelegatorParams(delAddr)) + bz, err := cdc.MarshalJSON(types.NewQueryDelegatorParams(delAddr)) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryDelegatorDelegations) + route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryDelegatorDelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -314,12 +313,12 @@ $ %s query staking delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ld return err } - bz, err := cdc.MarshalJSON(querier.NewQueryValidatorParams(valAddr)) + bz, err := cdc.MarshalJSON(types.NewQueryValidatorParams(valAddr)) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryValidatorDelegations) + route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryValidatorDelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -448,12 +447,12 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co return err } - bz, err := cdc.MarshalJSON(querier.NewQueryRedelegationParams(delAddr, valSrcAddr, valDstAddr)) + bz, err := cdc.MarshalJSON(types.NewQueryRedelegationParams(delAddr, valSrcAddr, valDstAddr)) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryRedelegations) + route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryRedelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -493,12 +492,12 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p return err } - bz, err := cdc.MarshalJSON(querier.QueryRedelegationParams{DelegatorAddr: delAddr}) + bz, err := cdc.MarshalJSON(types.QueryRedelegationParams{DelegatorAddr: delAddr}) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryRedelegations) + route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryRedelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -560,7 +559,7 @@ $ %s query staking params RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - route := fmt.Sprintf("custom/%s/%s", storeName, querier.QueryParameters) + route := fmt.Sprintf("custom/%s/%s", storeName, types.QueryParameters) bz, err := cliCtx.QueryWithData(route, nil) if err != nil { return err diff --git a/x/staking/client/rest/query.go b/x/staking/client/rest/query.go index 869f1b0ab295..14173a6d07fd 100644 --- a/x/staking/client/rest/query.go +++ b/x/staking/client/rest/query.go @@ -5,14 +5,13 @@ import ( "net/http" "strings" + "github.com/gorilla/mux" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/staking/querier" "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/gorilla/mux" ) func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { @@ -104,7 +103,7 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Co // HTTP request handler to query a delegator delegations func delegatorDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryDelegator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, querier.QueryDelegatorDelegations)) + return queryDelegator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegatorDelegations)) } // HTTP request handler to query a delegator unbonding delegations @@ -179,7 +178,7 @@ func unbondingDelegationHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) h // HTTP request handler to query redelegations func redelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var params querier.QueryRedelegationParams + var params types.QueryRedelegationParams bechDelegatorAddr := r.URL.Query().Get("delegator") bechSrcValidatorAddr := r.URL.Query().Get("validator_from") @@ -229,7 +228,7 @@ func redelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Ha // HTTP request handler to query a delegation func delegationHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryBonds(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, querier.QueryDelegation)) + return queryBonds(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegation)) } // HTTP request handler to query all delegator bonded validators @@ -256,14 +255,14 @@ func validatorsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Handl status = sdk.BondStatusBonded } - params := querier.NewQueryValidatorsParams(page, limit, status) + params := types.NewQueryValidatorsParams(page, limit, status) bz, err := cdc.MarshalJSON(params) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, querier.QueryValidators) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryValidators) res, err := cliCtx.QueryWithData(route, bz) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -280,7 +279,7 @@ func validatorHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Handle // HTTP request handler to query all unbonding delegations from a validator func validatorDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryValidator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, querier.QueryValidatorDelegations)) + return queryValidator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryValidatorDelegations)) } // HTTP request handler to query all unbonding delegations from a validator diff --git a/x/staking/client/rest/utils.go b/x/staking/client/rest/utils.go index 21f391dc4d41..d5ad533814f0 100644 --- a/x/staking/client/rest/utils.go +++ b/x/staking/client/rest/utils.go @@ -11,8 +11,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/staking/querier" "github.com/cosmos/cosmos-sdk/x/staking/tags" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // contains checks if the a given query contains one of the tx types @@ -50,7 +50,7 @@ func queryBonds(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string) ht return } - params := querier.NewQueryBondsParams(delegatorAddr, validatorAddr) + params := types.NewQueryBondsParams(delegatorAddr, validatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -78,7 +78,7 @@ func queryDelegator(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string return } - params := querier.NewQueryDelegatorParams(delegatorAddr) + params := types.NewQueryDelegatorParams(delegatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -106,7 +106,7 @@ func queryValidator(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string return } - params := querier.NewQueryValidatorParams(validatorAddr) + params := types.NewQueryValidatorParams(validatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { diff --git a/x/staking/querier/querier.go b/x/staking/keeper/querier.go similarity index 65% rename from x/staking/querier/querier.go rename to x/staking/keeper/querier.go index b18e77263066..807aa11048af 100644 --- a/x/staking/querier/querier.go +++ b/x/staking/keeper/querier.go @@ -1,4 +1,4 @@ -package querier +package keeper import ( "fmt" @@ -8,57 +8,38 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - keep "github.com/cosmos/cosmos-sdk/x/staking/keeper" "github.com/cosmos/cosmos-sdk/x/staking/types" ) -// query endpoints supported by the staking Querier -const ( - QueryValidators = "validators" - QueryValidator = "validator" - QueryDelegatorDelegations = "delegatorDelegations" - QueryDelegatorUnbondingDelegations = "delegatorUnbondingDelegations" - QueryRedelegations = "redelegations" - QueryValidatorDelegations = "validatorDelegations" - QueryValidatorRedelegations = "validatorRedelegations" - QueryValidatorUnbondingDelegations = "validatorUnbondingDelegations" - QueryDelegation = "delegation" - QueryUnbondingDelegation = "unbondingDelegation" - QueryDelegatorValidators = "delegatorValidators" - QueryDelegatorValidator = "delegatorValidator" - QueryPool = "pool" - QueryParameters = "parameters" -) - // creates a querier for staking REST endpoints -func NewQuerier(k keep.Keeper) sdk.Querier { +func NewQuerier(k Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) (res []byte, err sdk.Error) { switch path[0] { - case QueryValidators: + case types.QueryValidators: return queryValidators(ctx, req, k) - case QueryValidator: + case types.QueryValidator: return queryValidator(ctx, req, k) - case QueryValidatorDelegations: + case types.QueryValidatorDelegations: return queryValidatorDelegations(ctx, req, k) - case QueryValidatorUnbondingDelegations: + case types.QueryValidatorUnbondingDelegations: return queryValidatorUnbondingDelegations(ctx, req, k) - case QueryDelegation: + case types.QueryDelegation: return queryDelegation(ctx, req, k) - case QueryUnbondingDelegation: + case types.QueryUnbondingDelegation: return queryUnbondingDelegation(ctx, req, k) - case QueryDelegatorDelegations: + case types.QueryDelegatorDelegations: return queryDelegatorDelegations(ctx, req, k) - case QueryDelegatorUnbondingDelegations: + case types.QueryDelegatorUnbondingDelegations: return queryDelegatorUnbondingDelegations(ctx, req, k) - case QueryRedelegations: + case types.QueryRedelegations: return queryRedelegations(ctx, req, k) - case QueryDelegatorValidators: + case types.QueryDelegatorValidators: return queryDelegatorValidators(ctx, req, k) - case QueryDelegatorValidator: + case types.QueryDelegatorValidator: return queryDelegatorValidator(ctx, req, k) - case QueryPool: + case types.QueryPool: return queryPool(ctx, k) - case QueryParameters: + case types.QueryParameters: return queryParameters(ctx, k) default: return nil, sdk.ErrUnknownRequest("unknown staking query endpoint") @@ -66,70 +47,8 @@ func NewQuerier(k keep.Keeper) sdk.Querier { } } -// defines the params for the following queries: -// - 'custom/staking/delegatorDelegations' -// - 'custom/staking/delegatorUnbondingDelegations' -// - 'custom/staking/delegatorRedelegations' -// - 'custom/staking/delegatorValidators' -type QueryDelegatorParams struct { - DelegatorAddr sdk.AccAddress -} - -func NewQueryDelegatorParams(delegatorAddr sdk.AccAddress) QueryDelegatorParams { - return QueryDelegatorParams{ - DelegatorAddr: delegatorAddr, - } -} - -// defines the params for the following queries: -// - 'custom/staking/validator' -// - 'custom/staking/validatorDelegations' -// - 'custom/staking/validatorUnbondingDelegations' -// - 'custom/staking/validatorRedelegations' -type QueryValidatorParams struct { - ValidatorAddr sdk.ValAddress -} - -func NewQueryValidatorParams(validatorAddr sdk.ValAddress) QueryValidatorParams { - return QueryValidatorParams{ - ValidatorAddr: validatorAddr, - } -} - -// defines the params for the following queries: -// - 'custom/staking/delegation' -// - 'custom/staking/unbondingDelegation' -// - 'custom/staking/delegatorValidator' -type QueryBondsParams struct { - DelegatorAddr sdk.AccAddress - ValidatorAddr sdk.ValAddress -} - -func NewQueryBondsParams(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) QueryBondsParams { - return QueryBondsParams{ - DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, - } -} - -// defines the params for the following queries: -// - 'custom/staking/redelegation' -type QueryRedelegationParams struct { - DelegatorAddr sdk.AccAddress - SrcValidatorAddr sdk.ValAddress - DstValidatorAddr sdk.ValAddress -} - -func NewQueryRedelegationParams(delegatorAddr sdk.AccAddress, srcValidatorAddr sdk.ValAddress, dstValidatorAddr sdk.ValAddress) QueryRedelegationParams { - return QueryRedelegationParams{ - DelegatorAddr: delegatorAddr, - SrcValidatorAddr: srcValidatorAddr, - DstValidatorAddr: dstValidatorAddr, - } -} - -func queryValidators(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]byte, sdk.Error) { - var params QueryValidatorsParams +func queryValidators(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { + var params types.QueryValidatorsParams err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -172,8 +91,8 @@ func queryValidators(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]b return res, nil } -func queryValidator(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { - var params QueryValidatorParams +func queryValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper) (res []byte, err sdk.Error) { + var params types.QueryValidatorParams errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { @@ -192,8 +111,8 @@ func queryValidator(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res return res, nil } -func queryValidatorDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { - var params QueryValidatorParams +func queryValidatorDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper) (res []byte, err sdk.Error) { + var params types.QueryValidatorParams errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { @@ -214,8 +133,8 @@ func queryValidatorDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Ke return res, nil } -func queryValidatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { - var params QueryValidatorParams +func queryValidatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper) (res []byte, err sdk.Error) { + var params types.QueryValidatorParams errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { @@ -231,8 +150,8 @@ func queryValidatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, return res, nil } -func queryDelegatorDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { - var params QueryDelegatorParams +func queryDelegatorDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper) (res []byte, err sdk.Error) { + var params types.QueryDelegatorParams errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { @@ -253,8 +172,8 @@ func queryDelegatorDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Ke return res, nil } -func queryDelegatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { - var params QueryDelegatorParams +func queryDelegatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper) (res []byte, err sdk.Error) { + var params types.QueryDelegatorParams errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { @@ -270,8 +189,8 @@ func queryDelegatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, return res, nil } -func queryDelegatorValidators(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { - var params QueryDelegatorParams +func queryDelegatorValidators(ctx sdk.Context, req abci.RequestQuery, k Keeper) (res []byte, err sdk.Error) { + var params types.QueryDelegatorParams stakingParams := k.GetParams(ctx) @@ -289,8 +208,8 @@ func queryDelegatorValidators(ctx sdk.Context, req abci.RequestQuery, k keep.Kee return res, nil } -func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { - var params QueryBondsParams +func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper) (res []byte, err sdk.Error) { + var params types.QueryBondsParams errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { @@ -309,8 +228,8 @@ func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k keep.Keep return res, nil } -func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { - var params QueryBondsParams +func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper) (res []byte, err sdk.Error) { + var params types.QueryBondsParams errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { @@ -335,8 +254,8 @@ func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res return res, nil } -func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { - var params QueryBondsParams +func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper) (res []byte, err sdk.Error) { + var params types.QueryBondsParams errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { @@ -355,8 +274,8 @@ func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k keep.Kee return res, nil } -func queryRedelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { - var params QueryRedelegationParams +func queryRedelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper) (res []byte, err sdk.Error) { + var params types.QueryRedelegationParams errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { @@ -391,7 +310,7 @@ func queryRedelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ( return res, nil } -func queryPool(ctx sdk.Context, k keep.Keeper) (res []byte, err sdk.Error) { +func queryPool(ctx sdk.Context, k Keeper) (res []byte, err sdk.Error) { pool := k.GetPool(ctx) res, errRes := codec.MarshalJSONIndent(types.ModuleCdc, pool) @@ -401,7 +320,7 @@ func queryPool(ctx sdk.Context, k keep.Keeper) (res []byte, err sdk.Error) { return res, nil } -func queryParameters(ctx sdk.Context, k keep.Keeper) (res []byte, err sdk.Error) { +func queryParameters(ctx sdk.Context, k Keeper) (res []byte, err sdk.Error) { params := k.GetParams(ctx) res, errRes := codec.MarshalJSONIndent(types.ModuleCdc, params) @@ -411,13 +330,69 @@ func queryParameters(ctx sdk.Context, k keep.Keeper) (res []byte, err sdk.Error) return res, nil } -// QueryValidatorsParams defines the params for the following queries: -// - 'custom/staking/validators' -type QueryValidatorsParams struct { - Page, Limit int - Status string +//______________________________________________________ +// util + +func delegationToDelegationResponse(ctx sdk.Context, k Keeper, del types.Delegation) (types.DelegationResponse, sdk.Error) { + val, found := k.GetValidator(ctx, del.ValidatorAddress) + if !found { + return types.DelegationResponse{}, types.ErrNoValidatorFound(types.DefaultCodespace) + } + + return types.NewDelegationResp( + del.DelegatorAddress, + del.ValidatorAddress, + del.Shares, + val.TokensFromShares(del.Shares).TruncateInt(), + ), nil +} + +func delegationsToDelegationResponses( + ctx sdk.Context, k Keeper, delegations types.Delegations, +) (types.DelegationResponses, sdk.Error) { + + resp := make(types.DelegationResponses, len(delegations), 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 NewQueryValidatorsParams(page, limit int, status string) QueryValidatorsParams { - return QueryValidatorsParams{page, limit, status} +func redelegationsToRedelegationResponses( + ctx sdk.Context, k Keeper, redels types.Redelegations, +) (types.RedelegationResponses, sdk.Error) { + + resp := make(types.RedelegationResponses, len(redels), len(redels)) + for i, redel := range redels { + val, found := k.GetValidator(ctx, redel.ValidatorDstAddress) + if !found { + return nil, types.ErrNoValidatorFound(types.DefaultCodespace) + } + + entryResponses := make([]types.RedelegationEntryResponse, len(redel.Entries), 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( + redel.DelegatorAddress, + redel.ValidatorSrcAddress, + redel.ValidatorDstAddress, + entryResponses, + ) + } + + return resp, nil } diff --git a/x/staking/querier/querier_test.go b/x/staking/keeper/querier_test.go similarity index 68% rename from x/staking/querier/querier_test.go rename to x/staking/keeper/querier_test.go index 515cfcab326b..debf187a24ab 100644 --- a/x/staking/querier/querier_test.go +++ b/x/staking/keeper/querier_test.go @@ -1,4 +1,4 @@ -package querier +package keeper import ( "fmt" @@ -9,37 +9,36 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - keep "github.com/cosmos/cosmos-sdk/x/staking/keeper" "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( - addrAcc1, addrAcc2 = keep.Addrs[0], keep.Addrs[1] - addrVal1, addrVal2 = sdk.ValAddress(keep.Addrs[0]), sdk.ValAddress(keep.Addrs[1]) - pk1, pk2 = keep.PKs[0], keep.PKs[1] + addrAcc1, addrAcc2 = Addrs[0], Addrs[1] + addrVal1, addrVal2 = sdk.ValAddress(Addrs[0]), sdk.ValAddress(Addrs[1]) + pk1, pk2 = PKs[0], PKs[1] ) func TestNewQuerier(t *testing.T) { cdc := codec.New() - ctx, _, keeper := keep.CreateTestInput(t, false, 1000) - pool := keeper.GetPool(ctx) + ctx, _, r := CreateTestInput(t, false, 1000) + pool := r.GetPool(ctx) // Create Validators amts := []sdk.Int{sdk.NewInt(9), sdk.NewInt(8)} var validators [2]types.Validator for i, amt := range amts { - validators[i] = types.NewValidator(sdk.ValAddress(keep.Addrs[i]), keep.PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) - keeper.SetValidator(ctx, validators[i]) - keeper.SetValidatorByPowerIndex(ctx, validators[i]) + r.SetValidator(ctx, validators[i]) + r.SetValidatorByPowerIndex(ctx, validators[i]) } - keeper.SetPool(ctx, pool) + r.SetPool(ctx, pool) query := abci.RequestQuery{ Path: "", Data: []byte{}, } - querier := NewQuerier(keeper) + querier := NewQuerier(r) bz, err := querier(ctx, []string{"other"}, query) require.NotNil(t, err) @@ -51,7 +50,7 @@ func TestNewQuerier(t *testing.T) { _, err = querier(ctx, []string{"parameters"}, query) require.Nil(t, err) - queryValParams := NewQueryValidatorParams(addrVal1) + queryValParams := types.NewQueryValidatorParams(addrVal1) bz, errRes := cdc.MarshalJSON(queryValParams) require.Nil(t, errRes) @@ -67,7 +66,7 @@ func TestNewQuerier(t *testing.T) { _, err = querier(ctx, []string{"validatorUnbondingDelegations"}, query) require.Nil(t, err) - queryDelParams := NewQueryDelegatorParams(addrAcc2) + queryDelParams := types.NewQueryDelegatorParams(addrAcc2) bz, errRes = cdc.MarshalJSON(queryDelParams) require.Nil(t, errRes) @@ -83,7 +82,7 @@ func TestNewQuerier(t *testing.T) { _, err = querier(ctx, []string{"delegatorValidators"}, query) require.Nil(t, err) - bz, errRes = cdc.MarshalJSON(NewQueryRedelegationParams(nil, nil, nil)) + bz, errRes = cdc.MarshalJSON(types.NewQueryRedelegationParams(nil, nil, nil)) require.Nil(t, errRes) query.Data = bz @@ -93,60 +92,60 @@ func TestNewQuerier(t *testing.T) { func TestQueryParametersPool(t *testing.T) { cdc := codec.New() - ctx, _, keeper := keep.CreateTestInput(t, false, 1000) + ctx, _, r := CreateTestInput(t, false, 1000) - res, err := queryParameters(ctx, keeper) + res, err := queryParameters(ctx, r) require.Nil(t, err) var params types.Params errRes := cdc.UnmarshalJSON(res, ¶ms) require.Nil(t, errRes) - require.Equal(t, keeper.GetParams(ctx), params) + require.Equal(t, r.GetParams(ctx), params) - res, err = queryPool(ctx, keeper) + res, err = queryPool(ctx, r) require.Nil(t, err) var pool types.Pool errRes = cdc.UnmarshalJSON(res, &pool) require.Nil(t, errRes) - require.Equal(t, keeper.GetPool(ctx), pool) + require.Equal(t, r.GetPool(ctx), pool) } func TestQueryValidators(t *testing.T) { cdc := codec.New() - ctx, _, keeper := keep.CreateTestInput(t, false, 10000) - pool := keeper.GetPool(ctx) - params := keeper.GetParams(ctx) + ctx, _, r := CreateTestInput(t, false, 10000) + pool := r.GetPool(ctx) + params := r.GetParams(ctx) // Create Validators amts := []sdk.Int{sdk.NewInt(9), sdk.NewInt(8), sdk.NewInt(7)} status := []sdk.BondStatus{sdk.Bonded, sdk.Unbonded, sdk.Unbonding} var validators [3]types.Validator for i, amt := range amts { - validators[i] = types.NewValidator(sdk.ValAddress(keep.Addrs[i]), keep.PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) validators[i], pool = validators[i].UpdateStatus(pool, status[i]) } - keeper.SetPool(ctx, pool) - keeper.SetValidator(ctx, validators[0]) - keeper.SetValidator(ctx, validators[1]) - keeper.SetValidator(ctx, validators[2]) + r.SetPool(ctx, pool) + r.SetValidator(ctx, validators[0]) + r.SetValidator(ctx, validators[1]) + r.SetValidator(ctx, validators[2]) // Query Validators - queriedValidators := keeper.GetValidators(ctx, params.MaxValidators) + queriedValidators := r.GetValidators(ctx, params.MaxValidators) for i, s := range status { - queryValsParams := NewQueryValidatorsParams(1, int(params.MaxValidators), s.String()) + queryValsParams := types.NewQueryValidatorsParams(1, int(params.MaxValidators), s.String()) bz, err := cdc.MarshalJSON(queryValsParams) require.Nil(t, err) req := abci.RequestQuery{ - Path: fmt.Sprintf("/custom/%s/%s", types.QuerierRoute, QueryValidators), + Path: fmt.Sprintf("/custom/%s/%s", types.QuerierRoute, types.QueryValidators), Data: bz, } - res, err := queryValidators(ctx, req, keeper) + res, err := queryValidators(ctx, req, r) require.Nil(t, err) var validatorsResp []types.Validator @@ -159,7 +158,7 @@ func TestQueryValidators(t *testing.T) { } // Query each validator - queryParams := NewQueryValidatorParams(addrVal1) + queryParams := types.NewQueryValidatorParams(addrVal1) bz, err := cdc.MarshalJSON(queryParams) require.Nil(t, err) @@ -167,7 +166,7 @@ func TestQueryValidators(t *testing.T) { Path: "/custom/staking/validator", Data: bz, } - res, err := queryValidator(ctx, query, keeper) + res, err := queryValidator(ctx, query, r) require.Nil(t, err) var validator types.Validator @@ -179,26 +178,26 @@ func TestQueryValidators(t *testing.T) { func TestQueryDelegation(t *testing.T) { cdc := codec.New() - ctx, _, keeper := keep.CreateTestInput(t, false, 10000) - params := keeper.GetParams(ctx) + ctx, _, r := CreateTestInput(t, false, 10000) + params := r.GetParams(ctx) // Create Validators and Delegation val1 := types.NewValidator(addrVal1, pk1, types.Description{}) - keeper.SetValidator(ctx, val1) - keeper.SetValidatorByPowerIndex(ctx, val1) + r.SetValidator(ctx, val1) + r.SetValidatorByPowerIndex(ctx, val1) val2 := types.NewValidator(addrVal2, pk2, types.Description{}) - keeper.SetValidator(ctx, val2) - keeper.SetValidatorByPowerIndex(ctx, val2) + r.SetValidator(ctx, val2) + r.SetValidatorByPowerIndex(ctx, val2) delTokens := sdk.TokensFromTendermintPower(20) - keeper.Delegate(ctx, addrAcc2, delTokens, val1, true) + r.Delegate(ctx, addrAcc2, delTokens, val1, true) // apply TM updates - keeper.ApplyAndReturnValidatorSetUpdates(ctx) + r.ApplyAndReturnValidatorSetUpdates(ctx) // Query Delegator bonded validators - queryParams := NewQueryDelegatorParams(addrAcc2) + queryParams := types.NewQueryDelegatorParams(addrAcc2) bz, errRes := cdc.MarshalJSON(queryParams) require.Nil(t, errRes) @@ -207,9 +206,9 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - delValidators := keeper.GetDelegatorValidators(ctx, addrAcc2, params.MaxValidators) + delValidators := r.GetDelegatorValidators(ctx, addrAcc2, params.MaxValidators) - res, err := queryDelegatorValidators(ctx, query, keeper) + res, err := queryDelegatorValidators(ctx, query, r) require.Nil(t, err) var validatorsResp []types.Validator @@ -222,11 +221,11 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryDelegatorValidators(ctx, query, keeper) + _, err = queryDelegatorValidators(ctx, query, r) require.NotNil(t, err) // Query bonded validator - queryBondParams := NewQueryBondsParams(addrAcc2, addrVal1) + queryBondParams := types.NewQueryBondsParams(addrAcc2, addrVal1) bz, errRes = cdc.MarshalJSON(queryBondParams) require.Nil(t, errRes) @@ -235,7 +234,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryDelegatorValidator(ctx, query, keeper) + res, err = queryDelegatorValidator(ctx, query, r) require.Nil(t, err) var validator types.Validator @@ -247,7 +246,7 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryDelegatorValidator(ctx, query, keeper) + _, err = queryDelegatorValidator(ctx, query, r) require.NotNil(t, err) // Query delegation @@ -257,10 +256,10 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - delegation, found := keeper.GetDelegation(ctx, addrAcc2, addrVal1) + delegation, found := r.GetDelegation(ctx, addrAcc2, addrVal1) require.True(t, found) - res, err = queryDelegation(ctx, query, keeper) + res, err = queryDelegation(ctx, query, r) require.Nil(t, err) var delegationRes types.DelegationResponse @@ -277,7 +276,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryDelegatorDelegations(ctx, query, keeper) + res, err = queryDelegatorDelegations(ctx, query, r) require.Nil(t, err) var delegatorDelegations types.DelegationResponses @@ -291,12 +290,12 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryDelegation(ctx, query, keeper) + _, err = queryDelegation(ctx, query, r) require.NotNil(t, err) // Query validator delegations - bz, errRes = cdc.MarshalJSON(NewQueryValidatorParams(addrVal1)) + bz, errRes = cdc.MarshalJSON(types.NewQueryValidatorParams(addrVal1)) require.Nil(t, errRes) query = abci.RequestQuery{ @@ -304,7 +303,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryValidatorDelegations(ctx, query, keeper) + res, err = queryValidatorDelegations(ctx, query, r) require.Nil(t, err) var delegationsRes types.DelegationResponses @@ -317,10 +316,10 @@ func TestQueryDelegation(t *testing.T) { // Query unbonging delegation unbondingTokens := sdk.TokensFromTendermintPower(10) - _, err = keeper.Undelegate(ctx, addrAcc2, val1.OperatorAddress, unbondingTokens.ToDec()) + _, err = r.Undelegate(ctx, addrAcc2, val1.OperatorAddress, unbondingTokens.ToDec()) require.Nil(t, err) - queryBondParams = NewQueryBondsParams(addrAcc2, addrVal1) + queryBondParams = types.NewQueryBondsParams(addrAcc2, addrVal1) bz, errRes = cdc.MarshalJSON(queryBondParams) require.Nil(t, errRes) @@ -329,10 +328,10 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - unbond, found := keeper.GetUnbondingDelegation(ctx, addrAcc2, addrVal1) + unbond, found := r.GetUnbondingDelegation(ctx, addrAcc2, addrVal1) require.True(t, found) - res, err = queryUnbondingDelegation(ctx, query, keeper) + res, err = queryUnbondingDelegation(ctx, query, r) require.Nil(t, err) var unbondRes types.UnbondingDelegation @@ -344,7 +343,7 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryUnbondingDelegation(ctx, query, keeper) + _, err = queryUnbondingDelegation(ctx, query, r) require.NotNil(t, err) // Query Delegator Delegations @@ -354,7 +353,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryDelegatorUnbondingDelegations(ctx, query, keeper) + res, err = queryDelegatorUnbondingDelegations(ctx, query, r) require.Nil(t, err) var delegatorUbds []types.UnbondingDelegation @@ -365,18 +364,18 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryDelegatorUnbondingDelegations(ctx, query, keeper) + _, err = queryDelegatorUnbondingDelegations(ctx, query, r) require.NotNil(t, err) // Query redelegation redelegationTokens := sdk.TokensFromTendermintPower(10) - _, err = keeper.BeginRedelegation(ctx, addrAcc2, val1.OperatorAddress, + _, err = r.BeginRedelegation(ctx, addrAcc2, val1.OperatorAddress, val2.OperatorAddress, redelegationTokens.ToDec()) require.Nil(t, err) - redel, found := keeper.GetRedelegation(ctx, addrAcc2, val1.OperatorAddress, val2.OperatorAddress) + redel, found := r.GetRedelegation(ctx, addrAcc2, val1.OperatorAddress, val2.OperatorAddress) require.True(t, found) - bz, errRes = cdc.MarshalJSON(NewQueryRedelegationParams(addrAcc2, val1.OperatorAddress, val2.OperatorAddress)) + bz, errRes = cdc.MarshalJSON(types.NewQueryRedelegationParams(addrAcc2, val1.OperatorAddress, val2.OperatorAddress)) require.Nil(t, errRes) query = abci.RequestQuery{ @@ -384,7 +383,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryRedelegations(ctx, query, keeper) + res, err = queryRedelegations(ctx, query, r) require.Nil(t, err) var redelRes types.RedelegationResponses @@ -399,27 +398,27 @@ func TestQueryDelegation(t *testing.T) { func TestQueryRedelegations(t *testing.T) { cdc := codec.New() - ctx, _, keeper := keep.CreateTestInput(t, false, 10000) + ctx, _, r := CreateTestInput(t, false, 10000) // Create Validators and Delegation val1 := types.NewValidator(addrVal1, pk1, types.Description{}) val2 := types.NewValidator(addrVal2, pk2, types.Description{}) - keeper.SetValidator(ctx, val1) - keeper.SetValidator(ctx, val2) + r.SetValidator(ctx, val1) + r.SetValidator(ctx, val2) delAmount := sdk.TokensFromTendermintPower(100) - keeper.Delegate(ctx, addrAcc2, delAmount, val1, true) - _ = keeper.ApplyAndReturnValidatorSetUpdates(ctx) + r.Delegate(ctx, addrAcc2, delAmount, val1, true) + _ = r.ApplyAndReturnValidatorSetUpdates(ctx) rdAmount := sdk.TokensFromTendermintPower(20) - keeper.BeginRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator(), rdAmount.ToDec()) - keeper.ApplyAndReturnValidatorSetUpdates(ctx) + r.BeginRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator(), rdAmount.ToDec()) + r.ApplyAndReturnValidatorSetUpdates(ctx) - redel, found := keeper.GetRedelegation(ctx, addrAcc2, val1.OperatorAddress, val2.OperatorAddress) + redel, found := r.GetRedelegation(ctx, addrAcc2, val1.OperatorAddress, val2.OperatorAddress) require.True(t, found) // delegator redelegations - queryDelegatorParams := NewQueryDelegatorParams(addrAcc2) + queryDelegatorParams := types.NewQueryDelegatorParams(addrAcc2) bz, errRes := cdc.MarshalJSON(queryDelegatorParams) require.Nil(t, errRes) @@ -428,7 +427,7 @@ func TestQueryRedelegations(t *testing.T) { Data: bz, } - res, err := queryRedelegations(ctx, query, keeper) + res, err := queryRedelegations(ctx, query, r) require.Nil(t, err) var redelRes types.RedelegationResponses @@ -441,7 +440,7 @@ func TestQueryRedelegations(t *testing.T) { require.Len(t, redel.Entries, len(redelRes[0].Entries)) // validator redelegations - queryValidatorParams := NewQueryValidatorParams(val1.GetOperator()) + queryValidatorParams := types.NewQueryValidatorParams(val1.GetOperator()) bz, errRes = cdc.MarshalJSON(queryValidatorParams) require.Nil(t, errRes) @@ -450,7 +449,7 @@ func TestQueryRedelegations(t *testing.T) { Data: bz, } - res, err = queryRedelegations(ctx, query, keeper) + res, err = queryRedelegations(ctx, query, r) require.Nil(t, err) errRes = cdc.UnmarshalJSON(res, &redelRes) diff --git a/x/staking/querier/utils.go b/x/staking/querier/utils.go deleted file mode 100644 index 391464af5c92..000000000000 --- a/x/staking/querier/utils.go +++ /dev/null @@ -1,71 +0,0 @@ -package querier - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking/keeper" - "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -func delegationToDelegationResponse(ctx sdk.Context, k keeper.Keeper, del types.Delegation) (types.DelegationResponse, sdk.Error) { - val, found := k.GetValidator(ctx, del.ValidatorAddress) - if !found { - return types.DelegationResponse{}, types.ErrNoValidatorFound(types.DefaultCodespace) - } - - return types.NewDelegationResp( - del.DelegatorAddress, - del.ValidatorAddress, - del.Shares, - val.TokensFromShares(del.Shares).TruncateInt(), - ), nil -} - -func delegationsToDelegationResponses( - ctx sdk.Context, k keeper.Keeper, delegations types.Delegations, -) (types.DelegationResponses, sdk.Error) { - - resp := make(types.DelegationResponses, len(delegations), 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.Keeper, redels types.Redelegations, -) (types.RedelegationResponses, sdk.Error) { - - resp := make(types.RedelegationResponses, len(redels), len(redels)) - for i, redel := range redels { - val, found := k.GetValidator(ctx, redel.ValidatorDstAddress) - if !found { - return nil, types.ErrNoValidatorFound(types.DefaultCodespace) - } - - entryResponses := make([]types.RedelegationEntryResponse, len(redel.Entries), 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( - redel.DelegatorAddress, - redel.ValidatorSrcAddress, - redel.ValidatorDstAddress, - entryResponses, - ) - } - - return resp, nil -} diff --git a/x/staking/types/expected_keepers.go b/x/staking/types/expected_keepers.go index e3a799f9d3d7..656e94484599 100644 --- a/x/staking/types/expected_keepers.go +++ b/x/staking/types/expected_keepers.go @@ -2,7 +2,7 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) // expected coin keeper @@ -24,5 +24,5 @@ type BankKeeper interface { // expected bank keeper type AccountKeeper interface { - IterateAccounts(ctx sdk.Context, process func(types.Account) (stop bool)) + IterateAccounts(ctx sdk.Context, process func(authtypes.Account) (stop bool)) } diff --git a/x/staking/types/querier.go b/x/staking/types/querier.go new file mode 100644 index 000000000000..ba38a55742f5 --- /dev/null +++ b/x/staking/types/querier.go @@ -0,0 +1,98 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// query endpoints supported by the staking Querier +const ( + QueryValidators = "validators" + QueryValidator = "validator" + QueryDelegatorDelegations = "delegatorDelegations" + QueryDelegatorUnbondingDelegations = "delegatorUnbondingDelegations" + QueryRedelegations = "redelegations" + QueryValidatorDelegations = "validatorDelegations" + QueryValidatorRedelegations = "validatorRedelegations" + QueryValidatorUnbondingDelegations = "validatorUnbondingDelegations" + QueryDelegation = "delegation" + QueryUnbondingDelegation = "unbondingDelegation" + QueryDelegatorValidators = "delegatorValidators" + QueryDelegatorValidator = "delegatorValidator" + QueryPool = "pool" + QueryParameters = "parameters" +) + +// defines the params for the following queries: +// - 'custom/staking/delegatorDelegations' +// - 'custom/staking/delegatorUnbondingDelegations' +// - 'custom/staking/delegatorRedelegations' +// - 'custom/staking/delegatorValidators' +type QueryDelegatorParams struct { + DelegatorAddr sdk.AccAddress +} + +func NewQueryDelegatorParams(delegatorAddr sdk.AccAddress) QueryDelegatorParams { + return QueryDelegatorParams{ + DelegatorAddr: delegatorAddr, + } +} + +// defines the params for the following queries: +// - 'custom/staking/validator' +// - 'custom/staking/validatorDelegations' +// - 'custom/staking/validatorUnbondingDelegations' +// - 'custom/staking/validatorRedelegations' +type QueryValidatorParams struct { + ValidatorAddr sdk.ValAddress +} + +func NewQueryValidatorParams(validatorAddr sdk.ValAddress) QueryValidatorParams { + return QueryValidatorParams{ + ValidatorAddr: validatorAddr, + } +} + +// defines the params for the following queries: +// - 'custom/staking/delegation' +// - 'custom/staking/unbondingDelegation' +// - 'custom/staking/delegatorValidator' +type QueryBondsParams struct { + DelegatorAddr sdk.AccAddress + ValidatorAddr sdk.ValAddress +} + +func NewQueryBondsParams(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) QueryBondsParams { + return QueryBondsParams{ + DelegatorAddr: delegatorAddr, + ValidatorAddr: validatorAddr, + } +} + +// defines the params for the following queries: +// - 'custom/staking/redelegation' +type QueryRedelegationParams struct { + DelegatorAddr sdk.AccAddress + SrcValidatorAddr sdk.ValAddress + DstValidatorAddr sdk.ValAddress +} + +func NewQueryRedelegationParams(delegatorAddr sdk.AccAddress, + srcValidatorAddr, dstValidatorAddr sdk.ValAddress) QueryRedelegationParams { + + return QueryRedelegationParams{ + DelegatorAddr: delegatorAddr, + SrcValidatorAddr: srcValidatorAddr, + DstValidatorAddr: dstValidatorAddr, + } +} + +// QueryValidatorsParams defines the params for the following queries: +// - 'custom/staking/validators' +type QueryValidatorsParams struct { + Page, Limit int + Status string +} + +func NewQueryValidatorsParams(page, limit int, status string) QueryValidatorsParams { + return QueryValidatorsParams{page, limit, status} +} From 8cc66cc134d6927957b3fe4e868e3a6b219b0d61 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Mon, 3 Jun 2019 17:12:45 -0400 Subject: [PATCH 15/23] @jackzampolin comments --- simapp/app.go | 6 +----- types/module/module.go | 8 +++++++- x/distribution/client/cli/query.go | 2 +- x/distribution/client/cli/tx.go | 2 +- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/simapp/app.go b/simapp/app.go index 1ef058b8e139..0b41b8f3a875 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -41,10 +41,6 @@ var ( // The module BasicManager is in charge of setting up basic, // non-dependant module elements, such as codec registration // and genesis verification. - ModuleBasics module.BasicManager -) - -func init() { ModuleBasics = module.NewBasicManager( genaccounts.AppModuleBasic{}, genutil.AppModuleBasic{}, @@ -58,7 +54,7 @@ func init() { crisis.AppModuleBasic{}, slashing.AppModuleBasic{}, ) -} +) // custom tx codec func MakeCodec() *codec.Codec { diff --git a/types/module/module.go b/types/module/module.go index d5cc27b36f1a..0f84158c6bc5 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -2,7 +2,8 @@ Package module contains application module patterns and associated "manager" functionality. The module pattern has been broken down by: - independent module functionality (AppModuleBasic) - - inter-dependent module functionality (AppModule) + - inter-dependent module genesis functionality (AppModuleGenesis) + - inter-dependent module full functionality (AppModule) inter-dependent module functionality is module functionality which somehow depends on other modules, typically through the module keeper. Many of the @@ -18,6 +19,11 @@ high level pattern for modules to follow - for instance, such that we don't have to manually register all of the codecs for all the modules. This basic procedure as well as other basic patterns are handled through the use of BasicManager. + +Lastly the interface for genesis functionality (AppModuleGenesis) has been +separated out from full module functionality (AppModule) so that modules which +are only used for genesis can take advantage of the Module patterns without +needlessly defining many placeholder functions */ package module diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index a46ebe0e77c4..ee7ce6dc19ec 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -20,7 +20,7 @@ import ( // GetQueryCmd returns the cli query commands for this module func GetQueryCmd(storeKey string, cdc *amino.Codec) *cobra.Command { distQueryCmd := &cobra.Command{ - Use: "distr", + Use: types.ModuleName, Short: "Querying commands for the distribution module", } diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index b1ba8a0d20c0..91aa71fe722c 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -36,7 +36,7 @@ const ( // GetTxCmd returns the transaction commands for this module func GetTxCmd(storeKey string, cdc *amino.Codec) *cobra.Command { distTxCmd := &cobra.Command{ - Use: "distr", + Use: types.ModuleName, Short: "Distribution transactions subcommands", } From e5d0b716606b3435d114e246312a9b49519e3a5a Mon Sep 17 00:00:00 2001 From: Alexander Bezobchuk Date: Tue, 4 Jun 2019 09:38:15 -0400 Subject: [PATCH 16/23] Update x/auth/keeper.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> --- x/auth/keeper.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/auth/keeper.go b/x/auth/keeper.go index 3afe3f7eef09..1ffc0fc80042 100644 --- a/x/auth/keeper.go +++ b/x/auth/keeper.go @@ -17,7 +17,7 @@ type AccountKeeper struct { // The (unexposed) key used to access the store from the Context. key sdk.StoreKey - // The prototypical types.Account constructor. + // The prototypical Account constructor. proto func() types.Account // The codec codec for binary encoding/decoding of accounts. From 3b82dc596cac246f0fe55e2d22a907660e318147 Mon Sep 17 00:00:00 2001 From: Alexander Bezobchuk Date: Tue, 4 Jun 2019 09:40:23 -0400 Subject: [PATCH 17/23] Update x/auth/keeper.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> --- x/auth/keeper.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/auth/keeper.go b/x/auth/keeper.go index 1ffc0fc80042..7d7741054e95 100644 --- a/x/auth/keeper.go +++ b/x/auth/keeper.go @@ -177,7 +177,7 @@ func (ak AccountKeeper) GetNextAccountNumber(ctx sdk.Context) uint64 { } // ----------------------------------------------------------------------------- -// types.Params +// Params // SetParams sets the auth module's parameters. func (ak AccountKeeper) SetParams(ctx sdk.Context, params types.Params) { From 0e650ae29b5095d0ca5486113699e26552f17ce5 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 4 Jun 2019 16:17:37 -0400 Subject: [PATCH 18/23] add auth and bank tx/query subcommands --- client/utils/utils.go | 20 ++++++++-------- client/utils/utils_test.go | 12 +++++----- types/module/module.go | 8 +++++-- x/auth/client/cli/{account.go => query.go} | 17 +++++++++++--- x/auth/client/cli/tx.go | 21 +++++++++++++++++ .../cli/{multisign.go => tx_multisign.go} | 23 ++++++++++--------- x/auth/client/cli/{sign.go => tx_sign.go} | 20 ++++++++-------- x/auth/client/txbuilder/txbuilder.go | 22 +++++++++--------- x/auth/client/txbuilder/txbuilder_test.go | 18 +++++++-------- x/auth/module.go | 9 ++++++-- x/bank/client/cli/{sendtx.go => tx.go} | 20 ++++++++++++---- x/bank/module.go | 5 +++- x/crisis/client/cli/tx.go | 2 +- 13 files changed, 127 insertions(+), 70 deletions(-) rename x/auth/client/cli/{account.go => query.go} (65%) create mode 100644 x/auth/client/cli/tx.go rename x/auth/client/cli/{multisign.go => tx_multisign.go} (86%) rename x/auth/client/cli/{sign.go => tx_sign.go} (93%) rename x/bank/client/cli/{sendtx.go => tx.go} (77%) diff --git a/client/utils/utils.go b/client/utils/utils.go index 6334a8a40e8e..a283dd8b5d2f 100644 --- a/client/utils/utils.go +++ b/client/utils/utils.go @@ -17,8 +17,8 @@ import ( "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) // GasEstimateResponse defines a response definition for tx gas estimation. @@ -165,10 +165,10 @@ func PrintUnsignedStdTx(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msg // Don't perform online validation or lookups if offline is true. func SignStdTx( txBldr authtxb.TxBuilder, cliCtx context.CLIContext, name string, - stdTx auth.StdTx, appendSig bool, offline bool, -) (auth.StdTx, error) { + stdTx authtypes.StdTx, appendSig bool, offline bool, +) (authtypes.StdTx, error) { - var signedStdTx auth.StdTx + var signedStdTx authtypes.StdTx info, err := txBldr.Keybase().Get(name) if err != nil { @@ -201,8 +201,8 @@ func SignStdTx( // Don't perform online validation or lookups if offline is true, else // populate account and sequence numbers from a foreign account. func SignStdTxWithSignerAddress(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, - addr sdk.AccAddress, name string, stdTx auth.StdTx, - offline bool) (signedStdTx auth.StdTx, err error) { + addr sdk.AccAddress, name string, stdTx authtypes.StdTx, + offline bool) (signedStdTx authtypes.StdTx, err error) { // check whether the address is a signer if !isTxSigner(addr, stdTx.GetSigners()) { @@ -225,7 +225,7 @@ func SignStdTxWithSignerAddress(txBldr authtxb.TxBuilder, cliCtx context.CLICont } // Read and decode a StdTx from the given filename. Can pass "-" to read from stdin. -func ReadStdTxFromFile(cdc *codec.Codec, filename string) (stdTx auth.StdTx, err error) { +func ReadStdTxFromFile(cdc *codec.Codec, filename string) (stdTx authtypes.StdTx, err error) { var bytes []byte if filename == "-" { bytes, err = ioutil.ReadAll(os.Stdin) @@ -263,7 +263,7 @@ func populateAccountFromState( func GetTxEncoder(cdc *codec.Codec) (encoder sdk.TxEncoder) { encoder = sdk.GetConfig().GetTxEncoder() if encoder == nil { - encoder = auth.DefaultTxEncoder(cdc) + encoder = authtypes.DefaultTxEncoder(cdc) } return } @@ -321,7 +321,7 @@ func PrepareTxBuilder(txBldr authtxb.TxBuilder, cliCtx context.CLIContext) (auth return txBldr, nil } -func buildUnsignedStdTxOffline(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (stdTx auth.StdTx, err error) { +func buildUnsignedStdTxOffline(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (stdTx authtypes.StdTx, err error) { if txBldr.SimulateAndExecute() { if cliCtx.GenerateOnly { return stdTx, errors.New("cannot estimate gas with generate-only") @@ -340,7 +340,7 @@ func buildUnsignedStdTxOffline(txBldr authtxb.TxBuilder, cliCtx context.CLIConte return stdTx, nil } - return auth.NewStdTx(stdSignMsg.Msgs, stdSignMsg.Fee, nil, stdSignMsg.Memo), nil + return authtypes.NewStdTx(stdSignMsg.Msgs, stdSignMsg.Fee, nil, stdSignMsg.Memo), nil } func isTxSigner(user sdk.AccAddress, signers []sdk.AccAddress) bool { diff --git a/client/utils/utils_test.go b/client/utils/utils_test.go index 4bccac1d2def..f69f0003d428 100644 --- a/client/utils/utils_test.go +++ b/client/utils/utils_test.go @@ -14,7 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( @@ -72,7 +72,7 @@ func TestCalculateGas(t *testing.T) { func TestDefaultTxEncoder(t *testing.T) { cdc := makeCodec() - defaultEncoder := auth.DefaultTxEncoder(cdc) + defaultEncoder := authtypes.DefaultTxEncoder(cdc) encoder := GetTxEncoder(cdc) compareEncoders(t, defaultEncoder, encoder) @@ -98,8 +98,8 @@ func TestReadStdTxFromFile(t *testing.T) { sdk.RegisterCodec(cdc) // Build a test transaction - fee := auth.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) - stdTx := auth.NewStdTx([]sdk.Msg{}, fee, []auth.StdSignature{}, "foomemo") + fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) + stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") // Write it to the file encodedTx, _ := cdc.MarshalJSON(stdTx) @@ -116,7 +116,7 @@ func TestReadStdTxFromFile(t *testing.T) { func compareEncoders(t *testing.T, expected sdk.TxEncoder, actual sdk.TxEncoder) { msgs := []sdk.Msg{sdk.NewTestMsg(addr)} - tx := auth.NewStdTx(msgs, auth.StdFee{}, []auth.StdSignature{}, "") + tx := authtypes.NewStdTx(msgs, authtypes.StdFee{}, []authtypes.StdSignature{}, "") defaultEncoderBytes, err := expected(tx) require.NoError(t, err) @@ -139,7 +139,7 @@ func makeCodec() *codec.Codec { var cdc = codec.New() sdk.RegisterCodec(cdc) codec.RegisterCrypto(cdc) - auth.RegisterCodec(cdc) + authtypes.RegisterCodec(cdc) cdc.RegisterConcrete(sdk.TestMsg{}, "cosmos-sdk/Test", nil) return cdc } diff --git a/types/module/module.go b/types/module/module.go index 0f84158c6bc5..80b9b64f95a4 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -57,10 +57,14 @@ type AppModuleBasic interface { } // collections of AppModuleBasic -type BasicManager []AppModuleBasic +type BasicManager map[string]AppModuleBasic func NewBasicManager(modules ...AppModuleBasic) BasicManager { - return modules + moduleMap := make(map[string]AppModuleBasic) + for _, module := range modules { + moduleMap[module.Name()] = module + } + return moduleMap } // RegisterCodecs registers all module codecs diff --git a/x/auth/client/cli/account.go b/x/auth/client/cli/query.go similarity index 65% rename from x/auth/client/cli/account.go rename to x/auth/client/cli/query.go index 4ce5556f0745..6c8b05676802 100644 --- a/x/auth/client/cli/account.go +++ b/x/auth/client/cli/query.go @@ -3,16 +3,27 @@ package cli import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) +// GetTxCmd returns the transaction commands for this module +func GetQueryCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Querying commands for the auth module", + } + cmd.AddCommand(GetAccountCmd(cdc)) + return cmd +} + // GetAccountCmd returns a query account that will display the state of the // account at a given address. // nolint: unparam -func GetAccountCmd(storeName string, cdc *codec.Codec) *cobra.Command { +func GetAccountCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "account [address]", Short: "Query account balance", @@ -38,5 +49,5 @@ func GetAccountCmd(storeName string, cdc *codec.Codec) *cobra.Command { return cliCtx.PrintOutput(acc) }, } - return client.GetCommands(cmd)[0] + return flags.GetCommands(cmd)[0] } diff --git a/x/auth/client/cli/tx.go b/x/auth/client/cli/tx.go new file mode 100644 index 000000000000..cbd5372fb13e --- /dev/null +++ b/x/auth/client/cli/tx.go @@ -0,0 +1,21 @@ +package cli + +import ( + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +// GetTxCmd returns the transaction commands for this module +func GetTxCmd(cdc *codec.Codec) *cobra.Command { + txCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Auth transaction subcommands", + } + txCmd.AddCommand( + GetMultiSignCommand(cdc), + GetSignCommand(cdc), + ) + return txCmd +} diff --git a/x/auth/client/cli/multisign.go b/x/auth/client/cli/tx_multisign.go similarity index 86% rename from x/auth/client/cli/multisign.go rename to x/auth/client/cli/tx_multisign.go index b1aa98fd58c1..5535af047a58 100644 --- a/x/auth/client/cli/multisign.go +++ b/x/auth/client/cli/tx_multisign.go @@ -8,22 +8,23 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - amino "github.com/tendermint/go-amino" + "github.com/tendermint/tendermint/crypto/multisig" "github.com/tendermint/tendermint/libs/cli" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/utils" + "github.com/cosmos/cosmos-sdk/codec" crkeys "github.com/cosmos/cosmos-sdk/crypto/keys" "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/auth" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) // GetSignCommand returns the sign command -func GetMultiSignCommand(codec *amino.Codec) *cobra.Command { +func GetMultiSignCommand(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "multisign [file] [name] [[signature]...]", Short: "Generate multisig signatures for transactions generated offline", @@ -46,7 +47,7 @@ recommended to set such parameters manually. version.ClientName, ), ), - RunE: makeMultiSignCmd(codec), + RunE: makeMultiSignCmd(cdc), Args: cobra.MinimumNArgs(3), } @@ -55,10 +56,10 @@ recommended to set such parameters manually. cmd.Flags().String(flagOutfile, "", "The document will be written to the given file instead of STDOUT") // Add the flags here and return the command - return client.PostCommands(cmd)[0] + return flags.PostCommands(cmd)[0] } -func makeMultiSignCmd(cdc *amino.Codec) func(cmd *cobra.Command, args []string) error { +func makeMultiSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) (err error) { stdTx, err := utils.ReadStdTxFromFile(cdc, args[0]) if err != nil { @@ -106,7 +107,7 @@ func makeMultiSignCmd(cdc *amino.Codec) func(cmd *cobra.Command, args []string) } // Validate each signature - sigBytes := auth.StdSignBytes( + sigBytes := types.StdSignBytes( txBldr.ChainID(), txBldr.AccountNumber(), txBldr.Sequence(), stdTx.Fee, stdTx.GetMsgs(), stdTx.GetMemo(), ) @@ -118,8 +119,8 @@ func makeMultiSignCmd(cdc *amino.Codec) func(cmd *cobra.Command, args []string) } } - newStdSig := auth.StdSignature{Signature: cdc.MustMarshalBinaryBare(multisigSig), PubKey: multisigPub} - newTx := auth.NewStdTx(stdTx.GetMsgs(), stdTx.Fee, []auth.StdSignature{newStdSig}, stdTx.GetMemo()) + newStdSig := types.StdSignature{Signature: cdc.MustMarshalBinaryBare(multisigSig), PubKey: multisigPub} + newTx := types.NewStdTx(stdTx.GetMsgs(), stdTx.Fee, []types.StdSignature{newStdSig}, stdTx.GetMemo()) sigOnly := viper.GetBool(flagSigOnly) var json []byte @@ -156,7 +157,7 @@ func makeMultiSignCmd(cdc *amino.Codec) func(cmd *cobra.Command, args []string) } } -func readAndUnmarshalStdSignature(cdc *amino.Codec, filename string) (stdSig auth.StdSignature, err error) { +func readAndUnmarshalStdSignature(cdc *codec.Codec, filename string) (stdSig types.StdSignature, err error) { var bytes []byte if bytes, err = ioutil.ReadFile(filename); err != nil { return diff --git a/x/auth/client/cli/sign.go b/x/auth/client/cli/tx_sign.go similarity index 93% rename from x/auth/client/cli/sign.go rename to x/auth/client/cli/tx_sign.go index 6fbe51eaeb59..950fa4708b94 100644 --- a/x/auth/client/cli/sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -9,13 +9,13 @@ import ( "github.com/spf13/viper" "github.com/tendermint/tendermint/crypto/multisig" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) const ( @@ -77,8 +77,8 @@ be generated via the 'multisign' command. ) cmd.Flags().String(flagOutfile, "", "The document will be written to the given file instead of STDOUT") - cmd = client.PostCommands(cmd)[0] - cmd.MarkFlagRequired(client.FlagFrom) + cmd = flags.PostCommands(cmd)[0] + cmd.MarkFlagRequired(flags.FlagFrom) return cmd } @@ -87,8 +87,8 @@ func preSignCmd(cmd *cobra.Command, _ []string) { // Conditionally mark the account and sequence numbers required as no RPC // query will be done. if viper.GetBool(flagOffline) { - cmd.MarkFlagRequired(client.FlagAccountNumber) - cmd.MarkFlagRequired(client.FlagSequence) + cmd.MarkFlagRequired(flags.FlagAccountNumber) + cmd.MarkFlagRequired(flags.FlagSequence) } } @@ -112,7 +112,7 @@ func makeSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error } // if --signature-only is on, then override --append - var newTx auth.StdTx + var newTx types.StdTx generateSignatureOnly := viper.GetBool(flagSigOnly) multisigAddrStr := viper.GetString(flagMultisig) @@ -161,7 +161,7 @@ func makeSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error } } -func getSignatureJSON(cdc *codec.Codec, newTx auth.StdTx, indent, generateSignatureOnly bool) ([]byte, error) { +func getSignatureJSON(cdc *codec.Codec, newTx types.StdTx, indent, generateSignatureOnly bool) ([]byte, error) { switch generateSignatureOnly { case true: switch indent { @@ -186,7 +186,7 @@ func getSignatureJSON(cdc *codec.Codec, newTx auth.StdTx, indent, generateSignat // its expected signers. In addition, if offline has not been supplied, the // signature is verified over the transaction sign bytes. func printAndValidateSigs( - cliCtx context.CLIContext, chainID string, stdTx auth.StdTx, offline bool, + cliCtx context.CLIContext, chainID string, stdTx types.StdTx, offline bool, ) bool { fmt.Println("Signers:") @@ -229,7 +229,7 @@ func printAndValidateSigs( return false } - sigBytes := auth.StdSignBytes( + sigBytes := types.StdSignBytes( chainID, acc.GetAccountNumber(), acc.GetSequence(), stdTx.Fee, stdTx.GetMsgs(), stdTx.GetMemo(), ) diff --git a/x/auth/client/txbuilder/txbuilder.go b/x/auth/client/txbuilder/txbuilder.go index cc3a654392cb..8da587b12ac9 100644 --- a/x/auth/client/txbuilder/txbuilder.go +++ b/x/auth/client/txbuilder/txbuilder.go @@ -11,7 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/keys" crkeys "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) // TxBuilder implements a transaction context created in SDK modules. @@ -203,7 +203,7 @@ func (bldr TxBuilder) BuildSignMsg(msgs []sdk.Msg) (StdSignMsg, error) { Sequence: bldr.sequence, Memo: bldr.memo, Msgs: msgs, - Fee: auth.NewStdFee(bldr.gas, fees), + Fee: types.NewStdFee(bldr.gas, fees), }, nil } @@ -215,7 +215,7 @@ func (bldr TxBuilder) Sign(name, passphrase string, msg StdSignMsg) ([]byte, err return nil, err } - return bldr.txEncoder(auth.NewStdTx(msg.Msgs, msg.Fee, []auth.StdSignature{sig}, msg.Memo)) + return bldr.txEncoder(types.NewStdTx(msg.Msgs, msg.Fee, []types.StdSignature{sig}, msg.Memo)) } // BuildAndSign builds a single message to be signed, and signs a transaction @@ -238,15 +238,15 @@ func (bldr TxBuilder) BuildTxForSim(msgs []sdk.Msg) ([]byte, error) { } // the ante handler will populate with a sentinel pubkey - sigs := []auth.StdSignature{{}} - return bldr.txEncoder(auth.NewStdTx(signMsg.Msgs, signMsg.Fee, sigs, signMsg.Memo)) + sigs := []types.StdSignature{{}} + return bldr.txEncoder(types.NewStdTx(signMsg.Msgs, signMsg.Fee, sigs, signMsg.Memo)) } // SignStdTx appends a signature to a StdTx and returns a copy of it. If append // is false, it replaces the signatures already attached with the new signature. -func (bldr TxBuilder) SignStdTx(name, passphrase string, stdTx auth.StdTx, appendSig bool) (signedStdTx auth.StdTx, err error) { +func (bldr TxBuilder) SignStdTx(name, passphrase string, stdTx types.StdTx, appendSig bool) (signedStdTx types.StdTx, err error) { if bldr.chainID == "" { - return auth.StdTx{}, fmt.Errorf("chain ID required but not specified") + return types.StdTx{}, fmt.Errorf("chain ID required but not specified") } stdSignature, err := MakeSignature(bldr.keybase, name, passphrase, StdSignMsg{ @@ -263,17 +263,17 @@ func (bldr TxBuilder) SignStdTx(name, passphrase string, stdTx auth.StdTx, appen sigs := stdTx.GetSignatures() if len(sigs) == 0 || !appendSig { - sigs = []auth.StdSignature{stdSignature} + sigs = []types.StdSignature{stdSignature} } else { sigs = append(sigs, stdSignature) } - signedStdTx = auth.NewStdTx(stdTx.GetMsgs(), stdTx.Fee, sigs, stdTx.GetMemo()) + signedStdTx = types.NewStdTx(stdTx.GetMsgs(), stdTx.Fee, sigs, stdTx.GetMemo()) return } // MakeSignature builds a StdSignature given keybase, key name, passphrase, and a StdSignMsg. func MakeSignature(keybase crkeys.Keybase, name, passphrase string, - msg StdSignMsg) (sig auth.StdSignature, err error) { + msg StdSignMsg) (sig types.StdSignature, err error) { if keybase == nil { keybase, err = keys.NewKeyBaseFromHomeFlag() if err != nil { @@ -285,7 +285,7 @@ func MakeSignature(keybase crkeys.Keybase, name, passphrase string, if err != nil { return } - return auth.StdSignature{ + return types.StdSignature{ PubKey: pubkey, Signature: sigBytes, }, nil diff --git a/x/auth/client/txbuilder/txbuilder_test.go b/x/auth/client/txbuilder/txbuilder_test.go index 4ff4b0cec513..9b39c92bba47 100644 --- a/x/auth/client/txbuilder/txbuilder_test.go +++ b/x/auth/client/txbuilder/txbuilder_test.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( @@ -42,7 +42,7 @@ func TestTxBuilderBuild(t *testing.T) { { "builder with fees", fields{ - TxEncoder: auth.DefaultTxEncoder(codec.New()), + TxEncoder: types.DefaultTxEncoder(codec.New()), AccountNumber: 1, Sequence: 1, Gas: 200000, @@ -59,14 +59,14 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager 1!", Msgs: defaultMsg, - Fee: auth.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), + Fee: types.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), }, false, }, { "builder with gas prices", fields{ - TxEncoder: auth.DefaultTxEncoder(codec.New()), + TxEncoder: types.DefaultTxEncoder(codec.New()), AccountNumber: 1, Sequence: 1, Gas: 200000, @@ -83,14 +83,14 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager 2!", Msgs: defaultMsg, - Fee: auth.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), + Fee: types.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), }, false, }, { "no chain-id supplied", fields{ - TxEncoder: auth.DefaultTxEncoder(codec.New()), + TxEncoder: types.DefaultTxEncoder(codec.New()), AccountNumber: 1, Sequence: 1, Gas: 200000, @@ -107,14 +107,14 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager 1!", Msgs: defaultMsg, - Fee: auth.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), + Fee: types.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), }, true, }, { "builder w/ fees and gas prices", fields{ - TxEncoder: auth.DefaultTxEncoder(codec.New()), + TxEncoder: types.DefaultTxEncoder(codec.New()), AccountNumber: 1, Sequence: 1, Gas: 200000, @@ -132,7 +132,7 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager 1!", Msgs: defaultMsg, - Fee: auth.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), + Fee: types.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), }, true, }, diff --git a/x/auth/module.go b/x/auth/module.go index ca66d6e8e036..4e646dd659eb 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -11,6 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/auth/client/rest" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -54,10 +55,14 @@ func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router } // get the root tx command of this module -func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } +func (AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd(ModuleCdc) +} // get the root query command of this module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(ModuleCdc) +} //___________________________ // app module object diff --git a/x/bank/client/cli/sendtx.go b/x/bank/client/cli/tx.go similarity index 77% rename from x/bank/client/cli/sendtx.go rename to x/bank/client/cli/tx.go index 094b5edcd7d1..da9e04551e6b 100644 --- a/x/bank/client/cli/sendtx.go +++ b/x/bank/client/cli/tx.go @@ -1,15 +1,15 @@ package cli import ( + "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/bank" - - "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/x/bank/types" ) const ( @@ -17,6 +17,18 @@ const ( flagAmount = "amount" ) +// GetTxCmd returns the transaction commands for this module +func GetTxCmd(cdc *codec.Codec) *cobra.Command { + txCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Bank transaction subcommands", + } + txCmd.AddCommand( + SendTxCmd(cdc), + ) + return txCmd +} + // SendTxCmd will create a send tx and sign it with the given key. func SendTxCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ @@ -41,7 +53,7 @@ func SendTxCmd(cdc *codec.Codec) *cobra.Command { } // build and sign the transaction, then broadcast to Tendermint - msg := bank.NewMsgSend(cliCtx.GetFromAddress(), to, coins) + msg := types.NewMsgSend(cliCtx.GetFromAddress(), to, coins) return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) }, } diff --git a/x/bank/module.go b/x/bank/module.go index c50cb56a64e2..92fb87eba562 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -13,6 +13,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank/client/cli" "github.com/cosmos/cosmos-sdk/x/bank/client/rest" "github.com/cosmos/cosmos-sdk/x/bank/types" ) @@ -58,7 +59,9 @@ func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router } // get the root tx command of this module -func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } +func (AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd(ModuleCdc) +} // get the root query command of this module func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } diff --git a/x/crisis/client/cli/tx.go b/x/crisis/client/cli/tx.go index b7d013060a7a..6cc589a6be3f 100644 --- a/x/crisis/client/cli/tx.go +++ b/x/crisis/client/cli/tx.go @@ -37,7 +37,7 @@ func GetCmdInvariantBroken(cdc *codec.Codec) *cobra.Command { func GetTxCmd(cdc *codec.Codec) *cobra.Command { txCmd := &cobra.Command{ Use: types.ModuleName, - Short: "crisis transactions subcommands", + Short: "Crisis transactions subcommands", } txCmd.AddCommand(client.PostCommands( From bc64c7e0db73effe7e08aa6a37c3bdc2d054a7c5 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 4 Jun 2019 18:08:25 -0400 Subject: [PATCH 19/23] resolve cli issues, global cdc for commands --- client/context/context.go | 14 ++++++-------- client/tx/broadcast.go | 5 ++--- client/tx/encode.go | 5 ++--- tests/util.go | 8 ++++---- types/module/module.go | 12 ++++++------ x/auth/genaccounts/module.go | 4 ++-- x/auth/module.go | 8 ++++---- x/bank/module.go | 6 +++--- x/crisis/module.go | 8 +++----- x/distribution/client/cli/query.go | 3 +-- x/distribution/client/cli/tx.go | 13 ++++++------- x/distribution/client/proposal_handler.go | 2 +- x/distribution/module.go | 8 ++++---- x/genutil/module.go | 4 ++-- x/gov/client/proposal_handler.go | 7 +++++-- x/gov/module.go | 10 +++++----- x/mint/module.go | 8 +++----- x/params/client/cli/tx.go | 11 ++++++----- x/params/client/proposal_handler.go | 2 +- x/params/module.go | 4 ++-- x/slashing/module.go | 8 ++++---- x/staking/module.go | 8 ++++---- 22 files changed, 76 insertions(+), 82 deletions(-) diff --git a/client/context/context.go b/client/context/context.go index a44122d38256..83122fa47ee5 100644 --- a/client/context/context.go +++ b/client/context/context.go @@ -8,15 +8,8 @@ import ( "path/filepath" "github.com/pkg/errors" - - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/codec" - cryptokeys "github.com/cosmos/cosmos-sdk/crypto/keys" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/spf13/viper" - "gopkg.in/yaml.v2" + yaml "gopkg.in/yaml.v2" "github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/libs/log" @@ -24,7 +17,12 @@ import ( tmliteProxy "github.com/tendermint/tendermint/lite/proxy" rpcclient "github.com/tendermint/tendermint/rpc/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/codec" + cryptokeys "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( diff --git a/client/tx/broadcast.go b/client/tx/broadcast.go index 90d2ff792a04..d73c3ce8ebed 100644 --- a/client/tx/broadcast.go +++ b/client/tx/broadcast.go @@ -5,7 +5,6 @@ import ( "strings" "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth" @@ -62,7 +61,7 @@ func BroadcastTxRequest(cliCtx context.CLIContext, cdc *codec.Codec) http.Handle } // GetBroadcastCommand returns the tx broadcast command. -func GetBroadcastCommand(codec *amino.Codec) *cobra.Command { +func GetBroadcastCommand(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "broadcast [file_path]", Short: "Broadcast transactions generated offline", @@ -75,7 +74,7 @@ $ tx broadcast ./mytxn.json `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) (err error) { - cliCtx := context.NewCLIContext().WithCodec(codec) + cliCtx := context.NewCLIContext().WithCodec(cdc) stdTx, err := utils.ReadStdTxFromFile(cliCtx.Codec, args[0]) if err != nil { return diff --git a/client/tx/encode.go b/client/tx/encode.go index 36bb461a4ce6..7434f8547cbf 100644 --- a/client/tx/encode.go +++ b/client/tx/encode.go @@ -6,7 +6,6 @@ import ( "net/http" "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/flags" @@ -69,7 +68,7 @@ func (txr txEncodeRespStr) String() string { // GetEncodeCommand returns the encode command to take a JSONified transaction and turn it into // Amino-serialized bytes -func GetEncodeCommand(codec *amino.Codec) *cobra.Command { +func GetEncodeCommand(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "encode [file]", Short: "Encode transactions generated offline", @@ -78,7 +77,7 @@ Read a transaction from , serialize it to the Amino wire protocol, and out If you supply a dash (-) argument in place of an input filename, the command reads from standard input.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) (err error) { - cliCtx := context.NewCLIContext().WithCodec(codec) + cliCtx := context.NewCLIContext().WithCodec(cdc) stdTx, err := utils.ReadStdTxFromFile(cliCtx.Codec, args[0]) if err != nil { diff --git a/tests/util.go b/tests/util.go index d8ddd424e603..070073c2b3ed 100644 --- a/tests/util.go +++ b/tests/util.go @@ -5,17 +5,17 @@ import ( "io/ioutil" "net/http" "os" + "strings" "testing" "time" "github.com/stretchr/testify/require" - "strings" - - amino "github.com/tendermint/go-amino" tmclient "github.com/tendermint/tendermint/rpc/client" ctypes "github.com/tendermint/tendermint/rpc/core/types" rpcclient "github.com/tendermint/tendermint/rpc/lib/client" + + "github.com/cosmos/cosmos-sdk/codec" ) // Wait for the next tendermint block from the Tendermint RPC @@ -209,7 +209,7 @@ func NewTestCaseDir(t *testing.T) (string, func()) { return dir, func() { os.RemoveAll(dir) } } -var cdc = amino.NewCodec() +var cdc = codec.New() func init() { ctypes.RegisterAmino(cdc) diff --git a/types/module/module.go b/types/module/module.go index 80b9b64f95a4..b2e165d7dec2 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -52,8 +52,8 @@ type AppModuleBasic interface { // client functionality RegisterRESTRoutes(context.CLIContext, *mux.Router, *codec.Codec) - GetTxCmd() *cobra.Command - GetQueryCmd() *cobra.Command + GetTxCmd(*codec.Codec) *cobra.Command + GetQueryCmd(*codec.Codec) *cobra.Command } // collections of AppModuleBasic @@ -103,18 +103,18 @@ func (bm BasicManager) RegisterRESTRoutes( } // add all tx commands to the rootTxCmd -func (bm BasicManager) AddTxCommands(rootTxCmd *cobra.Command) { +func (bm BasicManager) AddTxCommands(rootTxCmd *cobra.Command, cdc *codec.Codec) { for _, b := range bm { - if cmd := b.GetTxCmd(); cmd != nil { + if cmd := b.GetTxCmd(cdc); cmd != nil { rootTxCmd.AddCommand(cmd) } } } // add all query commands to the rootQueryCmd -func (bm BasicManager) AddQueryCommands(rootQueryCmd *cobra.Command) { +func (bm BasicManager) AddQueryCommands(rootQueryCmd *cobra.Command, cdc *codec.Codec) { for _, b := range bm { - if cmd := b.GetQueryCmd(); cmd != nil { + if cmd := b.GetQueryCmd(cdc); cmd != nil { rootQueryCmd.AddCommand(cmd) } } diff --git a/x/auth/genaccounts/module.go b/x/auth/genaccounts/module.go index c1b92958e3cf..4513312a8d26 100644 --- a/x/auth/genaccounts/module.go +++ b/x/auth/genaccounts/module.go @@ -53,10 +53,10 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router, _ *codec.Codec) {} // get the root tx command of this module -func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } +func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } // get the root query command of this module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } +func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } // extra function from sdk.AppModuleBasic // iterate the genesis accounts and perform an operation at each of them diff --git a/x/auth/module.go b/x/auth/module.go index 4e646dd659eb..732d17375994 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -55,13 +55,13 @@ func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router } // get the root tx command of this module -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd(ModuleCdc) +func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetTxCmd(cdc) } // get the root query command of this module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(ModuleCdc) +func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetQueryCmd(cdc) } //___________________________ diff --git a/x/bank/module.go b/x/bank/module.go index 92fb87eba562..75f84f6f927c 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -59,12 +59,12 @@ func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router } // get the root tx command of this module -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd(ModuleCdc) +func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetTxCmd(cdc) } // get the root query command of this module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } +func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } //___________________________ // app module diff --git a/x/crisis/module.go b/x/crisis/module.go index 19e94554347f..6491a23b820b 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -52,14 +52,12 @@ func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router } // get the root tx command of this module -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd(ModuleCdc) +func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetTxCmd(cdc) } // get the root query command of this module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return nil -} +func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } //___________________________ // app module for bank diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index ee7ce6dc19ec..ce4558d7b9b6 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -6,7 +6,6 @@ import ( "strings" "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" @@ -18,7 +17,7 @@ import ( ) // GetQueryCmd returns the cli query commands for this module -func GetQueryCmd(storeKey string, cdc *amino.Codec) *cobra.Command { +func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { distQueryCmd := &cobra.Command{ Use: types.ModuleName, Short: "Querying commands for the distribution module", diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index 91aa71fe722c..5ab2aca74ae6 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -7,7 +7,6 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - amino "github.com/tendermint/go-amino" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" @@ -34,7 +33,7 @@ const ( ) // GetTxCmd returns the transaction commands for this module -func GetTxCmd(storeKey string, cdc *amino.Codec) *cobra.Command { +func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command { distTxCmd := &cobra.Command{ Use: types.ModuleName, Short: "Distribution transactions subcommands", @@ -193,7 +192,7 @@ $ %s tx set-withdraw-addr cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p --from m } // GetCmdSubmitProposal implements the command to submit a community-pool-spend proposal -func GetCmdSubmitProposal() *cobra.Command { +func GetCmdSubmitProposal(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "community-pool-spend [proposal-file]", Args: cobra.ExactArgs(1), @@ -229,12 +228,12 @@ Where proposal.json contains: ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(types.ModuleCdc)) + txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). - WithCodec(types.ModuleCdc). - WithAccountDecoder(types.ModuleCdc) + WithCodec(cdc). + WithAccountDecoder(cdc) - proposal, err := ParseCommunityPoolSpendProposalJSON(types.ModuleCdc, args[0]) + proposal, err := ParseCommunityPoolSpendProposalJSON(cdc, args[0]) if err != nil { return err } diff --git a/x/distribution/client/proposal_handler.go b/x/distribution/client/proposal_handler.go index f7d8fdf4f7dd..6514d8f5a242 100644 --- a/x/distribution/client/proposal_handler.go +++ b/x/distribution/client/proposal_handler.go @@ -7,4 +7,4 @@ import ( ) // param change proposal handler -var ProposalHandler = govclient.NewProposalHandler(cli.GetCmdSubmitProposal(), rest.ProposalRESTHandler) +var ProposalHandler = govclient.NewProposalHandler(cli.GetCmdSubmitProposal, rest.ProposalRESTHandler) diff --git a/x/distribution/module.go b/x/distribution/module.go index 37169043d872..0d8b82d0827d 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -55,13 +55,13 @@ func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router } // get the root tx command of this module -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd(StoreKey, ModuleCdc) +func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetTxCmd(StoreKey, cdc) } // get the root query command of this module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(StoreKey, ModuleCdc) +func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetQueryCmd(StoreKey, cdc) } // app module diff --git a/x/genutil/module.go b/x/genutil/module.go index 8afd4a5e7f96..0b57912c8cc6 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -53,10 +53,10 @@ func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router, _ } // get the root tx command of this module -func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } +func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } // get the root query command of this module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } +func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } //___________________________ // app module diff --git a/x/gov/client/proposal_handler.go b/x/gov/client/proposal_handler.go index 88bd94bb0bf3..c3297ee56d8f 100644 --- a/x/gov/client/proposal_handler.go +++ b/x/gov/client/proposal_handler.go @@ -11,14 +11,17 @@ import ( // function to create the rest handler type RESTHandlerFn func(context.CLIContext, *codec.Codec) rest.ProposalRESTHandler +// function to create the cli handler +type CLIHandlerFn func(*codec.Codec) *cobra.Command + // The combined type for a proposal handler for both cli and rest type ProposalHandler struct { - CLIHandler *cobra.Command + CLIHandler CLIHandlerFn RESTHandler RESTHandlerFn } // NewProposalHandler creates a new ProposalHandler object -func NewProposalHandler(cliHandler *cobra.Command, restHandler RESTHandlerFn) ProposalHandler { +func NewProposalHandler(cliHandler CLIHandlerFn, restHandler RESTHandlerFn) ProposalHandler { return ProposalHandler{ CLIHandler: cliHandler, RESTHandler: restHandler, diff --git a/x/gov/module.go b/x/gov/module.go index 672a7742cf0e..6e9a37755952 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -74,19 +74,19 @@ func (a AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Rout } // get the root tx command of this module -func (a AppModuleBasic) GetTxCmd() *cobra.Command { +func (a AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { var proposalCLIHandlers []*cobra.Command for _, proposalHandler := range a.proposalHandlers { - proposalCLIHandlers = append(proposalCLIHandlers, proposalHandler.CLIHandler) + proposalCLIHandlers = append(proposalCLIHandlers, proposalHandler.CLIHandler(cdc)) } - return cli.GetTxCmd(StoreKey, ModuleCdc, proposalCLIHandlers) + return cli.GetTxCmd(StoreKey, cdc, proposalCLIHandlers) } // get the root query command of this module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(StoreKey, ModuleCdc) +func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetQueryCmd(StoreKey, cdc) } //___________________________ diff --git a/x/mint/module.go b/x/mint/module.go index adf42d497433..061e848f503a 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -55,13 +55,11 @@ func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router } // get the root tx command of this module -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return nil -} +func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } // get the root query command of this module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(ModuleCdc) +func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetQueryCmd(cdc) } //___________________________ diff --git a/x/params/client/cli/tx.go b/x/params/client/cli/tx.go index 06c011e74445..7a1617b11b0b 100644 --- a/x/params/client/cli/tx.go +++ b/x/params/client/cli/tx.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" @@ -18,7 +19,7 @@ import ( // GetCmdSubmitProposal implements a command handler for submitting a parameter // change proposal transaction. -func GetCmdSubmitProposal() *cobra.Command { +func GetCmdSubmitProposal(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "param-change [proposal-file]", Args: cobra.ExactArgs(1), @@ -63,12 +64,12 @@ Where proposal.json contains: ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(types.ModuleCdc)) + txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). - WithCodec(types.ModuleCdc). - WithAccountDecoder(types.ModuleCdc) + WithCodec(cdc). + WithAccountDecoder(cdc) - proposal, err := paramscutils.ParseParamChangeProposalJSON(types.ModuleCdc, args[0]) + proposal, err := paramscutils.ParseParamChangeProposalJSON(cdc, args[0]) if err != nil { return err } diff --git a/x/params/client/proposal_handler.go b/x/params/client/proposal_handler.go index bc953e601ecf..040bebdf448f 100644 --- a/x/params/client/proposal_handler.go +++ b/x/params/client/proposal_handler.go @@ -7,4 +7,4 @@ import ( ) // param change proposal handler -var ProposalHandler = govclient.NewProposalHandler(cli.GetCmdSubmitProposal(), rest.ProposalRESTHandler) +var ProposalHandler = govclient.NewProposalHandler(cli.GetCmdSubmitProposal, rest.ProposalRESTHandler) diff --git a/x/params/module.go b/x/params/module.go index 36124b4156c2..f1ebed97af09 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -41,7 +41,7 @@ func (AppModuleBasic) ValidateGenesis(_ json.RawMessage) error { return nil } func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router, _ *codec.Codec) {} // get the root tx command of this module -func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } +func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } // get the root query command of this module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } +func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } diff --git a/x/slashing/module.go b/x/slashing/module.go index fc3e5bcc25e4..6d5561d0802a 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -58,13 +58,13 @@ func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router } // get the root tx command of this module -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd(ModuleCdc) +func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetTxCmd(cdc) } // get the root query command of this module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(StoreKey, ModuleCdc) +func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetQueryCmd(StoreKey, cdc) } //___________________________ diff --git a/x/staking/module.go b/x/staking/module.go index f77c87757616..54941648a8af 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -62,13 +62,13 @@ func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router } // get the root tx command of this module -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd(StoreKey, ModuleCdc) +func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetTxCmd(StoreKey, cdc) } // get the root query command of this module -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(StoreKey, ModuleCdc) +func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetQueryCmd(StoreKey, cdc) } //_____________________________________ From b646cfabe5b4c62a84b4a87bcc9f9175b60e2975 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 4 Jun 2019 19:34:11 -0400 Subject: [PATCH 20/23] update alias --- x/staking/alias.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/x/staking/alias.go b/x/staking/alias.go index 222183ae033d..bb65a9dbc9a7 100644 --- a/x/staking/alias.go +++ b/x/staking/alias.go @@ -3,9 +3,11 @@ // aliases generated for the following subdirectories: // ALIASGEN: github.com/cosmos/cosmos-sdk/x/staking/keeper // ALIASGEN: github.com/cosmos/cosmos-sdk/x/staking/types +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/staking/expected package staking import ( + "github.com/cosmos/cosmos-sdk/x/staking/expected" "github.com/cosmos/cosmos-sdk/x/staking/keeper" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -236,6 +238,9 @@ type ( FeeCollectionKeeper = types.FeeCollectionKeeper BankKeeper = types.BankKeeper AccountKeeper = types.AccountKeeper + ValidatorSet = types.ValidatorSet + DelegationSet = types.DelegationSet + StakingHooks = types.StakingHooks GenesisState = types.GenesisState LastValidatorPower = types.LastValidatorPower MultiStakingHooks = types.MultiStakingHooks @@ -254,4 +259,6 @@ type ( Validator = types.Validator Validators = types.Validators Description = types.Description + DelegationI = expected.DelegationI + ValidatorI = expected.ValidatorI ) From 9d81db8ff3fc2e0e6b74b0889e333d950b704e4a Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 5 Jun 2019 15:45:35 -0400 Subject: [PATCH 21/23] @fedekunze PR comments (round 2) --- x/bank/client/rest/{sendtx.go => tx.go} | 0 x/bank/invariants.go | 2 +- x/gov/keeper.go | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) rename x/bank/client/rest/{sendtx.go => tx.go} (100%) diff --git a/x/bank/client/rest/sendtx.go b/x/bank/client/rest/tx.go similarity index 100% rename from x/bank/client/rest/sendtx.go rename to x/bank/client/rest/tx.go diff --git a/x/bank/invariants.go b/x/bank/invariants.go index bbdc345e59f3..bd1528aa6edf 100644 --- a/x/bank/invariants.go +++ b/x/bank/invariants.go @@ -11,7 +11,7 @@ import ( // register bank invariants func RegisterInvariants(ir sdk.InvariantRouter, ak auth.AccountKeeper) { - ir.RegisterRoute(types.RouterKey, "nonnegative-outstanding", + ir.RegisterRoute(types.ModuleName, "nonnegative-outstanding", NonnegativeBalanceInvariant(ak)) } diff --git a/x/gov/keeper.go b/x/gov/keeper.go index b190b24e5320..e6d53945e1af 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -13,7 +13,7 @@ import ( "github.com/tendermint/tendermint/libs/log" ) -// TODO +// special governance addresses var ( // TODO: Find another way to implement this without using accounts, or find a cleaner way to implement it using accounts. DepositedCoinsAccAddr = sdk.AccAddress(crypto.AddressHash([]byte("govDepositedCoins"))) From 394ecd331937c16fded4765a91bbc799d3d43a1b Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 5 Jun 2019 16:24:39 -0400 Subject: [PATCH 22/23] @alexanderbez PR comments (and marko comment on queryRoute) --- client/rest/rest.go | 3 +- client/utils/utils.go | 23 ++++--- go.mod | 3 - go.sum | 4 -- x/auth/alias.go | 5 ++ x/auth/client/cli/tx_multisign.go | 3 +- x/auth/client/cli/tx_sign.go | 3 +- x/auth/client/txbuilder/stdsignmsg.go | 23 ------- x/auth/types/stdsignmsg.go | 22 +++++++ .../{client/txbuilder => types}/txbuilder.go | 23 ++++--- .../txbuilder => types}/txbuilder_test.go | 26 +++----- x/bank/client/cli/tx.go | 4 +- x/crisis/client/cli/tx.go | 4 +- x/distribution/client/cli/query.go | 14 ++-- x/distribution/client/cli/tx.go | 18 +++--- x/distribution/client/cli/tx_test.go | 8 +-- x/genutil/client/cli/gentx.go | 5 +- x/gov/client/cli/query.go | 22 +++---- x/gov/client/cli/tx.go | 8 +-- x/ibc/client/cli/ibctx.go | 4 +- x/ibc/client/cli/relay.go | 3 +- x/params/client/cli/tx.go | 4 +- x/slashing/client/cli/query.go | 4 +- x/slashing/client/cli/tx.go | 4 +- x/staking/client/cli/query.go | 64 +++++++++---------- x/staking/client/cli/tx.go | 13 ++-- x/staking/module.go | 4 +- 27 files changed, 151 insertions(+), 170 deletions(-) delete mode 100644 x/auth/client/txbuilder/stdsignmsg.go create mode 100644 x/auth/types/stdsignmsg.go rename x/auth/{client/txbuilder => types}/txbuilder.go (91%) rename x/auth/{client/txbuilder => types}/txbuilder_test.go (80%) diff --git a/client/rest/rest.go b/client/rest/rest.go index 325e54d14f57..6273afe63d7c 100644 --- a/client/rest/rest.go +++ b/client/rest/rest.go @@ -11,7 +11,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" ) //----------------------------------------------------------------------------- @@ -32,7 +31,7 @@ func WriteGenerateStdTxResponse(w http.ResponseWriter, cdc *codec.Codec, return } - txBldr := authtxb.NewTxBuilder( + txBldr := auth.NewTxBuilder( utils.GetTxEncoder(cdc), br.AccountNumber, br.Sequence, gas, gasAdj, br.Simulate, br.ChainID, br.Memo, br.Fees, br.GasPrices, ) diff --git a/client/utils/utils.go b/client/utils/utils.go index 56991dee5792..12e6a5bc4622 100644 --- a/client/utils/utils.go +++ b/client/utils/utils.go @@ -18,7 +18,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -35,7 +34,7 @@ func (gr GasEstimateResponse) String() string { // the provided context has generate-only enabled, the tx will only be printed // to STDOUT in a fully offline manner. Otherwise, the tx will be signed and // broadcasted. -func GenerateOrBroadcastMsgs(cliCtx context.CLIContext, txBldr authtxb.TxBuilder, msgs []sdk.Msg) error { +func GenerateOrBroadcastMsgs(cliCtx context.CLIContext, txBldr authtypes.TxBuilder, msgs []sdk.Msg) error { if cliCtx.GenerateOnly { return PrintUnsignedStdTx(txBldr, cliCtx, msgs) } @@ -48,7 +47,7 @@ func GenerateOrBroadcastMsgs(cliCtx context.CLIContext, txBldr authtxb.TxBuilder // QueryContext. It ensures that the account exists, has a proper number and // sequence set. In addition, it builds and signs a transaction with the // supplied messages. Finally, it broadcasts the signed transaction to a node. -func CompleteAndBroadcastTxCLI(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) error { +func CompleteAndBroadcastTxCLI(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) error { txBldr, err := PrepareTxBuilder(txBldr, cliCtx) if err != nil { return err @@ -118,7 +117,7 @@ func CompleteAndBroadcastTxCLI(txBldr authtxb.TxBuilder, cliCtx context.CLIConte // EnrichWithGas calculates the gas estimate that would be consumed by the // transaction and set the transaction's respective value accordingly. -func EnrichWithGas(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (authtxb.TxBuilder, error) { +func EnrichWithGas(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (authtypes.TxBuilder, error) { _, adjusted, err := simulateMsgs(txBldr, cliCtx, msgs) if err != nil { return txBldr, err @@ -146,7 +145,7 @@ func CalculateGas(queryFunc func(string, common.HexBytes) ([]byte, error), } // PrintUnsignedStdTx builds an unsigned StdTx and prints it to os.Stdout. -func PrintUnsignedStdTx(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) error { +func PrintUnsignedStdTx(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) error { stdTx, err := buildUnsignedStdTxOffline(txBldr, cliCtx, msgs) if err != nil { return err @@ -165,7 +164,7 @@ func PrintUnsignedStdTx(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msg // is false, it replaces the signatures already attached with the new signature. // Don't perform online validation or lookups if offline is true. func SignStdTx( - txBldr authtxb.TxBuilder, cliCtx context.CLIContext, name string, + txBldr authtypes.TxBuilder, cliCtx context.CLIContext, name string, stdTx authtypes.StdTx, appendSig bool, offline bool, ) (authtypes.StdTx, error) { @@ -201,7 +200,7 @@ func SignStdTx( // SignStdTxWithSignerAddress attaches a signature to a StdTx and returns a copy of a it. // Don't perform online validation or lookups if offline is true, else // populate account and sequence numbers from a foreign account. -func SignStdTxWithSignerAddress(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, +func SignStdTxWithSignerAddress(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, addr sdk.AccAddress, name string, stdTx authtypes.StdTx, offline bool) (signedStdTx authtypes.StdTx, err error) { @@ -243,8 +242,8 @@ func ReadStdTxFromFile(cdc *codec.Codec, filename string) (stdTx authtypes.StdTx } func populateAccountFromState( - txBldr authtxb.TxBuilder, cliCtx context.CLIContext, addr sdk.AccAddress, -) (authtxb.TxBuilder, error) { + txBldr authtypes.TxBuilder, cliCtx context.CLIContext, addr sdk.AccAddress, +) (authtypes.TxBuilder, error) { accNum, err := cliCtx.GetAccountNumber(addr) if err != nil { @@ -271,7 +270,7 @@ func GetTxEncoder(cdc *codec.Codec) (encoder sdk.TxEncoder) { // nolint // SimulateMsgs simulates the transaction and returns the gas estimate and the adjusted value. -func simulateMsgs(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (estimated, adjusted uint64, err error) { +func simulateMsgs(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (estimated, adjusted uint64, err error) { txBytes, err := txBldr.BuildTxForSim(msgs) if err != nil { return @@ -293,7 +292,7 @@ func parseQueryResponse(cdc *codec.Codec, rawRes []byte) (uint64, error) { } // PrepareTxBuilder populates a TxBuilder in preparation for the build of a Tx. -func PrepareTxBuilder(txBldr authtxb.TxBuilder, cliCtx context.CLIContext) (authtxb.TxBuilder, error) { +func PrepareTxBuilder(txBldr authtypes.TxBuilder, cliCtx context.CLIContext) (authtypes.TxBuilder, error) { if err := cliCtx.EnsureAccountExists(); err != nil { return txBldr, err } @@ -322,7 +321,7 @@ func PrepareTxBuilder(txBldr authtxb.TxBuilder, cliCtx context.CLIContext) (auth return txBldr, nil } -func buildUnsignedStdTxOffline(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (stdTx authtypes.StdTx, err error) { +func buildUnsignedStdTxOffline(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (stdTx authtypes.StdTx, err error) { if txBldr.SimulateAndExecute() { if cliCtx.GenerateOnly { return stdTx, errors.New("cannot estimate gas with generate-only") diff --git a/go.mod b/go.mod index 5af178a06070..7a9886c738ef 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,6 @@ require ( github.com/cosmos/go-bip39 v0.0.0-20180618194314-52158e4697b8 github.com/cosmos/ledger-cosmos-go v0.10.3 github.com/fortytw2/leaktest v1.3.0 // indirect - github.com/go-kit/kit v0.8.0 github.com/go-logfmt/logfmt v0.4.0 // indirect github.com/gogo/protobuf v1.1.1 github.com/golang/protobuf v1.3.0 @@ -20,9 +19,7 @@ require ( github.com/jmhodges/levigo v1.0.0 // indirect github.com/magiconair/properties v1.8.0 // indirect github.com/mattn/go-isatty v0.0.6 - github.com/mattn/go-runewidth v0.0.4 // indirect github.com/mitchellh/mapstructure v1.1.2 // indirect - github.com/olekukonko/tablewriter v0.0.1 github.com/pelletier/go-toml v1.2.0 github.com/pkg/errors v0.8.1 github.com/prometheus/client_golang v0.9.2 // indirect diff --git a/go.sum b/go.sum index 75bd5f7481a0..1d0f153daa76 100644 --- a/go.sum +++ b/go.sum @@ -82,15 +82,11 @@ github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDe github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mattn/go-isatty v0.0.6 h1:SrwhHcpV4nWrMGdNcC2kXpMfcBVYGDuTArqyhocJgvA= github.com/mattn/go-isatty v0.0.6/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y= -github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/olekukonko/tablewriter v0.0.1 h1:b3iUnf1v+ppJiOfNX4yxxqfWKMQPZR5yoh8urCTFX88= -github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= diff --git a/x/auth/alias.go b/x/auth/alias.go index c2471b10d3a6..3c1fe15fde10 100644 --- a/x/auth/alias.go +++ b/x/auth/alias.go @@ -56,6 +56,9 @@ var ( NewTestTx = types.NewTestTx NewTestTxWithMemo = types.NewTestTxWithMemo NewTestTxWithSignBytes = types.NewTestTxWithSignBytes + NewTxBuilder = types.NewTxBuilder + NewTxBuilderFromCLI = types.NewTxBuilderFromCLI + MakeSignature = types.MakeSignature // variable aliases ModuleCdc = types.ModuleCdc @@ -80,8 +83,10 @@ type ( GenesisState = types.GenesisState Params = types.Params QueryAccountParams = types.QueryAccountParams + StdSignMsg = types.StdSignMsg StdTx = types.StdTx StdFee = types.StdFee StdSignDoc = types.StdSignDoc StdSignature = types.StdSignature + TxBuilder = types.TxBuilder ) diff --git a/x/auth/client/cli/tx_multisign.go b/x/auth/client/cli/tx_multisign.go index 5535af047a58..c1a88a6a0b03 100644 --- a/x/auth/client/cli/tx_multisign.go +++ b/x/auth/client/cli/tx_multisign.go @@ -19,7 +19,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" crkeys "github.com/cosmos/cosmos-sdk/crypto/keys" "github.com/cosmos/cosmos-sdk/version" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -82,7 +81,7 @@ func makeMultiSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) multisigPub := multisigInfo.GetPubKey().(multisig.PubKeyMultisigThreshold) multisigSig := multisig.NewMultisig(len(multisigPub.PubKeys)) cliCtx := context.NewCLIContext().WithCodec(cdc).WithAccountDecoder(cdc) - txBldr := authtxb.NewTxBuilderFromCLI() + txBldr := types.NewTxBuilderFromCLI() if !viper.GetBool(flagOffline) { addr := multisigInfo.GetAddress() diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index 950fa4708b94..f7be335010e4 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -14,7 +14,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -101,7 +100,7 @@ func makeSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error offline := viper.GetBool(flagOffline) cliCtx := context.NewCLIContext().WithCodec(cdc).WithAccountDecoder(cdc) - txBldr := authtxb.NewTxBuilderFromCLI() + txBldr := types.NewTxBuilderFromCLI() if viper.GetBool(flagValidateSigs) { if !printAndValidateSigs(cliCtx, txBldr.ChainID(), stdTx, offline) { diff --git a/x/auth/client/txbuilder/stdsignmsg.go b/x/auth/client/txbuilder/stdsignmsg.go deleted file mode 100644 index 465b10be600e..000000000000 --- a/x/auth/client/txbuilder/stdsignmsg.go +++ /dev/null @@ -1,23 +0,0 @@ -package context - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// StdSignMsg is a convenience structure for passing along -// a Msg with the other requirements for a StdSignDoc before -// it is signed. For use in the CLI. -type StdSignMsg struct { - ChainID string `json:"chain_id"` - AccountNumber uint64 `json:"account_number"` - Sequence uint64 `json:"sequence"` - Fee types.StdFee `json:"fee"` - Msgs []sdk.Msg `json:"msgs"` - Memo string `json:"memo"` -} - -// get message bytes -func (msg StdSignMsg) Bytes() []byte { - return types.StdSignBytes(msg.ChainID, msg.AccountNumber, msg.Sequence, msg.Fee, msg.Msgs, msg.Memo) -} diff --git a/x/auth/types/stdsignmsg.go b/x/auth/types/stdsignmsg.go new file mode 100644 index 000000000000..889982811a46 --- /dev/null +++ b/x/auth/types/stdsignmsg.go @@ -0,0 +1,22 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// StdSignMsg is a convenience structure for passing along +// a Msg with the other requirements for a StdSignDoc before +// it is signed. For use in the CLI. +type StdSignMsg struct { + ChainID string `json:"chain_id"` + AccountNumber uint64 `json:"account_number"` + Sequence uint64 `json:"sequence"` + Fee StdFee `json:"fee"` + Msgs []sdk.Msg `json:"msgs"` + Memo string `json:"memo"` +} + +// get message bytes +func (msg StdSignMsg) Bytes() []byte { + return StdSignBytes(msg.ChainID, msg.AccountNumber, msg.Sequence, msg.Fee, msg.Msgs, msg.Memo) +} diff --git a/x/auth/client/txbuilder/txbuilder.go b/x/auth/types/txbuilder.go similarity index 91% rename from x/auth/client/txbuilder/txbuilder.go rename to x/auth/types/txbuilder.go index 8da587b12ac9..b29d977fd468 100644 --- a/x/auth/client/txbuilder/txbuilder.go +++ b/x/auth/types/txbuilder.go @@ -1,4 +1,4 @@ -package context +package types import ( "errors" @@ -11,7 +11,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/keys" crkeys "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" ) // TxBuilder implements a transaction context created in SDK modules. @@ -203,7 +202,7 @@ func (bldr TxBuilder) BuildSignMsg(msgs []sdk.Msg) (StdSignMsg, error) { Sequence: bldr.sequence, Memo: bldr.memo, Msgs: msgs, - Fee: types.NewStdFee(bldr.gas, fees), + Fee: NewStdFee(bldr.gas, fees), }, nil } @@ -215,7 +214,7 @@ func (bldr TxBuilder) Sign(name, passphrase string, msg StdSignMsg) ([]byte, err return nil, err } - return bldr.txEncoder(types.NewStdTx(msg.Msgs, msg.Fee, []types.StdSignature{sig}, msg.Memo)) + return bldr.txEncoder(NewStdTx(msg.Msgs, msg.Fee, []StdSignature{sig}, msg.Memo)) } // BuildAndSign builds a single message to be signed, and signs a transaction @@ -238,15 +237,15 @@ func (bldr TxBuilder) BuildTxForSim(msgs []sdk.Msg) ([]byte, error) { } // the ante handler will populate with a sentinel pubkey - sigs := []types.StdSignature{{}} - return bldr.txEncoder(types.NewStdTx(signMsg.Msgs, signMsg.Fee, sigs, signMsg.Memo)) + sigs := []StdSignature{{}} + return bldr.txEncoder(NewStdTx(signMsg.Msgs, signMsg.Fee, sigs, signMsg.Memo)) } // SignStdTx appends a signature to a StdTx and returns a copy of it. If append // is false, it replaces the signatures already attached with the new signature. -func (bldr TxBuilder) SignStdTx(name, passphrase string, stdTx types.StdTx, appendSig bool) (signedStdTx types.StdTx, err error) { +func (bldr TxBuilder) SignStdTx(name, passphrase string, stdTx StdTx, appendSig bool) (signedStdTx StdTx, err error) { if bldr.chainID == "" { - return types.StdTx{}, fmt.Errorf("chain ID required but not specified") + return StdTx{}, fmt.Errorf("chain ID required but not specified") } stdSignature, err := MakeSignature(bldr.keybase, name, passphrase, StdSignMsg{ @@ -263,17 +262,17 @@ func (bldr TxBuilder) SignStdTx(name, passphrase string, stdTx types.StdTx, appe sigs := stdTx.GetSignatures() if len(sigs) == 0 || !appendSig { - sigs = []types.StdSignature{stdSignature} + sigs = []StdSignature{stdSignature} } else { sigs = append(sigs, stdSignature) } - signedStdTx = types.NewStdTx(stdTx.GetMsgs(), stdTx.Fee, sigs, stdTx.GetMemo()) + signedStdTx = NewStdTx(stdTx.GetMsgs(), stdTx.Fee, sigs, stdTx.GetMemo()) return } // MakeSignature builds a StdSignature given keybase, key name, passphrase, and a StdSignMsg. func MakeSignature(keybase crkeys.Keybase, name, passphrase string, - msg StdSignMsg) (sig types.StdSignature, err error) { + msg StdSignMsg) (sig StdSignature, err error) { if keybase == nil { keybase, err = keys.NewKeyBaseFromHomeFlag() if err != nil { @@ -285,7 +284,7 @@ func MakeSignature(keybase crkeys.Keybase, name, passphrase string, if err != nil { return } - return types.StdSignature{ + return StdSignature{ PubKey: pubkey, Signature: sigBytes, }, nil diff --git a/x/auth/client/txbuilder/txbuilder_test.go b/x/auth/types/txbuilder_test.go similarity index 80% rename from x/auth/client/txbuilder/txbuilder_test.go rename to x/auth/types/txbuilder_test.go index 9b39c92bba47..063401c8a4ba 100644 --- a/x/auth/client/txbuilder/txbuilder_test.go +++ b/x/auth/types/txbuilder_test.go @@ -1,4 +1,4 @@ -package context +package types import ( "reflect" @@ -6,16 +6,8 @@ import ( "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -var ( - priv = ed25519.GenPrivKey() - addr = sdk.AccAddress(priv.PubKey().Address()) ) func TestTxBuilderBuild(t *testing.T) { @@ -42,7 +34,7 @@ func TestTxBuilderBuild(t *testing.T) { { "builder with fees", fields{ - TxEncoder: types.DefaultTxEncoder(codec.New()), + TxEncoder: DefaultTxEncoder(codec.New()), AccountNumber: 1, Sequence: 1, Gas: 200000, @@ -59,14 +51,14 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager 1!", Msgs: defaultMsg, - Fee: types.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), + Fee: NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), }, false, }, { "builder with gas prices", fields{ - TxEncoder: types.DefaultTxEncoder(codec.New()), + TxEncoder: DefaultTxEncoder(codec.New()), AccountNumber: 1, Sequence: 1, Gas: 200000, @@ -83,14 +75,14 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager 2!", Msgs: defaultMsg, - Fee: types.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), + Fee: NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), }, false, }, { "no chain-id supplied", fields{ - TxEncoder: types.DefaultTxEncoder(codec.New()), + TxEncoder: DefaultTxEncoder(codec.New()), AccountNumber: 1, Sequence: 1, Gas: 200000, @@ -107,14 +99,14 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager 1!", Msgs: defaultMsg, - Fee: types.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), + Fee: NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), }, true, }, { "builder w/ fees and gas prices", fields{ - TxEncoder: types.DefaultTxEncoder(codec.New()), + TxEncoder: DefaultTxEncoder(codec.New()), AccountNumber: 1, Sequence: 1, Gas: 200000, @@ -132,7 +124,7 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager 1!", Msgs: defaultMsg, - Fee: types.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), + Fee: NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), }, true, }, diff --git a/x/bank/client/cli/tx.go b/x/bank/client/cli/tx.go index b41000bcc2fb..86209a51fe64 100644 --- a/x/bank/client/cli/tx.go +++ b/x/bank/client/cli/tx.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + auth "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank/types" ) @@ -39,7 +39,7 @@ func SendTxCmd(cdc *codec.Codec) *cobra.Command { Short: "Create and sign a send tx", Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContextWithFrom(args[0]). WithCodec(cdc). WithAccountDecoder(cdc) diff --git a/x/crisis/client/cli/tx.go b/x/crisis/client/cli/tx.go index 0978d5a78d21..4cd41c4f1d8c 100644 --- a/x/crisis/client/cli/tx.go +++ b/x/crisis/client/cli/tx.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + auth "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/crisis/types" ) @@ -21,7 +21,7 @@ func GetCmdInvariantBroken(cdc *codec.Codec) *cobra.Command { Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext().WithCodec(cdc).WithAccountDecoder(cdc) senderAddr := cliCtx.GetFromAddress() diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index b688b182895b..b1c1dd97be4f 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -18,7 +18,7 @@ import ( ) // GetQueryCmd returns the cli query commands for this module -func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { distQueryCmd := &cobra.Command{ Use: types.ModuleName, Short: "Querying commands for the distribution module", @@ -28,12 +28,12 @@ func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { } distQueryCmd.AddCommand(client.GetCommands( - GetCmdQueryParams(storeKey, cdc), - GetCmdQueryValidatorOutstandingRewards(storeKey, cdc), - GetCmdQueryValidatorCommission(storeKey, cdc), - GetCmdQueryValidatorSlashes(storeKey, cdc), - GetCmdQueryDelegatorRewards(storeKey, cdc), - GetCmdQueryCommunityPool(storeKey, cdc), + GetCmdQueryParams(queryRoute, cdc), + GetCmdQueryValidatorOutstandingRewards(queryRoute, cdc), + GetCmdQueryValidatorCommission(queryRoute, cdc), + GetCmdQueryValidatorSlashes(queryRoute, cdc), + GetCmdQueryDelegatorRewards(queryRoute, cdc), + GetCmdQueryCommunityPool(queryRoute, cdc), )...) return distQueryCmd diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index 99e0fc69904c..83a5b2f24725 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -14,8 +14,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + auth "github.com/cosmos/cosmos-sdk/x/auth" + gov "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/distribution/client/common" "github.com/cosmos/cosmos-sdk/x/distribution/types" @@ -51,12 +51,12 @@ func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command { return distTxCmd } -type generateOrBroadcastFunc func(context.CLIContext, authtxb.TxBuilder, []sdk.Msg) error +type generateOrBroadcastFunc func(context.CLIContext, auth.TxBuilder, []sdk.Msg) error func splitAndApply( generateOrBroadcast generateOrBroadcastFunc, cliCtx context.CLIContext, - txBldr authtxb.TxBuilder, + txBldr auth.TxBuilder, msgs []sdk.Msg, chunkSize int, ) error { @@ -101,7 +101,7 @@ $ %s tx distr withdraw-rewards cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqh ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -141,7 +141,7 @@ $ %s tx distr withdraw-all-rewards --from mykey Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -177,7 +177,7 @@ $ %s tx set-withdraw-addr cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p --from m Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -231,7 +231,7 @@ Where proposal.json contains: ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -244,7 +244,7 @@ Where proposal.json contains: from := cliCtx.GetFromAddress() content := types.NewCommunityPoolSpendProposal(proposal.Title, proposal.Description, proposal.Recipient, proposal.Amount) - msg := govtypes.NewMsgSubmitProposal(content, proposal.Deposit, from) + msg := gov.NewMsgSubmitProposal(content, proposal.Deposit, from) if err := msg.ValidateBasic(); err != nil { return err } diff --git a/x/distribution/client/cli/tx_test.go b/x/distribution/client/cli/tx_test.go index 333ce645f85a..6996464086f2 100644 --- a/x/distribution/client/cli/tx_test.go +++ b/x/distribution/client/cli/tx_test.go @@ -10,12 +10,12 @@ import ( "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + auth "github.com/cosmos/cosmos-sdk/x/auth" ) -func createFakeTxBuilder() authtxb.TxBuilder { +func createFakeTxBuilder() auth.TxBuilder { cdc := codec.New() - return authtxb.NewTxBuilder( + return auth.NewTxBuilder( utils.GetTxEncoder(cdc), 123, 9876, @@ -57,7 +57,7 @@ func Test_splitAndCall_Splitting(t *testing.T) { callCount := 0 err := splitAndApply( - func(ctx context.CLIContext, txBldr authtxb.TxBuilder, msgs []sdk.Msg) error { + func(ctx context.CLIContext, txBldr auth.TxBuilder, msgs []sdk.Msg) error { callCount++ assert.NotNil(t, ctx) diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 350b579e9ada..bb04bc2ff638 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -27,7 +27,6 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" "github.com/cosmos/cosmos-sdk/x/genutil" ) @@ -35,7 +34,7 @@ import ( type StakingMsgBuildingHelpers interface { CreateValidatorMsgHelpers(ipDefault string) (fs *flag.FlagSet, nodeIDFlag, pubkeyFlag, amountFlag, defaultsDesc string) PrepareFlagsForTxCreateValidator(config *cfg.Config, nodeID, chainID string, valPubKey crypto.PubKey) - BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr authtxb.TxBuilder) (authtxb.TxBuilder, sdk.Msg, error) + BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr auth.TxBuilder) (auth.TxBuilder, sdk.Msg, error) } // GenTxCmd builds the application's gentx command. @@ -118,7 +117,7 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, sm return err } - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(client.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(client.GetTxEncoder(cdc)) cliCtx := client.NewCLIContext().WithCodec(cdc) // Set the generate-only flag here after the CLI context has diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index ebae16e5b93e..c0418c1eb638 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -19,7 +19,7 @@ import ( ) // GetQueryCmd returns the cli query commands for this module -func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { // Group gov queries under a subcommand govQueryCmd := &cobra.Command{ Use: types.ModuleName, @@ -30,16 +30,16 @@ func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { } govQueryCmd.AddCommand(client.GetCommands( - GetCmdQueryProposal(storeKey, cdc), - GetCmdQueryProposals(storeKey, cdc), - GetCmdQueryVote(storeKey, cdc), - GetCmdQueryVotes(storeKey, cdc), - GetCmdQueryParam(storeKey, cdc), - GetCmdQueryParams(storeKey, cdc), - GetCmdQueryProposer(storeKey, cdc), - GetCmdQueryDeposit(storeKey, cdc), - GetCmdQueryDeposits(storeKey, cdc), - GetCmdQueryTally(storeKey, cdc))...) + GetCmdQueryProposal(queryRoute, cdc), + GetCmdQueryProposals(queryRoute, cdc), + GetCmdQueryVote(queryRoute, cdc), + GetCmdQueryVotes(queryRoute, cdc), + GetCmdQueryParam(queryRoute, cdc), + GetCmdQueryParams(queryRoute, cdc), + GetCmdQueryProposer(queryRoute, cdc), + GetCmdQueryDeposit(queryRoute, cdc), + GetCmdQueryDeposits(queryRoute, cdc), + GetCmdQueryTally(queryRoute, cdc))...) return govQueryCmd } diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index 5b7f42b302f8..144085688cee 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -13,7 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + "github.com/cosmos/cosmos-sdk/x/auth" govutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" "github.com/cosmos/cosmos-sdk/x/gov/types" ) @@ -105,7 +105,7 @@ $ %s tx gov submit-proposal --title="Test Proposal" --description="My awesome pr ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -157,7 +157,7 @@ $ %s tx gov deposit 1 10stake --from mykey ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -206,7 +206,7 @@ $ %s tx gov vote 1 yes --from mykey ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) diff --git a/x/ibc/client/cli/ibctx.go b/x/ibc/client/cli/ibctx.go index 9a5ac05ee661..0b706cbed1d7 100644 --- a/x/ibc/client/cli/ibctx.go +++ b/x/ibc/client/cli/ibctx.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + auth "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/ibc" "github.com/spf13/cobra" @@ -26,7 +26,7 @@ func IBCTransferCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "transfer", RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) diff --git a/x/ibc/client/cli/relay.go b/x/ibc/client/cli/relay.go index c1c45611eb3f..577dcc0d18c3 100644 --- a/x/ibc/client/cli/relay.go +++ b/x/ibc/client/cli/relay.go @@ -12,7 +12,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" "github.com/cosmos/cosmos-sdk/x/ibc" "github.com/spf13/cobra" @@ -197,7 +196,7 @@ func (c relayCommander) refine(bz []byte, ibcSeq, accSeq uint64, passphrase stri Sequence: ibcSeq, } - txBldr := authtxb.NewTxBuilderFromCLI().WithSequence(accSeq).WithTxEncoder(utils.GetTxEncoder(c.cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithSequence(accSeq).WithTxEncoder(utils.GetTxEncoder(c.cdc)) cliCtx := context.NewCLIContext() name := cliCtx.GetFromName() diff --git a/x/params/client/cli/tx.go b/x/params/client/cli/tx.go index 7a1617b11b0b..d974f02b94a3 100644 --- a/x/params/client/cli/tx.go +++ b/x/params/client/cli/tx.go @@ -11,7 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + auth "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/gov" paramscutils "github.com/cosmos/cosmos-sdk/x/params/client/utils" "github.com/cosmos/cosmos-sdk/x/params/types" @@ -64,7 +64,7 @@ Where proposal.json contains: ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) diff --git a/x/slashing/client/cli/query.go b/x/slashing/client/cli/query.go index c8de01198731..de149a79dc56 100644 --- a/x/slashing/client/cli/query.go +++ b/x/slashing/client/cli/query.go @@ -16,7 +16,7 @@ import ( ) // GetQueryCmd returns the cli query commands for this module -func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { // Group slashing queries under a subcommand slashingQueryCmd := &cobra.Command{ Use: types.ModuleName, @@ -28,7 +28,7 @@ func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { slashingQueryCmd.AddCommand( client.GetCommands( - GetCmdQuerySigningInfo(storeKey, cdc), + GetCmdQuerySigningInfo(queryRoute, cdc), GetCmdQueryParams(cdc), )..., ) diff --git a/x/slashing/client/cli/tx.go b/x/slashing/client/cli/tx.go index f7164af87e77..01663254a197 100644 --- a/x/slashing/client/cli/tx.go +++ b/x/slashing/client/cli/tx.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) @@ -40,7 +40,7 @@ func GetCmdUnjail(cdc *codec.Codec) *cobra.Command { $ tx slashing unjail --from mykey `, RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) diff --git a/x/staking/client/cli/query.go b/x/staking/client/cli/query.go index 966724c3e183..f9ea5314ec86 100644 --- a/x/staking/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -16,7 +16,7 @@ import ( ) // GetQueryCmd returns the cli query commands for this module -func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { stakingQueryCmd := &cobra.Command{ Use: types.ModuleName, Short: "Querying commands for the staking module", @@ -25,19 +25,19 @@ func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { RunE: utils.ValidateCmd, } stakingQueryCmd.AddCommand(client.GetCommands( - GetCmdQueryDelegation(storeKey, cdc), - GetCmdQueryDelegations(storeKey, cdc), - GetCmdQueryUnbondingDelegation(storeKey, cdc), - GetCmdQueryUnbondingDelegations(storeKey, cdc), - GetCmdQueryRedelegation(storeKey, cdc), - GetCmdQueryRedelegations(storeKey, cdc), - GetCmdQueryValidator(storeKey, cdc), - GetCmdQueryValidators(storeKey, cdc), - GetCmdQueryValidatorDelegations(storeKey, cdc), - GetCmdQueryValidatorUnbondingDelegations(storeKey, cdc), - GetCmdQueryValidatorRedelegations(storeKey, cdc), - GetCmdQueryParams(storeKey, cdc), - GetCmdQueryPool(storeKey, cdc))...) + GetCmdQueryDelegation(queryRoute, cdc), + GetCmdQueryDelegations(queryRoute, cdc), + GetCmdQueryUnbondingDelegation(queryRoute, cdc), + GetCmdQueryUnbondingDelegations(queryRoute, cdc), + GetCmdQueryRedelegation(queryRoute, cdc), + GetCmdQueryRedelegations(queryRoute, cdc), + GetCmdQueryValidator(queryRoute, cdc), + GetCmdQueryValidators(queryRoute, cdc), + GetCmdQueryValidatorDelegations(queryRoute, cdc), + GetCmdQueryValidatorUnbondingDelegations(queryRoute, cdc), + GetCmdQueryValidatorRedelegations(queryRoute, cdc), + GetCmdQueryParams(queryRoute, cdc), + GetCmdQueryPool(queryRoute, cdc))...) return stakingQueryCmd @@ -114,7 +114,7 @@ $ %s query staking validators } // GetCmdQueryValidatorUnbondingDelegations implements the query all unbonding delegatations from a validator command. -func GetCmdQueryValidatorUnbondingDelegations(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryValidatorUnbondingDelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "unbonding-delegations-from [validator-addr]", Short: "Query all unbonding delegatations from a validator", @@ -141,7 +141,7 @@ $ %s query staking unbonding-delegations-from cosmosvaloper1gghjut3ccd8ay0zduzj6 return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryValidatorUnbondingDelegations) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryValidatorUnbondingDelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -156,7 +156,7 @@ $ %s query staking unbonding-delegations-from cosmosvaloper1gghjut3ccd8ay0zduzj6 // GetCmdQueryValidatorRedelegations implements the query all redelegatations // from a validator command. -func GetCmdQueryValidatorRedelegations(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryValidatorRedelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "redelegations-from [validator-addr]", Short: "Query all outgoing redelegatations from a validator", @@ -183,7 +183,7 @@ $ %s query staking redelegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fx return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryRedelegations) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryRedelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -200,7 +200,7 @@ $ %s query staking redelegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fx } // GetCmdQueryDelegation the query delegation command. -func GetCmdQueryDelegation(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryDelegation(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "delegation [delegator-addr] [validator-addr]", Short: "Query a delegation based on address and validator address", @@ -232,7 +232,7 @@ $ %s query staking delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosm return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryDelegation) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegation) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -250,7 +250,7 @@ $ %s query staking delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosm // GetCmdQueryDelegations implements the command to query all the delegations // made from one delegator. -func GetCmdQueryDelegations(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryDelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "delegations [delegator-addr]", Short: "Query all delegations made by one delegator", @@ -277,7 +277,7 @@ $ %s query staking delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryDelegatorDelegations) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorDelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -295,7 +295,7 @@ $ %s query staking delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p // GetCmdQueryValidatorDelegations implements the command to query all the // delegations to a specific validator. -func GetCmdQueryValidatorDelegations(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryValidatorDelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "delegations-to [validator-addr]", Short: "Query all delegations made to one validator", @@ -322,7 +322,7 @@ $ %s query staking delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ld return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryValidatorDelegations) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryValidatorDelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -340,7 +340,7 @@ $ %s query staking delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ld // GetCmdQueryUnbondingDelegation implements the command to query a single // unbonding-delegation record. -func GetCmdQueryUnbondingDelegation(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryUnbondingDelegation(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "unbonding-delegation [delegator-addr] [validator-addr]", Short: "Query an unbonding-delegation record based on delegator and validator address", @@ -372,7 +372,7 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7 return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryUnbondingDelegation) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryUnbondingDelegation) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -385,7 +385,7 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7 // GetCmdQueryUnbondingDelegations implements the command to query all the // unbonding-delegation records for a delegator. -func GetCmdQueryUnbondingDelegations(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryUnbondingDelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "unbonding-delegations [delegator-addr]", Short: "Query all unbonding-delegations records for one delegator", @@ -412,7 +412,7 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7 return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryDelegatorUnbondingDelegations) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorUnbondingDelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -430,7 +430,7 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7 // GetCmdQueryRedelegation implements the command to query a single // redelegation record. -func GetCmdQueryRedelegation(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryRedelegation(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "redelegation [delegator-addr] [src-validator-addr] [dst-validator-addr]", Short: "Query a redelegation record based on delegator and a source and destination validator address", @@ -467,7 +467,7 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryRedelegations) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryRedelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -485,7 +485,7 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co // GetCmdQueryRedelegations implements the command to query all the // redelegation records for a delegator. -func GetCmdQueryRedelegations(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryRedelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "redelegations [delegator-addr]", Args: cobra.ExactArgs(1), @@ -512,7 +512,7 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, types.QueryRedelegations) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryRedelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index dd9e5b66222d..665b6428f0bd 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -19,7 +19,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/auth" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -50,7 +49,7 @@ func GetCmdCreateValidator(cdc *codec.Codec) *cobra.Command { Use: "create-validator", Short: "create new validator initialized with a self-delegation to it", RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -88,7 +87,7 @@ func GetCmdEditValidator(cdc *codec.Codec) *cobra.Command { Use: "edit-validator", Short: "edit an existing validator account", RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -153,7 +152,7 @@ $ %s tx staking delegate cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 10 ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -191,7 +190,7 @@ $ %s tx staking redelegate cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -234,7 +233,7 @@ $ %s tx staking unbond cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100s ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -341,7 +340,7 @@ func PrepareFlagsForTxCreateValidator( } // BuildCreateValidatorMsg makes a new MsgCreateValidator. -func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr authtxb.TxBuilder) (authtxb.TxBuilder, sdk.Msg, error) { +func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr auth.TxBuilder) (auth.TxBuilder, sdk.Msg, error) { amounstStr := viper.GetString(FlagAmount) amount, err := sdk.ParseCoin(amounstStr) if err != nil { diff --git a/x/staking/module.go b/x/staking/module.go index 54941648a8af..8a540cb25fb0 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -15,7 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/staking/client/cli" "github.com/cosmos/cosmos-sdk/x/staking/client/rest" "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -88,7 +88,7 @@ func (AppModuleBasic) PrepareFlagsForTxCreateValidator(config *cfg.Config, nodeI // BuildCreateValidatorMsg - used for gen-tx func (AppModuleBasic) BuildCreateValidatorMsg(cliCtx context.CLIContext, - txBldr authtxb.TxBuilder) (authtxb.TxBuilder, sdk.Msg, error) { + txBldr authtypes.TxBuilder) (authtypes.TxBuilder, sdk.Msg, error) { return cli.BuildCreateValidatorMsg(cliCtx, txBldr) } From 02ab8f69810ed56daa2c955cf0916f2d6d4a42ac Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Wed, 5 Jun 2019 19:21:41 -0400 Subject: [PATCH 23/23] Fix pending file --- .pending/breaking/sdk/4451-Improve-modular | 5 +++++ .pending/improvements/sdk/4451-RegisterRoutes- | 1 - 2 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 .pending/breaking/sdk/4451-Improve-modular delete mode 100644 .pending/improvements/sdk/4451-RegisterRoutes- diff --git a/.pending/breaking/sdk/4451-Improve-modular b/.pending/breaking/sdk/4451-Improve-modular new file mode 100644 index 000000000000..ce9278f18b3d --- /dev/null +++ b/.pending/breaking/sdk/4451-Improve-modular @@ -0,0 +1,5 @@ +#4451 Improve modularization of clients and modules: + * Module directory structure improved and standardized + * Aliases autogenerated + * Auth and bank related commands are now mounted under the respective moduels + * Client initialization and mounting standardized diff --git a/.pending/improvements/sdk/4451-RegisterRoutes- b/.pending/improvements/sdk/4451-RegisterRoutes- deleted file mode 100644 index 8d638c3c3441..000000000000 --- a/.pending/improvements/sdk/4451-RegisterRoutes- +++ /dev/null @@ -1 +0,0 @@ -#4451 RegisterRoutes and ModuleClient to BasicModule pattern \ No newline at end of file