diff --git a/CHANGELOG.md b/CHANGELOG.md index 56f65c1a34bf..02fa507c2bb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -112,6 +112,21 @@ be used to retrieve the actual proposal `Content`. Also the `NewMsgSubmitProposa - TxBuilder.BuildAndSign - TxBuilder.Sign - TxBuilder.SignStdTx +* (client) [\#6290](https://github.com/cosmos/cosmos-sdk/pull/6290) `CLIContext` is renamed to `Context`. `Context` and all related methods have been moved from package context to client. + + Migration guide: + + ```go + cliCtx := context.CLIContext{} + ``` + + Now becomes: + + ```go + clientCtx = client.Context{} + ``` +* (client/rpc) [\#6290](https://github.com/cosmos/cosmos-sdk/pull/6290) `RegisterRoutes` of rpc is moved from package client to client/rpc and client/rpc.RegisterRPCRoutes is removed. +* (client/lcd) [\#6290](https://github.com/cosmos/cosmos-sdk/pull/6290) `CliCtx` of struct `RestServer` in package client/lcd has been renamed to `ClientCtx`. ### Features diff --git a/Makefile b/Makefile index b7064e8d221d..659de6a51cc4 100644 --- a/Makefile +++ b/Makefile @@ -36,7 +36,7 @@ build-sim: go.sum build-sim mocks: $(MOCKS_DIR) - mockgen -source=client/context/account_retriever.go -package mocks -destination tests/mocks/account_retriever.go + mockgen -source=client/account_retriever.go -package mocks -destination tests/mocks/account_retriever.go mockgen -package mocks -destination tests/mocks/tendermint_tm_db_DB.go github.com/tendermint/tm-db DB mockgen -source=types/module/module.go -package mocks -destination tests/mocks/types_module_module.go mockgen -source=types/invariant.go -package mocks -destination tests/mocks/types_invariant.go diff --git a/client/context/account_retriever.go b/client/account_retriever.go similarity index 94% rename from client/context/account_retriever.go rename to client/account_retriever.go index 595eadde91b5..0e124d2fbcb1 100644 --- a/client/context/account_retriever.go +++ b/client/account_retriever.go @@ -1,4 +1,4 @@ -package context +package client import "github.com/cosmos/cosmos-sdk/types" @@ -18,4 +18,4 @@ type NodeQuerier interface { QueryWithData(path string, data []byte) ([]byte, int64, error) } -var _ NodeQuerier = CLIContext{} +var _ NodeQuerier = Context{} diff --git a/client/context/broadcast.go b/client/broadcast.go similarity index 92% rename from client/context/broadcast.go rename to client/broadcast.go index 5f3d952452f6..203a3677065c 100644 --- a/client/context/broadcast.go +++ b/client/broadcast.go @@ -1,4 +1,4 @@ -package context +package client import ( "fmt" @@ -16,7 +16,7 @@ import ( // based on the context parameters. The result of the broadcast is parsed into // an intermediate structure which is logged if the context has a logger // defined. -func (ctx CLIContext) BroadcastTx(txBytes []byte) (res sdk.TxResponse, err error) { +func (ctx Context) BroadcastTx(txBytes []byte) (res sdk.TxResponse, err error) { switch ctx.BroadcastMode { case flags.BroadcastSync: res, err = ctx.BroadcastTxSync(txBytes) @@ -84,7 +84,7 @@ func CheckTendermintError(err error, txBytes []byte) *sdk.TxResponse { // NOTE: This should ideally not be used as the request may timeout but the tx // may still be included in a block. Use BroadcastTxAsync or BroadcastTxSync // instead. -func (ctx CLIContext) BroadcastTxCommit(txBytes []byte) (sdk.TxResponse, error) { +func (ctx Context) BroadcastTxCommit(txBytes []byte) (sdk.TxResponse, error) { node, err := ctx.GetNode() if err != nil { return sdk.TxResponse{}, err @@ -112,7 +112,7 @@ func (ctx CLIContext) BroadcastTxCommit(txBytes []byte) (sdk.TxResponse, error) // BroadcastTxSync broadcasts transaction bytes to a Tendermint node // synchronously (i.e. returns after CheckTx execution). -func (ctx CLIContext) BroadcastTxSync(txBytes []byte) (sdk.TxResponse, error) { +func (ctx Context) BroadcastTxSync(txBytes []byte) (sdk.TxResponse, error) { node, err := ctx.GetNode() if err != nil { return sdk.TxResponse{}, err @@ -128,7 +128,7 @@ func (ctx CLIContext) BroadcastTxSync(txBytes []byte) (sdk.TxResponse, error) { // BroadcastTxAsync broadcasts transaction bytes to a Tendermint node // asynchronously (i.e. returns immediately). -func (ctx CLIContext) BroadcastTxAsync(txBytes []byte) (sdk.TxResponse, error) { +func (ctx Context) BroadcastTxAsync(txBytes []byte) (sdk.TxResponse, error) { node, err := ctx.GetNode() if err != nil { return sdk.TxResponse{}, err diff --git a/client/context/broadcast_test.go b/client/broadcast_test.go similarity index 94% rename from client/context/broadcast_test.go rename to client/broadcast_test.go index cc429818aebf..4e97925ce81b 100644 --- a/client/context/broadcast_test.go +++ b/client/broadcast_test.go @@ -1,4 +1,4 @@ -package context +package client import ( "fmt" @@ -32,8 +32,8 @@ func (c MockClient) BroadcastTxSync(tx tmtypes.Tx) (*ctypes.ResultBroadcastTx, e return nil, c.err } -func CreateContextWithErrorAndMode(err error, mode string) CLIContext { - return CLIContext{ +func CreateContextWithErrorAndMode(err error, mode string) Context { + return Context{ Client: MockClient{err: err}, BroadcastMode: mode, } diff --git a/client/context/context.go b/client/context.go similarity index 72% rename from client/context/context.go rename to client/context.go index 6ea912c84359..88a96014b83e 100644 --- a/client/context/context.go +++ b/client/context.go @@ -1,4 +1,4 @@ -package context +package client import ( "bufio" @@ -21,9 +21,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// CLIContext implements a typical CLI context created in SDK modules for +// Context implements a typical context created in SDK modules for // transaction handling and queries. -type CLIContext struct { +type Context struct { FromAddress sdk.AccAddress Client rpcclient.Client ChainID string @@ -53,40 +53,40 @@ type CLIContext struct { Codec *codec.Codec } -// NewCLIContextWithInputAndFrom returns a new initialized CLIContext with parameters from the +// NewContextWithInputAndFrom returns a new initialized Context with parameters from the // command line using Viper. It takes a io.Reader and and key name or address and populates // the FromName and FromAddress field accordingly. It will also create Tendermint verifier // using the chain ID, home directory and RPC URI provided by the command line. If using -// a CLIContext in tests or any non CLI-based environment, the verifier will not be created +// a Context in tests or any non CLI-based environment, the verifier will not be created // and will be set as nil because FlagTrustNode must be set. -func NewCLIContextWithInputAndFrom(input io.Reader, from string) CLIContext { - ctx := CLIContext{} +func NewContextWithInputAndFrom(input io.Reader, from string) Context { + ctx := Context{} return ctx.InitWithInputAndFrom(input, from) } -// NewCLIContextWithFrom returns a new initialized CLIContext with parameters from the +// NewContextWithFrom returns a new initialized Context with parameters from the // command line using Viper. It takes a key name or address and populates the FromName and // FromAddress field accordingly. It will also create Tendermint verifier using // the chain ID, home directory and RPC URI provided by the command line. If using -// a CLIContext in tests or any non CLI-based environment, the verifier will not +// a Context in tests or any non CLI-based environment, the verifier will not // be created and will be set as nil because FlagTrustNode must be set. -func NewCLIContextWithFrom(from string) CLIContext { - return NewCLIContextWithInputAndFrom(os.Stdin, from) +func NewContextWithFrom(from string) Context { + return NewContextWithInputAndFrom(os.Stdin, from) } -// NewCLIContext returns a new initialized CLIContext with parameters from the +// NewContext returns a new initialized Context with parameters from the // command line using Viper. -func NewCLIContext() CLIContext { return NewCLIContextWithFrom(viper.GetString(flags.FlagFrom)) } +func NewContext() Context { return NewContextWithFrom(viper.GetString(flags.FlagFrom)) } -// NewCLIContextWithInput returns a new initialized CLIContext with a io.Reader and parameters +// NewContextWithInput returns a new initialized Context with a io.Reader and parameters // from the command line using Viper. -func NewCLIContextWithInput(input io.Reader) CLIContext { - return NewCLIContextWithInputAndFrom(input, viper.GetString(flags.FlagFrom)) +func NewContextWithInput(input io.Reader) Context { + return NewContextWithInputAndFrom(input, viper.GetString(flags.FlagFrom)) } -// InitWithInputAndFrom returns a new CLIContext re-initialized from an existing -// CLIContext with a new io.Reader and from parameter -func (ctx CLIContext) InitWithInputAndFrom(input io.Reader, from string) CLIContext { +// InitWithInputAndFrom returns a new Context re-initialized from an existing +// Context with a new io.Reader and from parameter +func (ctx Context) InitWithInputAndFrom(input io.Reader, from string) Context { input = bufio.NewReader(input) var ( @@ -165,67 +165,67 @@ func (ctx CLIContext) InitWithInputAndFrom(input io.Reader, from string) CLICont return ctx } -// InitWithFrom returns a new CLIContext re-initialized from an existing -// CLIContext with a new from parameter -func (ctx CLIContext) InitWithFrom(from string) CLIContext { +// InitWithFrom returns a new Context re-initialized from an existing +// Context with a new from parameter +func (ctx Context) InitWithFrom(from string) Context { return ctx.InitWithInputAndFrom(os.Stdin, from) } -// Init returns a new CLIContext re-initialized from an existing -// CLIContext with parameters from the command line using Viper. -func (ctx CLIContext) Init() CLIContext { return ctx.InitWithFrom(viper.GetString(flags.FlagFrom)) } +// Init returns a new Context re-initialized from an existing +// Context with parameters from the command line using Viper. +func (ctx Context) Init() Context { return ctx.InitWithFrom(viper.GetString(flags.FlagFrom)) } -// InitWithInput returns a new CLIContext re-initialized from an existing -// CLIContext with a new io.Reader and from parameter -func (ctx CLIContext) InitWithInput(input io.Reader) CLIContext { +// InitWithInput returns a new Context re-initialized from an existing +// Context with a new io.Reader and from parameter +func (ctx Context) InitWithInput(input io.Reader) Context { return ctx.InitWithInputAndFrom(input, viper.GetString(flags.FlagFrom)) } // WithKeyring returns a copy of the context with an updated keyring. -func (ctx CLIContext) WithKeyring(k keyring.Keyring) CLIContext { +func (ctx Context) WithKeyring(k keyring.Keyring) Context { ctx.Keyring = k return ctx } // WithInput returns a copy of the context with an updated input. -func (ctx CLIContext) WithInput(r io.Reader) CLIContext { +func (ctx Context) WithInput(r io.Reader) Context { ctx.Input = r return ctx } -// WithJSONMarshaler returns a copy of the CLIContext with an updated JSONMarshaler. -func (ctx CLIContext) WithJSONMarshaler(m codec.JSONMarshaler) CLIContext { +// WithJSONMarshaler returns a copy of the Context with an updated JSONMarshaler. +func (ctx Context) WithJSONMarshaler(m codec.JSONMarshaler) Context { ctx.JSONMarshaler = m return ctx } // WithCodec returns a copy of the context with an updated codec. // TODO: Deprecated (remove). -func (ctx CLIContext) WithCodec(cdc *codec.Codec) CLIContext { +func (ctx Context) WithCodec(cdc *codec.Codec) Context { ctx.Codec = cdc return ctx } // WithOutput returns a copy of the context with an updated output writer (e.g. stdout). -func (ctx CLIContext) WithOutput(w io.Writer) CLIContext { +func (ctx Context) WithOutput(w io.Writer) Context { ctx.Output = w return ctx } // WithFrom returns a copy of the context with an updated from address or name. -func (ctx CLIContext) WithFrom(from string) CLIContext { +func (ctx Context) WithFrom(from string) Context { ctx.From = from return ctx } // WithTrustNode returns a copy of the context with an updated TrustNode flag. -func (ctx CLIContext) WithTrustNode(trustNode bool) CLIContext { +func (ctx Context) WithTrustNode(trustNode bool) Context { ctx.TrustNode = trustNode return ctx } // WithNodeURI returns a copy of the context with an updated node URI. -func (ctx CLIContext) WithNodeURI(nodeURI string) CLIContext { +func (ctx Context) WithNodeURI(nodeURI string) Context { ctx.NodeURI = nodeURI client, err := rpchttp.New(nodeURI, "/websocket") if err != nil { @@ -237,76 +237,76 @@ func (ctx CLIContext) WithNodeURI(nodeURI string) CLIContext { } // WithHeight returns a copy of the context with an updated height. -func (ctx CLIContext) WithHeight(height int64) CLIContext { +func (ctx Context) WithHeight(height int64) Context { ctx.Height = height return ctx } // WithClient returns a copy of the context with an updated RPC client // instance. -func (ctx CLIContext) WithClient(client rpcclient.Client) CLIContext { +func (ctx Context) WithClient(client rpcclient.Client) Context { ctx.Client = client return ctx } // WithUseLedger returns a copy of the context with an updated UseLedger flag. -func (ctx CLIContext) WithUseLedger(useLedger bool) CLIContext { +func (ctx Context) WithUseLedger(useLedger bool) Context { ctx.UseLedger = useLedger return ctx } // WithVerifier returns a copy of the context with an updated Verifier. -func (ctx CLIContext) WithVerifier(verifier tmlite.Verifier) CLIContext { +func (ctx Context) WithVerifier(verifier tmlite.Verifier) Context { ctx.Verifier = verifier return ctx } // WithChainID returns a copy of the context with an updated chain ID. -func (ctx CLIContext) WithChainID(chainID string) CLIContext { +func (ctx Context) WithChainID(chainID string) Context { ctx.ChainID = chainID return ctx } // WithGenerateOnly returns a copy of the context with updated GenerateOnly value -func (ctx CLIContext) WithGenerateOnly(generateOnly bool) CLIContext { +func (ctx Context) WithGenerateOnly(generateOnly bool) Context { ctx.GenerateOnly = generateOnly return ctx } // WithSimulation returns a copy of the context with updated Simulate value -func (ctx CLIContext) WithSimulation(simulate bool) CLIContext { +func (ctx Context) WithSimulation(simulate bool) Context { ctx.Simulate = simulate return ctx } // WithFromName returns a copy of the context with an updated from account name. -func (ctx CLIContext) WithFromName(name string) CLIContext { +func (ctx Context) WithFromName(name string) Context { ctx.FromName = name return ctx } // WithFromAddress returns a copy of the context with an updated from account // address. -func (ctx CLIContext) WithFromAddress(addr sdk.AccAddress) CLIContext { +func (ctx Context) WithFromAddress(addr sdk.AccAddress) Context { ctx.FromAddress = addr return ctx } // WithBroadcastMode returns a copy of the context with an updated broadcast // mode. -func (ctx CLIContext) WithBroadcastMode(mode string) CLIContext { +func (ctx Context) WithBroadcastMode(mode string) Context { ctx.BroadcastMode = mode return ctx } // WithTxGenerator returns the context with an updated TxGenerator -func (ctx CLIContext) WithTxGenerator(generator TxGenerator) CLIContext { +func (ctx Context) WithTxGenerator(generator TxGenerator) Context { ctx.TxGenerator = generator return ctx } // WithAccountRetriever returns the context with an updated AccountRetriever -func (ctx CLIContext) WithAccountRetriever(retriever AccountRetriever) CLIContext { +func (ctx Context) WithAccountRetriever(retriever AccountRetriever) Context { ctx.AccountRetriever = retriever return ctx } @@ -314,7 +314,7 @@ func (ctx CLIContext) WithAccountRetriever(retriever AccountRetriever) CLIContex // Println outputs toPrint to the ctx.Output based on ctx.OutputFormat which is // either text or json. If text, toPrint will be YAML encoded. Otherwise, toPrint // will be JSON encoded using ctx.JSONMarshaler. An error is returned upon failure. -func (ctx CLIContext) Println(toPrint interface{}) error { +func (ctx Context) Println(toPrint interface{}) error { var ( out []byte err error @@ -349,7 +349,7 @@ func (ctx CLIContext) Println(toPrint interface{}) error { // // TODO: Remove once client-side Protobuf migration has been completed. // ref: https://github.com/cosmos/cosmos-sdk/issues/5864 -func (ctx CLIContext) PrintOutput(toPrint interface{}) error { +func (ctx Context) PrintOutput(toPrint interface{}) error { var ( out []byte err error diff --git a/client/context/context_test.go b/client/context_test.go similarity index 79% rename from client/context/context_test.go rename to client/context_test.go index 626e430e0c63..fee6d55873ec 100644 --- a/client/context/context_test.go +++ b/client/context_test.go @@ -1,4 +1,4 @@ -package context_test +package client_test import ( "os" @@ -10,20 +10,20 @@ import ( "github.com/spf13/viper" "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" ) -func TestCLIContext_WithOffline(t *testing.T) { +func TestContext_WithOffline(t *testing.T) { viper.Set(flags.FlagOffline, true) viper.Set(flags.FlagNode, "tcp://localhost:26657") - ctx := context.NewCLIContext() + ctx := client.NewContext() require.True(t, ctx.Offline) require.Nil(t, ctx.Client) } -func TestCLIContext_WithGenOnly(t *testing.T) { +func TestContext_WithGenOnly(t *testing.T) { viper.Set(flags.FlagGenerateOnly, true) validFromAddr := "cosmos1q7380u26f7ntke3facjmynajs4umlr329vr4ja" @@ -53,7 +53,7 @@ func TestCLIContext_WithGenOnly(t *testing.T) { for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { - ctx := context.NewCLIContextWithFrom(tt.from) + ctx := client.NewContextWithFrom(tt.from) require.Equal(t, tt.expectedFromAddr, ctx.FromAddress) require.Equal(t, tt.expectedFromName, ctx.FromName) @@ -61,9 +61,9 @@ func TestCLIContext_WithGenOnly(t *testing.T) { } } -func TestCLIContext_WithKeyring(t *testing.T) { +func TestContext_WithKeyring(t *testing.T) { viper.Set(flags.FlagGenerateOnly, true) - ctx := context.NewCLIContextWithFrom("cosmos1q7380u26f7ntke3facjmynajs4umlr329vr4ja") + ctx := client.NewContextWithFrom("cosmos1q7380u26f7ntke3facjmynajs4umlr329vr4ja") require.NotNil(t, ctx.Keyring) kr := ctx.Keyring ctx = ctx.WithKeyring(nil) diff --git a/client/context/errors.go b/client/errors.go similarity index 98% rename from client/context/errors.go rename to client/errors.go index 2c83c375dd53..d7f7e29664c9 100644 --- a/client/context/errors.go +++ b/client/errors.go @@ -1,4 +1,4 @@ -package context +package client import ( "fmt" diff --git a/client/lcd/root.go b/client/lcd/root.go index 71227f9f9bf6..e2784f06e4b7 100644 --- a/client/lcd/root.go +++ b/client/lcd/root.go @@ -15,7 +15,7 @@ import ( "github.com/tendermint/tendermint/libs/log" tmrpcserver "github.com/tendermint/tendermint/rpc/jsonrpc/server" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server" @@ -26,8 +26,8 @@ import ( // RestServer represents the Light Client Rest server type RestServer struct { - Mux *mux.Router - CliCtx context.CLIContext + Mux *mux.Router + ClientCtx client.Context log log.Logger listener net.Listener @@ -36,13 +36,13 @@ type RestServer struct { // NewRestServer creates a new rest server instance func NewRestServer(cdc *codec.Codec) *RestServer { r := mux.NewRouter() - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)).With("module", "rest-server") return &RestServer{ - Mux: r, - CliCtx: cliCtx, - log: logger, + Mux: r, + ClientCtx: clientCtx, + log: logger, } } diff --git a/client/context/query.go b/client/query.go similarity index 84% rename from client/context/query.go rename to client/query.go index 447ee24aae8b..674cae599ab8 100644 --- a/client/context/query.go +++ b/client/query.go @@ -1,4 +1,4 @@ -package context +package client import ( "fmt" @@ -20,7 +20,7 @@ import ( // GetNode returns an RPC client. If the context's client is not defined, an // error is returned. -func (ctx CLIContext) GetNode() (rpcclient.Client, error) { +func (ctx Context) GetNode() (rpcclient.Client, error) { if ctx.Client == nil { return nil, errors.New("no RPC client is defined in offline mode") } @@ -31,34 +31,34 @@ func (ctx CLIContext) GetNode() (rpcclient.Client, error) { // Query performs a query to a Tendermint node with the provided path. // It returns the result and height of the query upon success or an error if // the query fails. -func (ctx CLIContext) Query(path string) ([]byte, int64, error) { +func (ctx Context) Query(path string) ([]byte, int64, error) { return ctx.query(path, nil) } // QueryWithData performs a query to a Tendermint node with the provided path // and a data payload. It returns the result and height of the query upon success // or an error if the query fails. -func (ctx CLIContext) QueryWithData(path string, data []byte) ([]byte, int64, error) { +func (ctx Context) QueryWithData(path string, data []byte) ([]byte, int64, error) { return ctx.query(path, data) } // QueryStore performs a query to a Tendermint node with the provided key and // store name. It returns the result and height of the query upon success // or an error if the query fails. -func (ctx CLIContext) QueryStore(key tmbytes.HexBytes, storeName string) ([]byte, int64, error) { +func (ctx Context) QueryStore(key tmbytes.HexBytes, storeName string) ([]byte, int64, error) { return ctx.queryStore(key, storeName, "key") } // QueryABCI performs a query to a Tendermint node with the provide RequestQuery. // It returns the ResultQuery obtained from the query. -func (ctx CLIContext) QueryABCI(req abci.RequestQuery) (abci.ResponseQuery, error) { +func (ctx Context) QueryABCI(req abci.RequestQuery) (abci.ResponseQuery, error) { return ctx.queryABCI(req) } // QuerySubspace performs a query to a Tendermint node with the provided // store name and subspace. It returns key value pair and height of the query // upon success or an error if the query fails. -func (ctx CLIContext) QuerySubspace(subspace []byte, storeName string) (res []sdk.KVPair, height int64, err error) { +func (ctx Context) QuerySubspace(subspace []byte, storeName string) (res []sdk.KVPair, height int64, err error) { resRaw, height, err := ctx.queryStore(subspace, storeName, "subspace") if err != nil { return res, height, err @@ -69,16 +69,16 @@ func (ctx CLIContext) QuerySubspace(subspace []byte, storeName string) (res []sd } // GetFromAddress returns the from address from the context's name. -func (ctx CLIContext) GetFromAddress() sdk.AccAddress { +func (ctx Context) GetFromAddress() sdk.AccAddress { return ctx.FromAddress } // GetFromName returns the key name for the current context. -func (ctx CLIContext) GetFromName() string { +func (ctx Context) GetFromName() string { return ctx.FromName } -func (ctx CLIContext) queryABCI(req abci.RequestQuery) (abci.ResponseQuery, error) { +func (ctx Context) queryABCI(req abci.RequestQuery) (abci.ResponseQuery, error) { node, err := ctx.GetNode() if err != nil { return abci.ResponseQuery{}, err @@ -115,7 +115,7 @@ func (ctx CLIContext) queryABCI(req abci.RequestQuery) (abci.ResponseQuery, erro // or an error if the query fails. In addition, it will verify the returned // proof if TrustNode is disabled. If proof verification fails or the query // height is invalid, an error will be returned. -func (ctx CLIContext) query(path string, key tmbytes.HexBytes) ([]byte, int64, error) { +func (ctx Context) query(path string, key tmbytes.HexBytes) ([]byte, int64, error) { resp, err := ctx.queryABCI(abci.RequestQuery{ Path: path, Data: key, @@ -128,7 +128,7 @@ func (ctx CLIContext) query(path string, key tmbytes.HexBytes) ([]byte, int64, e } // Verify verifies the consensus proof at given height. -func (ctx CLIContext) Verify(height int64) (tmtypes.SignedHeader, error) { +func (ctx Context) Verify(height int64) (tmtypes.SignedHeader, error) { if ctx.Verifier == nil { return tmtypes.SignedHeader{}, fmt.Errorf("missing valid certifier to verify data from distrusted node") } @@ -146,7 +146,7 @@ func (ctx CLIContext) Verify(height int64) (tmtypes.SignedHeader, error) { } // verifyProof perform response proof verification. -func (ctx CLIContext) verifyProof(queryPath string, resp abci.ResponseQuery) error { +func (ctx Context) verifyProof(queryPath string, resp abci.ResponseQuery) error { if ctx.Verifier == nil { return fmt.Errorf("missing valid certifier to verify data from distrusted node") } @@ -157,7 +157,7 @@ func (ctx CLIContext) verifyProof(queryPath string, resp abci.ResponseQuery) err return err } - // TODO: Instead of reconstructing, stash on CLIContext field? + // TODO: Instead of reconstructing, stash on Context field? prt := rootmulti.DefaultProofRuntime() // TODO: Better convention for path? @@ -188,7 +188,7 @@ func (ctx CLIContext) verifyProof(queryPath string, resp abci.ResponseQuery) err // queryStore performs a query to a Tendermint node with the provided a store // name and path. It returns the result and height of the query upon success // or an error if the query fails. -func (ctx CLIContext) queryStore(key tmbytes.HexBytes, storeName, endPath string) ([]byte, int64, error) { +func (ctx Context) queryStore(key tmbytes.HexBytes, storeName, endPath string) ([]byte, int64, error) { path := fmt.Sprintf("/store/%s/%s", storeName, endPath) return ctx.query(path, key) } diff --git a/client/routes.go b/client/routes.go deleted file mode 100644 index 9eac8fa0d828..000000000000 --- a/client/routes.go +++ /dev/null @@ -1,13 +0,0 @@ -package client - -import ( - "github.com/gorilla/mux" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/client/rpc" -) - -// Register routes -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { - rpc.RegisterRPCRoutes(cliCtx, r) -} diff --git a/client/rpc/block.go b/client/rpc/block.go index 6e930b641c01..766a41fea953 100644 --- a/client/rpc/block.go +++ b/client/rpc/block.go @@ -9,7 +9,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types/rest" @@ -34,9 +34,9 @@ func BlockCommand() *cobra.Command { return cmd } -func getBlock(cliCtx context.CLIContext, height *int64) ([]byte, error) { +func getBlock(clientCtx client.Context, height *int64) ([]byte, error) { // get the node - node, err := cliCtx.GetNode() + node, err := clientCtx.GetNode() if err != nil { return nil, err } @@ -49,8 +49,8 @@ func getBlock(cliCtx context.CLIContext, height *int64) ([]byte, error) { return nil, err } - if !cliCtx.TrustNode { - check, err := cliCtx.Verify(res.Block.Height) + if !clientCtx.TrustNode { + check, err := clientCtx.Verify(res.Block.Height) if err != nil { return nil, err } @@ -64,7 +64,7 @@ func getBlock(cliCtx context.CLIContext, height *int64) ([]byte, error) { } } - if cliCtx.Indent { + if clientCtx.Indent { return codec.Cdc.MarshalJSONIndent(res, "", " ") } @@ -72,8 +72,8 @@ func getBlock(cliCtx context.CLIContext, height *int64) ([]byte, error) { } // get the current blockchain height -func GetChainHeight(cliCtx context.CLIContext) (int64, error) { - node, err := cliCtx.GetNode() +func GetChainHeight(clientCtx client.Context) (int64, error) { + node, err := clientCtx.GetNode() if err != nil { return -1, err } @@ -103,7 +103,7 @@ func printBlock(cmd *cobra.Command, args []string) error { } } - output, err := getBlock(context.NewCLIContext(), height) + output, err := getBlock(client.NewContext(), height) if err != nil { return err } @@ -115,7 +115,7 @@ func printBlock(cmd *cobra.Command, args []string) error { // REST // REST handler to get a block -func BlockRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func BlockRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) @@ -126,7 +126,7 @@ func BlockRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - chainHeight, err := GetChainHeight(cliCtx) + chainHeight, err := GetChainHeight(clientCtx) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, "failed to parse chain height") return @@ -137,23 +137,23 @@ func BlockRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - output, err := getBlock(cliCtx, &height) + output, err := getBlock(clientCtx, &height) if rest.CheckInternalServerError(w, err) { return } - rest.PostProcessResponseBare(w, cliCtx, output) + rest.PostProcessResponseBare(w, clientCtx, output) } } // REST handler to get the latest block -func LatestBlockRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func LatestBlockRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - output, err := getBlock(cliCtx, nil) + output, err := getBlock(clientCtx, nil) if rest.CheckInternalServerError(w, err) { return } - rest.PostProcessResponseBare(w, cliCtx, output) + rest.PostProcessResponseBare(w, clientCtx, output) } } diff --git a/client/rpc/root.go b/client/rpc/root.go deleted file mode 100644 index d614253e0f58..000000000000 --- a/client/rpc/root.go +++ /dev/null @@ -1,17 +0,0 @@ -package rpc - -import ( - "github.com/gorilla/mux" - - "github.com/cosmos/cosmos-sdk/client/context" -) - -// Register REST endpoints -func RegisterRPCRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/node_info", NodeInfoRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/syncing", NodeSyncingRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/blocks/latest", LatestBlockRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/blocks/{height}", BlockRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/validatorsets/latest", LatestValidatorSetRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/validatorsets/{height}", ValidatorSetRequestHandlerFn(cliCtx)).Methods("GET") -} diff --git a/client/rpc/routes.go b/client/rpc/routes.go new file mode 100644 index 000000000000..7934ece7c92b --- /dev/null +++ b/client/rpc/routes.go @@ -0,0 +1,17 @@ +package rpc + +import ( + "github.com/gorilla/mux" + + "github.com/cosmos/cosmos-sdk/client" +) + +// Register REST endpoints. +func RegisterRoutes(clientCtx client.Context, r *mux.Router) { + r.HandleFunc("/node_info", NodeInfoRequestHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc("/syncing", NodeSyncingRequestHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc("/blocks/latest", LatestBlockRequestHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc("/blocks/{height}", BlockRequestHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc("/validatorsets/latest", LatestValidatorSetRequestHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc("/validatorsets/{height}", ValidatorSetRequestHandlerFn(clientCtx)).Methods("GET") +} diff --git a/client/rpc/status.go b/client/rpc/status.go index 5987930b7779..e8215006a19e 100644 --- a/client/rpc/status.go +++ b/client/rpc/status.go @@ -9,7 +9,7 @@ import ( ctypes "github.com/tendermint/tendermint/rpc/core/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types/rest" @@ -32,8 +32,8 @@ func StatusCommand() *cobra.Command { return cmd } -func getNodeStatus(cliCtx context.CLIContext) (*ctypes.ResultStatus, error) { - node, err := cliCtx.GetNode() +func getNodeStatus(clientCtx client.Context) (*ctypes.ResultStatus, error) { + node, err := clientCtx.GetNode() if err != nil { return &ctypes.ResultStatus{}, err } @@ -47,14 +47,14 @@ func printNodeStatus(_ *cobra.Command, _ []string) error { // No need to verify proof in getting node status viper.Set(flags.FlagKeyringBackend, flags.DefaultKeyringBackend) - cliCtx := context.NewCLIContext() - status, err := getNodeStatus(cliCtx) + clientCtx := client.NewContext() + status, err := getNodeStatus(clientCtx) if err != nil { return err } var output []byte - if cliCtx.Indent { + if clientCtx.Indent { output, err = codec.Cdc.MarshalJSONIndent(status, "", " ") } else { output, err = codec.Cdc.MarshalJSON(status) @@ -76,9 +76,9 @@ type NodeInfoResponse struct { } // REST handler for node info -func NodeInfoRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func NodeInfoRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - status, err := getNodeStatus(cliCtx) + status, err := getNodeStatus(clientCtx) if rest.CheckInternalServerError(w, err) { return } @@ -87,7 +87,7 @@ func NodeInfoRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { DefaultNodeInfo: status.NodeInfo, ApplicationVersion: version.NewInfo(), } - rest.PostProcessResponseBare(w, cliCtx, resp) + rest.PostProcessResponseBare(w, clientCtx, resp) } } @@ -97,13 +97,13 @@ type SyncingResponse struct { } // REST handler for node syncing -func NodeSyncingRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func NodeSyncingRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - status, err := getNodeStatus(cliCtx) + status, err := getNodeStatus(clientCtx) if rest.CheckInternalServerError(w, err) { return } - rest.PostProcessResponseBare(w, cliCtx, SyncingResponse{Syncing: status.SyncInfo.CatchingUp}) + rest.PostProcessResponseBare(w, clientCtx, SyncingResponse{Syncing: status.SyncInfo.CatchingUp}) } } diff --git a/client/rpc/validators.go b/client/rpc/validators.go index d90583cb1da2..4e7fc8af12a5 100644 --- a/client/rpc/validators.go +++ b/client/rpc/validators.go @@ -13,7 +13,7 @@ import ( tmtypes "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -43,14 +43,14 @@ func ValidatorCommand(cdc *codec.Codec) *cobra.Command { } } - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) - result, err := GetValidators(cliCtx, height, viper.GetInt(flags.FlagPage), viper.GetInt(flags.FlagLimit)) + result, err := GetValidators(clientCtx, height, viper.GetInt(flags.FlagPage), viper.GetInt(flags.FlagLimit)) if err != nil { return err } - return cliCtx.PrintOutput(result) + return clientCtx.PrintOutput(result) }, } @@ -119,9 +119,9 @@ func bech32ValidatorOutput(validator *tmtypes.Validator) (ValidatorOutput, error } // GetValidators from client -func GetValidators(cliCtx context.CLIContext, height *int64, page, limit int) (ResultValidatorsOutput, error) { +func GetValidators(clientCtx client.Context, height *int64, page, limit int) (ResultValidatorsOutput, error) { // get the node - node, err := cliCtx.GetNode() + node, err := clientCtx.GetNode() if err != nil { return ResultValidatorsOutput{}, err } @@ -131,8 +131,8 @@ func GetValidators(cliCtx context.CLIContext, height *int64, page, limit int) (R return ResultValidatorsOutput{}, err } - if !cliCtx.TrustNode { - check, err := cliCtx.Verify(validatorsRes.BlockHeight) + if !clientCtx.TrustNode { + check, err := clientCtx.Verify(validatorsRes.BlockHeight) if err != nil { return ResultValidatorsOutput{}, err } @@ -160,7 +160,7 @@ func GetValidators(cliCtx context.CLIContext, height *int64, page, limit int) (R // REST // Validator Set at a height REST handler -func ValidatorSetRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func ValidatorSetRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { _, page, limit, err := rest.ParseHTTPArgsWithLimit(r, 100) if err != nil { @@ -175,7 +175,7 @@ func ValidatorSetRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - chainHeight, err := GetChainHeight(cliCtx) + chainHeight, err := GetChainHeight(clientCtx) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, "failed to parse chain height") return @@ -185,16 +185,16 @@ func ValidatorSetRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - output, err := GetValidators(cliCtx, &height, page, limit) + output, err := GetValidators(clientCtx, &height, page, limit) if rest.CheckInternalServerError(w, err) { return } - rest.PostProcessResponse(w, cliCtx, output) + rest.PostProcessResponse(w, clientCtx, output) } } // Latest Validator Set REST handler -func LatestValidatorSetRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func LatestValidatorSetRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { _, page, limit, err := rest.ParseHTTPArgsWithLimit(r, 100) if err != nil { @@ -202,11 +202,11 @@ func LatestValidatorSetRequestHandlerFn(cliCtx context.CLIContext) http.HandlerF return } - output, err := GetValidators(cliCtx, nil, page, limit) + output, err := GetValidators(clientCtx, nil, page, limit) if rest.CheckInternalServerError(w, err) { return } - rest.PostProcessResponse(w, cliCtx, output) + rest.PostProcessResponse(w, clientCtx, output) } } diff --git a/client/tx/factory.go b/client/tx/factory.go index dc1b2c6dfcb6..33508acbfa47 100644 --- a/client/tx/factory.go +++ b/client/tx/factory.go @@ -5,7 +5,7 @@ import ( "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" @@ -15,8 +15,8 @@ import ( // signing an application-specific transaction. type Factory struct { keybase keyring.Keyring - txGenerator context.TxGenerator - accountRetriever context.AccountRetriever + txGenerator client.TxGenerator + accountRetriever client.AccountRetriever accountNumber uint64 sequence uint64 gas uint64 @@ -56,29 +56,29 @@ func NewFactoryFromCLI(input io.Reader) Factory { return f } -func (f Factory) AccountNumber() uint64 { return f.accountNumber } -func (f Factory) Sequence() uint64 { return f.sequence } -func (f Factory) Gas() uint64 { return f.gas } -func (f Factory) GasAdjustment() float64 { return f.gasAdjustment } -func (f Factory) Keybase() keyring.Keyring { return f.keybase } -func (f Factory) ChainID() string { return f.chainID } -func (f Factory) Memo() string { return f.memo } -func (f Factory) Fees() sdk.Coins { return f.fees } -func (f Factory) GasPrices() sdk.DecCoins { return f.gasPrices } -func (f Factory) AccountRetriever() context.AccountRetriever { return f.accountRetriever } +func (f Factory) AccountNumber() uint64 { return f.accountNumber } +func (f Factory) Sequence() uint64 { return f.sequence } +func (f Factory) Gas() uint64 { return f.gas } +func (f Factory) GasAdjustment() float64 { return f.gasAdjustment } +func (f Factory) Keybase() keyring.Keyring { return f.keybase } +func (f Factory) ChainID() string { return f.chainID } +func (f Factory) Memo() string { return f.memo } +func (f Factory) Fees() sdk.Coins { return f.fees } +func (f Factory) GasPrices() sdk.DecCoins { return f.gasPrices } +func (f Factory) AccountRetriever() client.AccountRetriever { return f.accountRetriever } // SimulateAndExecute returns the option to simulate and then execute the transaction // using the gas from the simulation results func (f Factory) SimulateAndExecute() bool { return f.simulateAndExecute } // WithTxGenerator returns a copy of the Factory with an updated TxGenerator. -func (f Factory) WithTxGenerator(g context.TxGenerator) Factory { +func (f Factory) WithTxGenerator(g client.TxGenerator) Factory { f.txGenerator = g return f } // WithAccountRetriever returns a copy of the Factory with an updated AccountRetriever. -func (f Factory) WithAccountRetriever(ar context.AccountRetriever) Factory { +func (f Factory) WithAccountRetriever(ar client.AccountRetriever) Factory { f.accountRetriever = ar return f } diff --git a/client/tx/tx.go b/client/tx/tx.go index b7548cda1058..234f5e986be8 100644 --- a/client/tx/tx.go +++ b/client/tx/tx.go @@ -10,7 +10,7 @@ import ( "github.com/gogo/protobuf/jsonpb" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/input" clientkeys "github.com/cosmos/cosmos-sdk/client/keys" @@ -21,32 +21,32 @@ import ( // GenerateOrBroadcastTx will either generate and print and unsigned transaction // or sign it and broadcast it returning an error upon failure. -func GenerateOrBroadcastTx(ctx context.CLIContext, msgs ...sdk.Msg) error { - txf := NewFactoryFromCLI(ctx.Input).WithTxGenerator(ctx.TxGenerator).WithAccountRetriever(ctx.AccountRetriever) - return GenerateOrBroadcastTxWithFactory(ctx, txf, msgs...) +func GenerateOrBroadcastTx(clientCtx client.Context, msgs ...sdk.Msg) error { + txf := NewFactoryFromCLI(clientCtx.Input).WithTxGenerator(clientCtx.TxGenerator).WithAccountRetriever(clientCtx.AccountRetriever) + return GenerateOrBroadcastTxWithFactory(clientCtx, txf, msgs...) } // GenerateOrBroadcastTxWithFactory will either generate and print and unsigned transaction // or sign it and broadcast it returning an error upon failure. -func GenerateOrBroadcastTxWithFactory(ctx context.CLIContext, txf Factory, msgs ...sdk.Msg) error { - if ctx.GenerateOnly { - return GenerateTx(ctx, txf, msgs...) +func GenerateOrBroadcastTxWithFactory(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error { + if clientCtx.GenerateOnly { + return GenerateTx(clientCtx, txf, msgs...) } - return BroadcastTx(ctx, txf, msgs...) + return BroadcastTx(clientCtx, txf, msgs...) } // GenerateTx will generate an unsigned transaction and print it to the writer // specified by ctx.Output. If simulation was requested, the gas will be // simulated and also printed to the same writer before the transaction is // printed. -func GenerateTx(ctx context.CLIContext, txf Factory, msgs ...sdk.Msg) error { +func GenerateTx(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error { if txf.SimulateAndExecute() { - if ctx.Offline { + if clientCtx.Offline { return errors.New("cannot estimate gas in offline mode") } - _, adjusted, err := CalculateGas(ctx.QueryWithData, txf, msgs...) + _, adjusted, err := CalculateGas(clientCtx.QueryWithData, txf, msgs...) if err != nil { return err } @@ -60,20 +60,20 @@ func GenerateTx(ctx context.CLIContext, txf Factory, msgs ...sdk.Msg) error { return err } - return ctx.Println(tx.GetTx()) + return clientCtx.Println(tx.GetTx()) } // BroadcastTx attempts to generate, sign and broadcast a transaction with the // given set of messages. It will also simulate gas requirements if necessary. // It will return an error upon failure. -func BroadcastTx(ctx context.CLIContext, txf Factory, msgs ...sdk.Msg) error { - txf, err := PrepareFactory(ctx, txf) +func BroadcastTx(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error { + txf, err := PrepareFactory(clientCtx, txf) if err != nil { return err } - if txf.SimulateAndExecute() || ctx.Simulate { - _, adjusted, err := CalculateGas(ctx.QueryWithData, txf, msgs...) + if txf.SimulateAndExecute() || clientCtx.Simulate { + _, adjusted, err := CalculateGas(clientCtx.QueryWithData, txf, msgs...) if err != nil { return err } @@ -82,7 +82,7 @@ func BroadcastTx(ctx context.CLIContext, txf Factory, msgs ...sdk.Msg) error { _, _ = fmt.Fprintf(os.Stderr, "%s\n", GasEstimateResponse{GasEstimate: txf.Gas()}) } - if ctx.Simulate { + if clientCtx.Simulate { return nil } @@ -91,8 +91,8 @@ func BroadcastTx(ctx context.CLIContext, txf Factory, msgs ...sdk.Msg) error { return err } - if !ctx.SkipConfirm { - out, err := ctx.JSONMarshaler.MarshalJSON(tx) + if !clientCtx.SkipConfirm { + out, err := clientCtx.JSONMarshaler.MarshalJSON(tx) if err != nil { return err } @@ -108,25 +108,25 @@ func BroadcastTx(ctx context.CLIContext, txf Factory, msgs ...sdk.Msg) error { } } - txBytes, err := Sign(txf, ctx.GetFromName(), clientkeys.DefaultKeyPass, tx) + txBytes, err := Sign(txf, clientCtx.GetFromName(), clientkeys.DefaultKeyPass, tx) if err != nil { return err } // broadcast to a Tendermint node - res, err := ctx.BroadcastTx(txBytes) + res, err := clientCtx.BroadcastTx(txBytes) if err != nil { return err } - return ctx.Println(res) + return clientCtx.Println(res) } // WriteGeneratedTxResponse writes a generated unsigned transaction to the // provided http.ResponseWriter. It will simulate gas costs if requested by the // BaseReq. Upon any error, the error will be written to the http.ResponseWriter. func WriteGeneratedTxResponse( - ctx context.CLIContext, w http.ResponseWriter, br rest.BaseReq, msgs ...sdk.Msg, + ctx client.Context, w http.ResponseWriter, br rest.BaseReq, msgs ...sdk.Msg, ) { gasAdj, ok := rest.ParseFloat64OrReturnBadRequest(w, br.GasAdjustment, flags.DefaultGasAdjustment) if !ok { @@ -185,7 +185,7 @@ func WriteGeneratedTxResponse( // BuildUnsignedTx builds a transaction to be signed given a set of messages. The // transaction is initially created via the provided factory's generator. Once // created, the fee, memo, and messages are set. -func BuildUnsignedTx(txf Factory, msgs ...sdk.Msg) (context.TxBuilder, error) { +func BuildUnsignedTx(txf Factory, msgs ...sdk.Msg) (client.TxBuilder, error) { if txf.chainID == "" { return nil, fmt.Errorf("chain ID required but not specified") } @@ -278,16 +278,16 @@ func CalculateGas( // if the account number and/or the account sequence number are zero (not set), // they will be queried for and set on the provided Factory. A new Factory with // the updated fields will be returned. -func PrepareFactory(ctx context.CLIContext, txf Factory) (Factory, error) { - from := ctx.GetFromAddress() +func PrepareFactory(clientCtx client.Context, txf Factory) (Factory, error) { + from := clientCtx.GetFromAddress() - if err := txf.accountRetriever.EnsureExists(ctx, from); err != nil { + if err := txf.accountRetriever.EnsureExists(clientCtx, from); err != nil { return txf, err } initNum, initSeq := txf.accountNumber, txf.sequence if initNum == 0 || initSeq == 0 { - num, seq, err := txf.accountRetriever.GetAccountNumberSequence(ctx, from) + num, seq, err := txf.accountRetriever.GetAccountNumberSequence(clientCtx, from) if err != nil { return txf, err } @@ -312,7 +312,7 @@ func PrepareFactory(ctx context.CLIContext, txf Factory) (Factory, error) { // // Note, It is assumed the Factory has the necessary fields set that are required // by the CanonicalSignBytes call. -func Sign(txf Factory, name, passphrase string, tx context.TxBuilder) ([]byte, error) { +func Sign(txf Factory, name, passphrase string, tx client.TxBuilder) ([]byte, error) { if txf.keybase == nil { return nil, errors.New("keybase must be set prior to signing a transaction") } diff --git a/client/tx/tx_test.go b/client/tx/tx_test.go index 85f6973679ef..f12916de569c 100644 --- a/client/tx/tx_test.go +++ b/client/tx/tx_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp" @@ -15,7 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank" ) -func NewTestTxGenerator() context.TxGenerator { +func NewTestTxGenerator() client.TxGenerator { _, cdc := simapp.MakeCodecs() return types.StdTxGenerator{Cdc: cdc} } diff --git a/client/context/tx_generator.go b/client/tx_generator.go similarity index 85% rename from client/context/tx_generator.go rename to client/tx_generator.go index ff023fcec06f..f840bd39e922 100644 --- a/client/context/tx_generator.go +++ b/client/tx_generator.go @@ -1,4 +1,4 @@ -package context +package client import ( "github.com/tendermint/tendermint/crypto" @@ -12,18 +12,18 @@ type ( // implement TxBuilder. TxGenerator interface { NewTx() TxBuilder - NewFee() ClientFee - NewSignature() ClientSignature + NewFee() Fee + NewSignature() Signature MarshalTx(tx types.Tx) ([]byte, error) } - ClientFee interface { + Fee interface { types.Fee SetGas(uint64) SetAmount(types.Coins) } - ClientSignature interface { + Signature interface { types.Signature SetPubKey(crypto.PubKey) error SetSignature([]byte) @@ -38,9 +38,9 @@ type ( SetMsgs(...types.Msg) error GetSignatures() []types.Signature - SetSignatures(...ClientSignature) error + SetSignatures(...Signature) error GetFee() types.Fee - SetFee(ClientFee) error + SetFee(Fee) error GetMemo() string SetMemo(string) diff --git a/client/context/verifier.go b/client/verifier.go similarity index 75% rename from client/context/verifier.go rename to client/verifier.go index b849d3e397d1..063808075448 100644 --- a/client/context/verifier.go +++ b/client/verifier.go @@ -1,4 +1,4 @@ -package context +package client import ( "path/filepath" @@ -17,12 +17,12 @@ const ( DefaultVerifierCacheSize = 10 ) -// CreateVerifier returns a Tendermint verifier from a CLIContext object and -// cache size. An error is returned if the CLIContext is missing required values -// or if the verifier could not be created. A CLIContext must at the very least -// have the chain ID and home directory set. If the CLIContext has TrustNode +// CreateVerifier returns a Tendermint verifier from a Context object and +// cache size. An error is returned if the Context is missing required values +// or if the verifier could not be created. A Context must at the very least +// have the chain ID and home directory set. If the Context has TrustNode // enabled, no verifier will be created. -func CreateVerifier(ctx CLIContext, cacheSize int) (tmlite.Verifier, error) { +func CreateVerifier(ctx Context, cacheSize int) (tmlite.Verifier, error) { if ctx.TrustNode { return nil, nil } diff --git a/client/context/verifier_test.go b/client/verifier_test.go similarity index 53% rename from client/context/verifier_test.go rename to client/verifier_test.go index bd2539492349..029577f48773 100644 --- a/client/context/verifier_test.go +++ b/client/verifier_test.go @@ -1,4 +1,4 @@ -package context_test +package client_test import ( "io/ioutil" @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" ) func TestCreateVerifier(t *testing.T) { @@ -15,18 +15,18 @@ func TestCreateVerifier(t *testing.T) { testCases := []struct { name string - ctx context.CLIContext + ctx client.Context expectErr bool }{ - {"no chain ID", context.CLIContext{}, true}, - {"no home directory", context.CLIContext{}.WithChainID("test"), true}, - {"no client or RPC URI", context.CLIContext{HomeDir: tmpDir}.WithChainID("test"), true}, + {"no chain ID", client.Context{}, true}, + {"no home directory", client.Context{}.WithChainID("test"), true}, + {"no client or RPC URI", client.Context{HomeDir: tmpDir}.WithChainID("test"), true}, } for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { - verifier, err := context.CreateVerifier(tc.ctx, context.DefaultVerifierCacheSize) + verifier, err := client.CreateVerifier(tc.ctx, client.DefaultVerifierCacheSize) require.Equal(t, tc.expectErr, err != nil, err) if !tc.expectErr { diff --git a/docs/architecture/adr-013-metrics.md b/docs/architecture/adr-013-metrics.md index 78c8ada17e52..ad49bbb9cfc1 100644 --- a/docs/architecture/adr-013-metrics.md +++ b/docs/architecture/adr-013-metrics.md @@ -25,7 +25,7 @@ type AppModuleBasic interface { ValidateGenesis(json.RawMessage) error // client functionality - RegisterRESTRoutes(context.CLIContext, *mux.Router) + RegisterRESTRoutes(client.Context, *mux.Router) GetTxCmd(*codec.Codec) *cobra.Command GetQueryCmd(*codec.Codec) *cobra.Command } diff --git a/docs/architecture/adr-020-protobuf-transaction-encoding.md b/docs/architecture/adr-020-protobuf-transaction-encoding.md index 811f557039de..1b68e728aab5 100644 --- a/docs/architecture/adr-020-protobuf-transaction-encoding.md +++ b/docs/architecture/adr-020-protobuf-transaction-encoding.md @@ -323,25 +323,25 @@ type TxBuilder interface { } ``` -We then update `CLIContext` to have new fields: `JSONMarshaler`, `TxGenerator`, +We then update `Context` to have new fields: `JSONMarshaler`, `TxGenerator`, and `AccountRetriever`, and we update `AppModuleBasic.GetTxCmd` to take -a `CLIContext` which should have all of these fields pre-populated. +a `Context` which should have all of these fields pre-populated. Each client method should then use one of the `Init` methods to re-initialize -the pre-populated `CLIContext`. `tx.GenerateOrBroadcastTx` can be used to +the pre-populated `Context`. `tx.GenerateOrBroadcastTx` can be used to generate or broadcast a transaction. For example: ```go import "github.com/spf13/cobra" +import "github.com/cosmos/cosmos-sdk/client" import "github.com/cosmos/cosmos-sdk/client/tx" -import "github.com/cosmos/cosmos-sdk/client/context" -func NewCmdDoSomething(ctx context.CLIContext) *cobra.Command { +func NewCmdDoSomething(clientCtx client.Context) *cobra.Command { return &cobra.Command{ RunE: func(cmd *cobra.Command, args []string) error { - ctx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := ctx.InitWithInput(cmd.InOrStdin()) msg := NewSomeMsg{...} - tx.GenerateOrBroadcastTx(cliCtx, msg) + tx.GenerateOrBroadcastTx(clientCtx, msg) }, } } diff --git a/docs/architecture/adr-021-protobuf-query-encoding.md b/docs/architecture/adr-021-protobuf-query-encoding.md index 198432e94baf..178c582df7af 100644 --- a/docs/architecture/adr-021-protobuf-query-encoding.md +++ b/docs/architecture/adr-021-protobuf-query-encoding.md @@ -211,14 +211,14 @@ we have tweaked the grpc codegen to use an interface rather than concrete type for the generated client struct. This allows us to also reuse the GRPC infrastructure for ABCI client queries. -`CLIContext` will receive a new method `QueryConn` that returns a `ClientConn` +1Context` will receive a new method `QueryConn` that returns a `ClientConn` that routes calls to ABCI queries Clients (such as CLI methods) will then be able to call query methods like this: ```go -cliCtx := context.NewCLIContext() -queryClient := types.NewQueryClient(cliCtx.QueryConn()) +clientCtx := client.NewContext() +queryClient := types.NewQueryClient(clientCtx.QueryConn()) params := &types.QueryBalanceParams{addr, denom} result, err := queryClient.QueryBalance(gocontext.Background(), params) ``` diff --git a/docs/building-modules/module-interfaces.md b/docs/building-modules/module-interfaces.md index 442777b3a9d1..7eb37dd3a012 100644 --- a/docs/building-modules/module-interfaces.md +++ b/docs/building-modules/module-interfaces.md @@ -30,10 +30,10 @@ This getter function creates the command for the Buy Name transaction. It does t + **Short and Long:** A description for the function is provided here. A `Short` description is expected, and `Long` can be used to provide a more detailed description when a user uses the `--help` flag to ask for more information. + **RunE:** Defines a function that can return an error, called when the command is executed. Using `Run` would do the same thing, but would not allow for errors to be returned. - **`RunE` Function Body:** The function should be specified as a `RunE` to allow for errors to be returned. This function encapsulates all of the logic to create a new transaction that is ready to be relayed to nodes. - + The function should first initialize a [`TxBuilder`](../core/transactions.md#txbuilder) with the application `codec`'s `TxEncoder`, as well as a new [`CLIContext`](../interfaces/query-lifecycle.md#clicontext) with the `codec` and `AccountDecoder`. These contexts contain all the information provided by the user and will be used to transfer this user-specific information between processes. To learn more about how contexts are used in a transaction, click [here](../core/transactions.md#transaction-generation). + + The function should first initialize a [`TxBuilder`](../core/transactions.md#txbuilder) with the application `codec`'s `TxEncoder`, as well as a new [`Context`](../interfaces/query-lifecycle.md#context) with the `codec` and `AccountDecoder`. These contexts contain all the information provided by the user and will be used to transfer this user-specific information between processes. To learn more about how contexts are used in a transaction, click [here](../core/transactions.md#transaction-generation). + If applicable, the command's arguments are parsed. Here, the `amount` given by the user is parsed into a denomination of `coins`. - + If applicable, the `CLIContext` is used to retrieve any parameters such as the transaction originator's address to be used in the transaction. Here, the `from` address is retrieved by calling `cliCtx.getFromAddress()`. - + A [message](./messages-and-queries.md) is created using all parameters parsed from the command arguments and `CLIContext`. The constructor function of the specific message type is called directly. It is good practice to call `ValidateBasic()` on the newly created message to run a sanity check and check for invalid arguments. + + If applicable, the `Context` is used to retrieve any parameters such as the transaction originator's address to be used in the transaction. Here, the `from` address is retrieved by calling `cliCtx.getFromAddress()`. + + A [message](./messages-and-queries.md) is created using all parameters parsed from the command arguments and `Context`. The constructor function of the specific message type is called directly. It is good practice to call `ValidateBasic()` on the newly created message to run a sanity check and check for invalid arguments. + Depending on what the user wants, the transaction is either generated offline or signed and broadcasted to the preconfigured node using `GenerateOrBroadcastMsgs()`. - **Flags.** Add any [flags](#flags) to the command. No flags were specified here, but all transaction commands have flags to provide additional information from the user (e.g. amount of fees they are willing to pay). These *persistent* [transaction flags](../interfaces/cli.md#flags) can be added to a higher-level command so that they apply to all transaction commands. @@ -54,11 +54,11 @@ This query returns the address that owns a particular name. The getter function - **`codec` and `queryRoute`.** In addition to taking in the application `codec`, query command getters also take a `queryRoute` used to construct a path [Baseapp](../core/baseapp.md#query-routing) uses to route the query in the application. - **Construct the command.** Read the [Cobra Documentation](https://github.com/spf13/cobra) and the [transaction command](#transaction-commands) example above for more information. The user must type `whois` and provide the `name` they are querying for as the only argument. - **`RunE`.** The function should be specified as a `RunE` to allow for errors to be returned. This function encapsulates all of the logic to create a new query that is ready to be relayed to nodes. - + The function should first initialize a new [`CLIContext`](../interfaces/query-lifecycle.md#clicontext) with the application `codec`. - + If applicable, the `CLIContext` is used to retrieve any parameters (e.g. the query originator's address to be used in the query) and marshal them with the query parameter type, in preparation to be relayed to a node. There are no `CLIContext` parameters in this case because the query does not involve any information about the user. + + The function should first initialize a new [`Context`](../interfaces/query-lifecycle.md#context) with the application `codec`. + + If applicable, the `Context` is used to retrieve any parameters (e.g. the query originator's address to be used in the query) and marshal them with the query parameter type, in preparation to be relayed to a node. There are no `Context` parameters in this case because the query does not involve any information about the user. + The `queryRoute` is used to construct a `path` [`baseapp`](../core/baseapp.md) will use to route the query to the appropriate [querier](./querier.md). The expected format for a query `path` is "queryCategory/queryRoute/queryType/arg1/arg2/...", where `queryCategory` can be `p2p`, `store`, `app`, or `custom`, `queryRoute` is the name of the module, and `queryType` is the name of the query type defined within the module. [`baseapp`](../core/baseapp.md) can handle each type of `queryCategory` by routing it to a module querier or retrieving results directly from stores and functions for querying peer nodes. Module queries are `custom` type queries (some SDK modules have exceptions, such as `auth` and `gov` module queries). - + The `CLIContext` `QueryWithData()` function is used to relay the query to a node and retrieve the response. It requires the `path`. It returns the result and height of the query upon success or an error if the query fails. In addition, it will verify the returned proof if `TrustNode` is disabled. If proof verification fails or the query height is invalid, an error will be returned. - + The `codec` is used to nmarshal the response and the `CLIContext` is used to print the output back to the user. + + The `Context` `QueryWithData()` function is used to relay the query to a node and retrieve the response. It requires the `path`. It returns the result and height of the query upon success or an error if the query fails. In addition, it will verify the returned proof if `TrustNode` is disabled. If proof verification fails or the query height is invalid, an error will be returned. + + The `codec` is used to nmarshal the response and the `Context` is used to print the output back to the user. - **Flags.** Add any [flags](#flags) to the command. @@ -125,7 +125,7 @@ The `BaseReq` includes basic information that every request needs to have, simil ### Request Handlers -Request handlers must be defined for both transaction and query requests. Handlers' arguments include a reference to the application's `codec` and the [`CLIContext`](../interfaces/query-lifecycle.md#clicontext) created in the user interaction. +Request handlers must be defined for both transaction and query requests. Handlers' arguments include a reference to the application's `codec` and the [`Context`](../interfaces/query-lifecycle.md#context) created in the user interaction. Here is an example of a request handler for the nameservice module `buyNameReq` request (the same one shown above): @@ -135,7 +135,7 @@ The request handler can be broken down as follows: * **Parse Request:** The request handler first attempts to parse the request, and then run `Sanitize` and `ValidateBasic` on the underlying `BaseReq` to check the validity of the request. Next, it attempts to parse the arguments `Buyer` and `Amount` to the types `AccountAddress` and `Coins` respectively. * **Message:** Then, a [message](./messages-and-queries.md) of the type `MsgBuyName` (defined by the module developer to trigger the state changes for this transaction) is created from the values and another sanity check, `ValidateBasic` is run on it. -* **Generate Transaction:** Finally, the HTTP `ResponseWriter`, application [`codec`](../core/encoding.md), [`CLIContext`](../interfaces/query-lifecycle.md#clicontext), request [`BaseReq`](../interfaces/rest.md#basereq), and message is passed to `WriteGenerateStdTxResponse` to further process the request. +* **Generate Transaction:** Finally, the HTTP `ResponseWriter`, application [`codec`](../core/encoding.md), [`Context`](../interfaces/query-lifecycle.md#context), request [`BaseReq`](../interfaces/rest.md#basereq), and message is passed to `WriteGenerateStdTxResponse` to further process the request. To read more about how a transaction is generated, visit the transactions documentation [here](../core/transactions.md#transaction-generation). @@ -149,7 +149,7 @@ The router used by the SDK is [Gorilla Mux](https://github.com/gorilla/mux). The Here is a `registerRoutes` function with one query route example from the [nameservice tutorial](https://cosmos.network/docs/tutorial/rest.html): ``` go -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, storeName string) { +func RegisterRoutes(cliCtx client.Context, r *mux.Router, cdc *codec.Codec, storeName string) { // ResolveName Query r.HandleFunc(fmt.Sprintf("/%s/names/{%s}", storeName, restName), resolveNameHandler(cdc, cliCtx, storeName)).Methods("GET") } @@ -157,9 +157,9 @@ func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, A few things to note: -* The router `r` has already been initialized by the application and is passed in here as an argument - this function is able to add on the nameservice module's routes onto any application's router. The application must also provide a [`CLIContext`](../interfaces/query-lifecycle.md#clicontext) that the querier will need to process user requests and the application [`codec`](../core/encoding.md) for encoding and decoding application-specific types. +* The router `r` has already been initialized by the application and is passed in here as an argument - this function is able to add on the nameservice module's routes onto any application's router. The application must also provide a [`Context`](../interfaces/query-lifecycle.md#context) that the querier will need to process user requests and the application [`codec`](../core/encoding.md) for encoding and decoding application-specific types. * `"/%s/names/{%s}", storeName, restName` is the url for the HTTP request. `storeName` is the name of the module, `restName` is a variable provided by the user to specify what kind of query they are making. -* `resolveNameHandler` is the query request handler defined by the module developer. It also takes the application `codec` and `CLIContext` passed in from the user side, as well as the `storeName`. +* `resolveNameHandler` is the query request handler defined by the module developer. It also takes the application `codec` and `Context` passed in from the user side, as well as the `storeName`. * `"GET"` is the HTTP Request method. As to be expected, queries are typically GET requests. Transactions are typically POST and PUT requests. diff --git a/docs/building-modules/module-manager.md b/docs/building-modules/module-manager.md index 70291e1ee279..5adc44fd22c4 100644 --- a/docs/building-modules/module-manager.md +++ b/docs/building-modules/module-manager.md @@ -37,7 +37,7 @@ Let us go through the methods: - `RegisterCodec(*codec.Codec)`: Registers the `codec` for the module, which is used to marhsal and unmarshal structs to/from `[]byte` in order to persist them in the moduel's `KVStore`. - `DefaultGenesis()`: Returns a default [`GenesisState`](./genesis.md#genesisstate) for the module, marshalled to `json.RawMessage`. The default `GenesisState` need to be defined by the module developer and is primarily used for testing. - `ValidateGenesis(json.RawMessage)`: Used to validate the `GenesisState` defined by a module, given in its `json.RawMessage` form. It will usually unmarshall the `json` before running a custom [`ValidateGenesis`](./genesis.md#validategenesis) function defined by the module developer. -- `RegisterRESTRoutes(context.CLIContext, *mux.Router)`: Registers the REST routes for the module. These routes will be used to map REST request to the module in order to process them. See [../interfaces/rest.md] for more. +- `RegisterRESTRoutes(client.Context, *mux.Router)`: Registers the REST routes for the module. These routes will be used to map REST request to the module in order to process them. See [../interfaces/rest.md] for more. - `GetTxCmd(*codec.Codec)`: Returns the root [`Tx` command](./module-interfaces.md#tx) for the module. The subcommands of this root command are used by end-users to generate new transactions containing [`message`s](./messages-and-queries.md#queries) defined in the module. - `GetQueryCmd(*codec.Codec)`: Return the root [`query` command](./module-interfaces.md#query) for the module. The subcommands of this root command are used by end-users to generate new queries to the subset of the state defined by the module. @@ -112,7 +112,7 @@ It implements the following methods: - `RegisterCodec(cdc *codec.Codec)`: Registers the [`codec`s](../core/encoding.md) of each of the application's `AppModuleBasic`. This function is usually called early on in the [application's construction](../basics/app-anatomy.md#constructor). - `DefaultGenesis()`: Provides default genesis information for modules in the application by calling the [`DefaultGenesis()`](./genesis.md#defaultgenesis) function of each module. It is used to construct a default genesis file for the application. - `ValidateGenesis(genesis map[string]json.RawMessage)`: Validates the genesis information modules by calling the [`ValidateGenesis()`](./genesis.md#validategenesis) function of each module. -- `RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router)`: Registers REST routes for modules by calling the [`RegisterRESTRoutes`](./module-interfaces.md#register-routes) function of each module. This function is usually called function from the `main.go` function of the [application's command-line interface](../interfaces/cli.md). +- `RegisterRESTRoutes(ctx client.Context, rtr *mux.Router)`: Registers REST routes for modules by calling the [`RegisterRESTRoutes`](./module-interfaces.md#register-routes) function of each module. This function is usually called function from the `main.go` function of the [application's command-line interface](../interfaces/cli.md). - `AddTxCommands(rootTxCmd *cobra.Command, cdc *codec.Codec)`: Adds modules' transaction commands to the application's [`rootTxCommand`](../interfaces/cli.md#transaction-commands). This function is usually called function from the `main.go` function of the [application's command-line interface](../interfaces/cli.md). - `AddQueryCommands(rootQueryCmd *cobra.Command, cdc *codec.Codec)`: Adds modules' query commands to the application's [`rootQueryCommand`](../interfaces/cli.md#query-commands). This function is usually called function from the `main.go` function of the [application's command-line interface](../interfaces/cli.md). diff --git a/docs/core/transactions.md b/docs/core/transactions.md index 42302d32063a..ede39cf1a627 100644 --- a/docs/core/transactions.md +++ b/docs/core/transactions.md @@ -55,13 +55,13 @@ Note: module `messages` are not to be confused with [ABCI Messages](https://tend To learn more about `message`s, click [here](../building-modules/messages-and-queries.md#messages). -While messages contain the information for state transition logic, a transaction's other metadata and relevant information are stored in the `TxBuilder` and `CLIContext`. +While messages contain the information for state transition logic, a transaction's other metadata and relevant information are stored in the `TxBuilder` and `Context`. ### Transaction Generation Transactions are first created by end-users through an `appcli tx` command through the command-line or a POST request to an HTTPS server. For details about transaction creation, click [here](../basics/tx-lifecycle.md#transaction-creation). -[`Contexts`](https://godoc.org/context) are immutable objects that contain all the information needed to process a request. In the process of creating a transaction through the `auth` module (though it is not mandatory to create transactions this way), two contexts are created: the [`CLIContext`](../interfaces/query-lifecycle.md#clicontext) and `TxBuilder`. Both are automatically generated and do not need to be defined by application developers, but do require input from the transaction creator (e.g. using flags through the CLI). +[`Contexts`](https://godoc.org/context) are immutable objects that contain all the information needed to process a request. In the process of creating a transaction through the `auth` module (though it is not mandatory to create transactions this way), two contexts are created: the [`Context`](../interfaces/query-lifecycle.md#context) and `TxBuilder`. Both are automatically generated and do not need to be defined by application developers, but do require input from the transaction creator (e.g. using flags through the CLI). The `TxBuilder` contains data closely related with the processing of transactions. @@ -79,9 +79,9 @@ The `TxBuilder` contains data closely related with the processing of transaction - `Fees`, the maximum amount the user is willing to pay in fees. Alternative to specifying gas prices. - `GasPrices`, the amount per unit of gas the user is willing to pay in fees. Alternative to specifying fees. -The `CLIContext` is initialized using the application's `codec` and data more closely related to the user interaction with the interface, holding data such as the output to the user and the broadcast mode. Read more about `CLIContext` [here](../interfaces/query-lifecycle.md#clicontext). +The `Context` is initialized using the application's `codec` and data more closely related to the user interaction with the interface, holding data such as the output to the user and the broadcast mode. Read more about `Context` [here](../interfaces/query-lifecycle.md#context). -Every message in a transaction must be signed by the addresses specified by `GetSigners`. The signing process must be handled by a module, and the most widely used one is the [`auth`](https://github.com/cosmos/cosmos-sdk/tree/master/x/auth/spec) module. Signing is automatically performed when the transaction is created, unless the user choses to generate and sign separately. The `TxBuilder` (namely, the `KeyBase`) is used to perform the signing operations, and the `CLIContext` is used to broadcast transactions. +Every message in a transaction must be signed by the addresses specified by `GetSigners`. The signing process must be handled by a module, and the most widely used one is the [`auth`](https://github.com/cosmos/cosmos-sdk/tree/master/x/auth/spec) module. Signing is automatically performed when the transaction is created, unless the user choses to generate and sign separately. The `TxBuilder` (namely, the `KeyBase`) is used to perform the signing operations, and the `Context` is used to broadcast transactions. ### Handlers diff --git a/docs/interfaces/query-lifecycle.md b/docs/interfaces/query-lifecycle.md index a18bd50bf490..395043dfa48e 100644 --- a/docs/interfaces/query-lifecycle.md +++ b/docs/interfaces/query-lifecycle.md @@ -40,7 +40,7 @@ The CLI understands a specific set of commands, defined in a hierarchical struct ### REST -Another interface through which users can make queries is through HTTP Requests to a [REST server](./rest.md#rest-server). The REST server contains, among other things, a [`CLIContext`](#clicontext) and [mux](./rest.md#gorilla-mux) router. The request looks like this: +Another interface through which users can make queries is through HTTP Requests to a [REST server](./rest.md#rest-server). The REST server contains, among other things, a [`Context`](#context) and [mux](./rest.md#gorilla-mux) router. The request looks like this: ```bash GET http://localhost:{PORT}/staking/delegators/{delegatorAddr}/delegations @@ -52,17 +52,17 @@ The router automatically routes the `Query` HTTP request to the staking module ` +++ https://github.com/cosmos/cosmos-sdk/blob/7d7821b9af132b0f6131640195326aa02b6751db/x/staking/client/rest/query.go#L103-L106 -Since this function is defined within the module and thus has no inherent knowledge of the application `Query` belongs to, it takes in the application `codec` and `CLIContext` as parameters. +Since this function is defined within the module and thus has no inherent knowledge of the application `Query` belongs to, it takes in the application `codec` and `Context` as parameters. To summarize, when users interact with the interfaces, they create a CLI command or HTTP request. `Query` now exists in one of these two forms, but needs to be transformed into an object understood by a full-node. ## Query Preparation -The interactions from the users' perspective are a bit different, but the underlying functions are almost identical because they are implementations of the same command defined by the module developer. This step of processing happens within the CLI or REST server and heavily involves a `CLIContext`. +The interactions from the users' perspective are a bit different, but the underlying functions are almost identical because they are implementations of the same command defined by the module developer. This step of processing happens within the CLI or REST server and heavily involves a `Context`. -### CLIContext +### Context -The first thing that is created in the execution of a CLI command is a `CLIContext`, while the REST Server directly provides a `CLIContext` for the REST Request handler. A [Context](../core/context.md) is an immutable object that stores all the data needed to process a request on the user side. In particular, a `CLIContext` stores the following: +The first thing that is created in the execution of a CLI command is a `Context`, while the REST Server directly provides a `Context` for the REST Request handler. A [Context](../core/context.md) is an immutable object that stores all the data needed to process a request on the user side. In particular, a `Context` stores the following: * **Codec**: The [encoder/decoder](../core/encoding.md) used by the application, used to marshal the parameters and query before making the Tendermint RPC request and unmarshal the returned response into a JSON object. * **Account Decoder**: The account decoder from the [`auth`](https://github.com/cosmos/cosmos-sdk/tree/master/x/auth/spec) module, which translates `[]byte`s into accounts. @@ -71,19 +71,19 @@ The first thing that is created in the execution of a CLI command is a `CLIConte * **Output Writer**: A [Writer](https://golang.org/pkg/io/#Writer) used to output the response. * **Configurations**: The flags configured by the user for this command, including `--height`, specifying the height of the blockchain to query and `--indent`, which indicates to add an indent to the JSON response. -The `CLIContext` also contains various functions such as `Query()` which retrieves the RPC Client and makes an ABCI call to relay a query to a full-node. +The `Context` also contains various functions such as `Query()` which retrieves the RPC Client and makes an ABCI call to relay a query to a full-node. +++ https://github.com/cosmos/cosmos-sdk/blob/7d7821b9af132b0f6131640195326aa02b6751db/client/context/context.go#L23-L47 -The `CLIContext`'s primary role is to store data used during interactions with the end-user and provide methods to interact with this data - it is used before and after the query is processed by the full-node. Specifically, in handling `Query`, the `CLIContext` is utilized to encode the query parameters, retrieve the full-node, and write the output. Prior to being relayed to a full-node, the query needs to be encoded into a `[]byte` form, as full-nodes are application-agnostic and do not understand specific types. The full-node (RPC Client) itself is retrieved using the `CLIContext`, which knows which node the user CLI is connected to. The query is relayed to this full-node to be processed. Finally, the `CLIContext` contains a `Writer` to write output when the response is returned. These steps are further described in later sections. +The `Context`'s primary role is to store data used during interactions with the end-user and provide methods to interact with this data - it is used before and after the query is processed by the full-node. Specifically, in handling `Query`, the `Context` is utilized to encode the query parameters, retrieve the full-node, and write the output. Prior to being relayed to a full-node, the query needs to be encoded into a `[]byte` form, as full-nodes are application-agnostic and do not understand specific types. The full-node (RPC Client) itself is retrieved using the `Context`, which knows which node the user CLI is connected to. The query is relayed to this full-node to be processed. Finally, the `Context` contains a `Writer` to write output when the response is returned. These steps are further described in later sections. ### Arguments and Route Creation -At this point in the lifecycle, the user has created a CLI command or HTTP Request with all of the data they wish to include in their `Query`. A `CLIContext` exists to assist in the rest of the `Query`'s journey. Now, the next step is to parse the command or request, extract the arguments, create a `queryRoute`, and encode everything. These steps all happen on the user side within the interface they are interacting with. +At this point in the lifecycle, the user has created a CLI command or HTTP Request with all of the data they wish to include in their `Query`. A `Context` exists to assist in the rest of the `Query`'s journey. Now, the next step is to parse the command or request, extract the arguments, create a `queryRoute`, and encode everything. These steps all happen on the user side within the interface they are interacting with. #### Encoding -In this case, `Query` contains an [address](../basics/accounts.md#addresses) `delegatorAddress` as its only argument. However, the request can only contain `[]byte`s, as it will be relayed to a consensus engine (e.g. Tendermint Core) of a full-node that has no inherent knowledge of the application types. Thus, the `codec` of `CLIContext` is used to marshal the address. +In this case, `Query` contains an [address](../basics/accounts.md#addresses) `delegatorAddress` as its only argument. However, the request can only contain `[]byte`s, as it will be relayed to a consensus engine (e.g. Tendermint Core) of a full-node that has no inherent knowledge of the application types. Thus, the `codec` of `Context` is used to marshal the address. Here is what the code looks like for the CLI command: @@ -119,7 +119,7 @@ Now, `Query` exists as a set of encoded arguments and a route to a specific modu #### ABCI Query Call -The `CLIContext` has a `Query()` function used to retrieve the pre-configured node and relay a query to it; the function takes the query `route` and arguments as parameters. It first retrieves the RPC Client (called the [**node**](../core/node.md)) configured by the user to relay this query to, and creates the `ABCIQueryOptions` (parameters formatted for the ABCI call). The node is then used to make the ABCI call, `ABCIQueryWithOptions()`. +The `Context` has a `Query()` function used to retrieve the pre-configured node and relay a query to it; the function takes the query `route` and arguments as parameters. It first retrieves the RPC Client (called the [**node**](../core/node.md)) configured by the user to relay this query to, and creates the `ABCIQueryOptions` (parameters formatted for the ABCI call). The node is then used to make the ABCI call, `ABCIQueryWithOptions()`. Here is what the code looks like: @@ -141,19 +141,19 @@ Once a result is received from the querier, `baseapp` begins the process of retu ## Response -Since `Query()` is an ABCI function, `baseapp` returns the response as an [`abci.ResponseQuery`](https://tendermint.com/docs/spec/abci/abci.html#messages) type. The `CLIContext` `Query()` routine receives the response and, if `--trust-node` is toggled to `false` and a proof needs to be verified, the response is verified with the `CLIContext` `verifyProof()` function before the response is returned. +Since `Query()` is an ABCI function, `baseapp` returns the response as an [`abci.ResponseQuery`](https://tendermint.com/docs/spec/abci/abci.html#messages) type. The `Context` `Query()` routine receives the response and, if `--trust-node` is toggled to `false` and a proof needs to be verified, the response is verified with the `Context` `verifyProof()` function before the response is returned. +++ https://github.com/cosmos/cosmos-sdk/blob/7d7821b9af132b0f6131640195326aa02b6751db/client/context/query.go#L127-L165 ### CLI Response -The application [`codec`](../core/encoding.md) is used to unmarshal the response to a JSON and the `CLIContext` prints the output to the command line, applying any configurations such as `--indent`. +The application [`codec`](../core/encoding.md) is used to unmarshal the response to a JSON and the `Context` prints the output to the command line, applying any configurations such as `--indent`. +++ https://github.com/cosmos/cosmos-sdk/blob/7d7821b9af132b0f6131640195326aa02b6751db/x/staking/client/cli/query.go#L252-L293 ### REST Response -The [REST server](./rest.md#rest-server) uses the `CLIContext` to format the response properly, then uses the HTTP package to write the appropriate response or error. +The [REST server](./rest.md#rest-server) uses the `Context` to format the response properly, then uses the HTTP package to write the appropriate response or error. +++ https://github.com/cosmos/cosmos-sdk/blob/7d7821b9af132b0f6131640195326aa02b6751db/x/staking/client/rest/utils.go#L115-L148 diff --git a/docs/interfaces/rest.md b/docs/interfaces/rest.md index da9f9e88d3f5..876a4eeb5ac8 100644 --- a/docs/interfaces/rest.md +++ b/docs/interfaces/rest.md @@ -32,7 +32,7 @@ Note that if `trust-node` is set to `false`, the REST server will verify the que A REST Server is used to receive and route HTTP Requests, obtain the results from the application, and return a response to the user. The REST Server defined by the SDK `rest` package contains the following: - **Router:** A router for HTTP requests. A new router can be instantiated for an application and used to match routes based on path, request method, headers, etc. The SDK uses the [Gorilla Mux Router](https://github.com/gorilla/mux). -- **CLIContext:** A [`CLIContext`](./query-lifecycle.md#clicontext) created for a user interaction. +- **Context:** A [`Context`](./query-lifecycle.md#context) created for a user interaction. - **Keybase:** A [Keybase](../basics/accounts.md#keybase) is a key manager. - **Logger:** A logger from Tendermint `Log`, a log package structured around key-value pairs that allows logging level to be set differently for different keys. The logger takes `Debug()`, `Info()`, and `Error()`s. - **Listener:** A [listener](https://golang.org/pkg/net/#Listener) from the net package. @@ -49,8 +49,8 @@ At the bare minimum, a `RegisterRoutes()` function should use the SDK client pac ```go func registerRoutes(rs *rest.RestServer) { - client.RegisterRoutes(rs.CliCtx, rs.Mux) - app.ModuleBasics.RegisterRESTRoutes(rs.CliCtx, rs.Mux) + rpc.RegisterRoutes(rs.ClientCtx, rs.Mux) + app.ModuleBasics.RegisterRESTRoutes(rs.ClientCtx, rs.Mux) } ``` diff --git a/go.sum b/go.sum index 75f7bca09919..507be717e0b5 100644 --- a/go.sum +++ b/go.sum @@ -480,8 +480,6 @@ github.com/tendermint/iavl v0.13.3 h1:expgBDY1MX+6/3sqrIxGChbTNf9N9aTJ67SH4bPchC github.com/tendermint/iavl v0.13.3/go.mod h1:2lE7GiWdSvc7kvT78ncIKmkOjCnp6JEnSb2O7B9htLw= github.com/tendermint/tendermint v0.33.2 h1:NzvRMTuXJxqSsFed2J7uHmMU5N1CVzSpfi3nCc882KY= github.com/tendermint/tendermint v0.33.2/go.mod h1:25DqB7YvV1tN3tHsjWoc2vFtlwICfrub9XO6UBO+4xk= -github.com/tendermint/tendermint v0.33.4 h1:NM3G9618yC5PaaxGrcAySc5ylc1PAANeIx42u2Re/jo= -github.com/tendermint/tendermint v0.33.4/go.mod h1:6NW9DVkvsvqmCY6wbRsOo66qGDhMXglRL70aXajvBEA= github.com/tendermint/tendermint v0.33.5 h1:jYgRd9ImkzA9iOyhpmgreYsqSB6tpDa6/rXYPb8HKE8= github.com/tendermint/tendermint v0.33.5/go.mod h1:0yUs9eIuuDq07nQql9BmI30FtYGcEC60Tu5JzB5IezM= github.com/tendermint/tm-db v0.4.1/go.mod h1:JsJ6qzYkCGiGwm5GHl/H5GLI9XLb6qZX7PRe425dHAY= diff --git a/simapp/cmd/simcli/main.go b/simapp/cmd/simcli/main.go index 0ae3f1c5dc5b..780fcaca7f42 100644 --- a/simapp/cmd/simcli/main.go +++ b/simapp/cmd/simcli/main.go @@ -10,7 +10,6 @@ import ( "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/lcd" @@ -118,15 +117,15 @@ func txCmd(cdc *codec.Codec) *cobra.Command { RunE: client.ValidateCmd, } - cliCtx := context.CLIContext{} - cliCtx = cliCtx. + clientCtx := client.Context{} + clientCtx = clientCtx. WithJSONMarshaler(appCodec). WithTxGenerator(types.StdTxGenerator{Cdc: cdc}). WithAccountRetriever(types.NewAccountRetriever(appCodec)). WithCodec(cdc) txCmd.AddCommand( - bankcmd.NewSendTxCmd(cliCtx), + bankcmd.NewSendTxCmd(clientCtx), flags.LineBreak, authcmd.GetSignCommand(cdc), authcmd.GetMultiSignCommand(cdc), @@ -139,7 +138,7 @@ func txCmd(cdc *codec.Codec) *cobra.Command { ) // add modules' tx commands - simapp.ModuleBasics.AddTxCommands(txCmd, cliCtx) + simapp.ModuleBasics.AddTxCommands(txCmd, clientCtx) return txCmd } @@ -147,9 +146,9 @@ func txCmd(cdc *codec.Codec) *cobra.Command { // registerRoutes registers the routes from the different modules for the REST client. // NOTE: details on the routes added for each module are in the module documentation func registerRoutes(rs *lcd.RestServer) { - client.RegisterRoutes(rs.CliCtx, rs.Mux) - authrest.RegisterTxRoutes(rs.CliCtx, rs.Mux) - simapp.ModuleBasics.RegisterRESTRoutes(rs.CliCtx, rs.Mux) + rpc.RegisterRoutes(rs.ClientCtx, rs.Mux) + authrest.RegisterTxRoutes(rs.ClientCtx, rs.Mux) + simapp.ModuleBasics.RegisterRESTRoutes(rs.ClientCtx, rs.Mux) } func initConfig(cmd *cobra.Command) error { diff --git a/tests/mocks/account_retriever.go b/tests/mocks/account_retriever.go index f0e089f2881a..fed099f26e2d 100644 --- a/tests/mocks/account_retriever.go +++ b/tests/mocks/account_retriever.go @@ -1,11 +1,11 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: client/context/account_retriever.go +// Source: client/account_retriever.go // Package mocks is a generated GoMock package. package mocks import ( - context "github.com/cosmos/cosmos-sdk/client/context" + client "github.com/cosmos/cosmos-sdk/client" types "github.com/cosmos/cosmos-sdk/types" gomock "github.com/golang/mock/gomock" reflect "reflect" @@ -35,7 +35,7 @@ func (m *MockAccountRetriever) EXPECT() *MockAccountRetrieverMockRecorder { } // EnsureExists mocks base method -func (m *MockAccountRetriever) EnsureExists(nodeQuerier context.NodeQuerier, addr types.AccAddress) error { +func (m *MockAccountRetriever) EnsureExists(nodeQuerier client.NodeQuerier, addr types.AccAddress) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "EnsureExists", nodeQuerier, addr) ret0, _ := ret[0].(error) @@ -49,7 +49,7 @@ func (mr *MockAccountRetrieverMockRecorder) EnsureExists(nodeQuerier, addr inter } // GetAccountNumberSequence mocks base method -func (m *MockAccountRetriever) GetAccountNumberSequence(nodeQuerier context.NodeQuerier, addr types.AccAddress) (uint64, uint64, error) { +func (m *MockAccountRetriever) GetAccountNumberSequence(nodeQuerier client.NodeQuerier, addr types.AccAddress) (uint64, uint64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAccountNumberSequence", nodeQuerier, addr) ret0, _ := ret[0].(uint64) diff --git a/tests/mocks/tendermint_tm_db_DB.go b/tests/mocks/tendermint_tm_db_DB.go index cdf5e5ab0a27..bed59a498d03 100644 --- a/tests/mocks/tendermint_tm_db_DB.go +++ b/tests/mocks/tendermint_tm_db_DB.go @@ -6,7 +6,7 @@ package mocks import ( gomock "github.com/golang/mock/gomock" - db "github.com/tendermint/tm-db" + tm_db "github.com/tendermint/tm-db" reflect "reflect" ) @@ -106,10 +106,10 @@ func (mr *MockDBMockRecorder) Has(arg0 interface{}) *gomock.Call { } // Iterator mocks base method -func (m *MockDB) Iterator(arg0, arg1 []byte) (db.Iterator, error) { +func (m *MockDB) Iterator(arg0, arg1 []byte) (tm_db.Iterator, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Iterator", arg0, arg1) - ret0, _ := ret[0].(db.Iterator) + ret0, _ := ret[0].(tm_db.Iterator) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -121,10 +121,10 @@ func (mr *MockDBMockRecorder) Iterator(arg0, arg1 interface{}) *gomock.Call { } // NewBatch mocks base method -func (m *MockDB) NewBatch() db.Batch { +func (m *MockDB) NewBatch() tm_db.Batch { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NewBatch") - ret0, _ := ret[0].(db.Batch) + ret0, _ := ret[0].(tm_db.Batch) return ret0 } @@ -149,10 +149,10 @@ func (mr *MockDBMockRecorder) Print() *gomock.Call { } // ReverseIterator mocks base method -func (m *MockDB) ReverseIterator(arg0, arg1 []byte) (db.Iterator, error) { +func (m *MockDB) ReverseIterator(arg0, arg1 []byte) (tm_db.Iterator, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReverseIterator", arg0, arg1) - ret0, _ := ret[0].(db.Iterator) + ret0, _ := ret[0].(tm_db.Iterator) ret1, _ := ret[1].(error) return ret0, ret1 } diff --git a/tests/mocks/types_module_module.go b/tests/mocks/types_module_module.go index 0d52cde999c6..22b353a97eb5 100644 --- a/tests/mocks/types_module_module.go +++ b/tests/mocks/types_module_module.go @@ -6,7 +6,7 @@ package mocks import ( json "encoding/json" - context "github.com/cosmos/cosmos-sdk/client/context" + client "github.com/cosmos/cosmos-sdk/client" codec "github.com/cosmos/cosmos-sdk/codec" types "github.com/cosmos/cosmos-sdk/types" gomock "github.com/golang/mock/gomock" @@ -94,7 +94,7 @@ func (mr *MockAppModuleBasicMockRecorder) ValidateGenesis(arg0, arg1 interface{} } // RegisterRESTRoutes mocks base method -func (m *MockAppModuleBasic) RegisterRESTRoutes(arg0 context.CLIContext, arg1 *mux.Router) { +func (m *MockAppModuleBasic) RegisterRESTRoutes(arg0 client.Context, arg1 *mux.Router) { m.ctrl.T.Helper() m.ctrl.Call(m, "RegisterRESTRoutes", arg0, arg1) } @@ -106,7 +106,7 @@ func (mr *MockAppModuleBasicMockRecorder) RegisterRESTRoutes(arg0, arg1 interfac } // GetTxCmd mocks base method -func (m *MockAppModuleBasic) GetTxCmd(arg0 context.CLIContext) *cobra.Command { +func (m *MockAppModuleBasic) GetTxCmd(arg0 client.Context) *cobra.Command { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetTxCmd", arg0) ret0, _ := ret[0].(*cobra.Command) @@ -211,7 +211,7 @@ func (mr *MockAppModuleGenesisMockRecorder) ValidateGenesis(arg0, arg1 interface } // RegisterRESTRoutes mocks base method -func (m *MockAppModuleGenesis) RegisterRESTRoutes(arg0 context.CLIContext, arg1 *mux.Router) { +func (m *MockAppModuleGenesis) RegisterRESTRoutes(arg0 client.Context, arg1 *mux.Router) { m.ctrl.T.Helper() m.ctrl.Call(m, "RegisterRESTRoutes", arg0, arg1) } @@ -223,7 +223,7 @@ func (mr *MockAppModuleGenesisMockRecorder) RegisterRESTRoutes(arg0, arg1 interf } // GetTxCmd mocks base method -func (m *MockAppModuleGenesis) GetTxCmd(arg0 context.CLIContext) *cobra.Command { +func (m *MockAppModuleGenesis) GetTxCmd(arg0 client.Context) *cobra.Command { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetTxCmd", arg0) ret0, _ := ret[0].(*cobra.Command) @@ -356,7 +356,7 @@ func (mr *MockAppModuleMockRecorder) ValidateGenesis(arg0, arg1 interface{}) *go } // RegisterRESTRoutes mocks base method -func (m *MockAppModule) RegisterRESTRoutes(arg0 context.CLIContext, arg1 *mux.Router) { +func (m *MockAppModule) RegisterRESTRoutes(arg0 client.Context, arg1 *mux.Router) { m.ctrl.T.Helper() m.ctrl.Call(m, "RegisterRESTRoutes", arg0, arg1) } @@ -368,7 +368,7 @@ func (mr *MockAppModuleMockRecorder) RegisterRESTRoutes(arg0, arg1 interface{}) } // GetTxCmd mocks base method -func (m *MockAppModule) GetTxCmd(arg0 context.CLIContext) *cobra.Command { +func (m *MockAppModule) GetTxCmd(arg0 client.Context) *cobra.Command { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetTxCmd", arg0) ret0, _ := ret[0].(*cobra.Command) diff --git a/types/module/module.go b/types/module/module.go index d3bdd2155c81..2ef4cc98a66a 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -35,7 +35,7 @@ import ( "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -51,8 +51,8 @@ type AppModuleBasic interface { ValidateGenesis(codec.JSONMarshaler, json.RawMessage) error // client functionality - RegisterRESTRoutes(context.CLIContext, *mux.Router) - GetTxCmd(context.CLIContext) *cobra.Command + RegisterRESTRoutes(client.Context, *mux.Router) + GetTxCmd(client.Context) *cobra.Command GetQueryCmd(*codec.Codec) *cobra.Command } @@ -97,14 +97,14 @@ func (bm BasicManager) ValidateGenesis(cdc codec.JSONMarshaler, genesis map[stri } // RegisterRESTRoutes registers all module rest routes -func (bm BasicManager) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { +func (bm BasicManager) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { for _, b := range bm { - b.RegisterRESTRoutes(ctx, rtr) + b.RegisterRESTRoutes(clientCtx, rtr) } } // AddTxCommands adds all tx commands to the rootTxCmd -func (bm BasicManager) AddTxCommands(rootTxCmd *cobra.Command, ctx context.CLIContext) { +func (bm BasicManager) AddTxCommands(rootTxCmd *cobra.Command, ctx client.Context) { for _, b := range bm { if cmd := b.GetTxCmd(ctx); cmd != nil { rootTxCmd.AddCommand(cmd) diff --git a/types/module/module_test.go b/types/module/module_test.go index 1f5e1f247bb0..45b6e8c46ad1 100644 --- a/types/module/module_test.go +++ b/types/module/module_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/tests/mocks" sdk "github.com/cosmos/cosmos-sdk/types" @@ -24,8 +24,8 @@ func TestBasicManager(t *testing.T) { mockCtrl := gomock.NewController(t) t.Cleanup(mockCtrl.Finish) cdc := codec.New() - ctx := context.CLIContext{} - ctx = ctx.WithCodec(cdc) + clientCtx := client.Context{} + clientCtx = clientCtx.WithCodec(cdc) wantDefaultGenesis := map[string]json.RawMessage{"mockAppModuleBasic1": json.RawMessage(``)} mockAppModuleBasic1 := mocks.NewMockAppModuleBasic(mockCtrl) @@ -33,9 +33,9 @@ func TestBasicManager(t *testing.T) { mockAppModuleBasic1.EXPECT().Name().AnyTimes().Return("mockAppModuleBasic1") mockAppModuleBasic1.EXPECT().DefaultGenesis(gomock.Eq(cdc)).Times(1).Return(json.RawMessage(``)) mockAppModuleBasic1.EXPECT().ValidateGenesis(gomock.Eq(cdc), gomock.Eq(wantDefaultGenesis["mockAppModuleBasic1"])).Times(1).Return(errFoo) - mockAppModuleBasic1.EXPECT().RegisterRESTRoutes(gomock.Eq(context.CLIContext{}), gomock.Eq(&mux.Router{})).Times(1) + mockAppModuleBasic1.EXPECT().RegisterRESTRoutes(gomock.Eq(client.Context{}), gomock.Eq(&mux.Router{})).Times(1) mockAppModuleBasic1.EXPECT().RegisterCodec(gomock.Eq(cdc)).Times(1) - mockAppModuleBasic1.EXPECT().GetTxCmd(ctx).Times(1).Return(nil) + mockAppModuleBasic1.EXPECT().GetTxCmd(clientCtx).Times(1).Return(nil) mockAppModuleBasic1.EXPECT().GetQueryCmd(cdc).Times(1).Return(nil) mm := module.NewBasicManager(mockAppModuleBasic1) @@ -50,10 +50,10 @@ func TestBasicManager(t *testing.T) { require.True(t, errors.Is(errFoo, mm.ValidateGenesis(cdc, wantDefaultGenesis))) - mm.RegisterRESTRoutes(context.CLIContext{}, &mux.Router{}) + mm.RegisterRESTRoutes(client.Context{}, &mux.Router{}) mockCmd := &cobra.Command{Use: "root"} - mm.AddTxCommands(mockCmd, ctx) + mm.AddTxCommands(mockCmd, clientCtx) mm.AddQueryCommands(mockCmd, cdc) diff --git a/types/rest/rest.go b/types/rest/rest.go index 8395c983c32e..2ada6d6da586 100644 --- a/types/rest/rest.go +++ b/types/rest/rest.go @@ -14,7 +14,7 @@ import ( "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -229,32 +229,32 @@ func ParseFloat64OrReturnBadRequest(w http.ResponseWriter, s string, defaultIfEm // ParseQueryHeightOrReturnBadRequest sets the height to execute a query if set by the http request. // It returns false if there was an error parsing the height. -func ParseQueryHeightOrReturnBadRequest(w http.ResponseWriter, cliCtx context.CLIContext, r *http.Request) (context.CLIContext, bool) { +func ParseQueryHeightOrReturnBadRequest(w http.ResponseWriter, clientCtx client.Context, r *http.Request) (client.Context, bool) { heightStr := r.FormValue("height") if heightStr != "" { height, err := strconv.ParseInt(heightStr, 10, 64) if CheckBadRequestError(w, err) { - return cliCtx, false + return clientCtx, false } if height < 0 { WriteErrorResponse(w, http.StatusBadRequest, "height must be equal or greater than zero") - return cliCtx, false + return clientCtx, false } if height > 0 { - cliCtx = cliCtx.WithHeight(height) + clientCtx = clientCtx.WithHeight(height) } } else { - cliCtx = cliCtx.WithHeight(0) + clientCtx = clientCtx.WithHeight(0) } - return cliCtx, true + return clientCtx, true } // PostProcessResponseBare post processes a body similar to PostProcessResponse // except it does not wrap the body and inject the height. -func PostProcessResponseBare(w http.ResponseWriter, ctx context.CLIContext, body interface{}) { +func PostProcessResponseBare(w http.ResponseWriter, ctx client.Context, body interface{}) { var ( resp []byte err error @@ -293,7 +293,7 @@ func PostProcessResponseBare(w http.ResponseWriter, ctx context.CLIContext, body // PostProcessResponse performs post processing for a REST response. The result // returned to clients will contain two fields, the height at which the resource // was queried at and the original result. -func PostProcessResponse(w http.ResponseWriter, ctx context.CLIContext, resp interface{}) { +func PostProcessResponse(w http.ResponseWriter, ctx client.Context, resp interface{}) { var ( result []byte err error diff --git a/types/rest/rest_test.go b/types/rest/rest_test.go index 90988c4ef702..465c098c95cd 100644 --- a/types/rest/rest_test.go +++ b/types/rest/rest_test.go @@ -15,7 +15,7 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/secp256k1" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types" @@ -147,25 +147,25 @@ func TestParseQueryHeight(t *testing.T) { name string req *http.Request w http.ResponseWriter - cliCtx context.CLIContext + clientCtx client.Context expectedHeight int64 expectedOk bool }{ - {"no height", req0, httptest.NewRecorder(), context.CLIContext{}, emptyHeight, true}, - {"height", req1, httptest.NewRecorder(), context.CLIContext{}, height, true}, - {"invalid height", req2, httptest.NewRecorder(), context.CLIContext{}, emptyHeight, false}, - {"negative height", req3, httptest.NewRecorder(), context.CLIContext{}, emptyHeight, false}, + {"no height", req0, httptest.NewRecorder(), client.Context{}, emptyHeight, true}, + {"height", req1, httptest.NewRecorder(), client.Context{}, height, true}, + {"invalid height", req2, httptest.NewRecorder(), client.Context{}, emptyHeight, false}, + {"negative height", req3, httptest.NewRecorder(), client.Context{}, emptyHeight, false}, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(tt.w, tt.cliCtx, tt.req) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(tt.w, tt.clientCtx, tt.req) if tt.expectedOk { require.True(t, ok) - require.Equal(t, tt.expectedHeight, cliCtx.Height) + require.Equal(t, tt.expectedHeight, clientCtx.Height) } else { require.False(t, ok) - require.Empty(t, tt.expectedHeight, cliCtx.Height) + require.Empty(t, tt.expectedHeight, clientCtx.Height) } }) } @@ -187,7 +187,7 @@ func TestProcessPostResponse(t *testing.T) { // setup viper.Set(flags.FlagOffline, true) - ctx := context.NewCLIContext() + ctx := client.NewContext() height := int64(194423) privKey := secp256k1.GenPrivKey() @@ -312,11 +312,11 @@ func TestPostProcessResponseBare(t *testing.T) { t.Parallel() // write bytes - ctx := context.CLIContext{} + clientCtx := client.Context{} w := httptest.NewRecorder() bs := []byte("text string") - rest.PostProcessResponseBare(w, ctx, bs) + rest.PostProcessResponseBare(w, clientCtx, bs) res := w.Result() //nolint:bodyclose require.Equal(t, http.StatusOK, res.StatusCode) @@ -328,14 +328,14 @@ func TestPostProcessResponseBare(t *testing.T) { require.Equal(t, "text string", string(got)) // write struct and indent response - ctx = context.CLIContext{Indent: true}.WithCodec(codec.New()) + clientCtx = client.Context{Indent: true}.WithCodec(codec.New()) w = httptest.NewRecorder() data := struct { X int `json:"x"` S string `json:"s"` }{X: 10, S: "test"} - rest.PostProcessResponseBare(w, ctx, data) + rest.PostProcessResponseBare(w, clientCtx, data) res = w.Result() //nolint:bodyclose require.Equal(t, http.StatusOK, res.StatusCode) @@ -350,14 +350,14 @@ func TestPostProcessResponseBare(t *testing.T) { }`, string(got)) // write struct, don't indent response - ctx = context.CLIContext{Indent: false}.WithCodec(codec.New()) + clientCtx = client.Context{Indent: false}.WithCodec(codec.New()) w = httptest.NewRecorder() data = struct { X int `json:"x"` S string `json:"s"` }{X: 10, S: "test"} - rest.PostProcessResponseBare(w, ctx, data) + rest.PostProcessResponseBare(w, clientCtx, data) res = w.Result() //nolint:bodyclose require.Equal(t, http.StatusOK, res.StatusCode) @@ -369,11 +369,11 @@ func TestPostProcessResponseBare(t *testing.T) { require.Equal(t, `{"x":"10","s":"test"}`, string(got)) // test marshalling failure - ctx = context.CLIContext{Indent: false}.WithCodec(codec.New()) + clientCtx = client.Context{Indent: false}.WithCodec(codec.New()) w = httptest.NewRecorder() data2 := badJSONMarshaller{} - rest.PostProcessResponseBare(w, ctx, data2) + rest.PostProcessResponseBare(w, clientCtx, data2) res = w.Result() //nolint:bodyclose require.Equal(t, http.StatusInternalServerError, res.StatusCode) @@ -395,7 +395,7 @@ func (badJSONMarshaller) MarshalJSON() ([]byte, error) { // asserts that ResponseRecorder returns the expected code and body // runs PostProcessResponse on the objects regular interface and on // the marshalled struct. -func runPostProcessResponse(t *testing.T, ctx context.CLIContext, obj interface{}, expectedBody []byte, indent bool) { +func runPostProcessResponse(t *testing.T, ctx client.Context, obj interface{}, expectedBody []byte, indent bool) { if indent { ctx.Indent = indent } diff --git a/x/auth/client/cli/broadcast.go b/x/auth/client/cli/broadcast.go index f948dbdd9b8b..9e24d63e5a38 100644 --- a/x/auth/client/cli/broadcast.go +++ b/x/auth/client/cli/broadcast.go @@ -6,10 +6,10 @@ import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/auth/client" + authclient "github.com/cosmos/cosmos-sdk/x/auth/client" ) // GetBroadcastCommand returns the tx broadcast command. @@ -26,28 +26,28 @@ $ tx broadcast ./mytxn.json `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) - if cliCtx.Offline { + if clientCtx.Offline { return errors.New("cannot broadcast tx during offline mode") } - stdTx, err := client.ReadStdTxFromFile(cliCtx.Codec, args[0]) + stdTx, err := authclient.ReadStdTxFromFile(clientCtx.Codec, args[0]) if err != nil { return err } - txBytes, err := cliCtx.Codec.MarshalBinaryBare(stdTx) + txBytes, err := clientCtx.Codec.MarshalBinaryBare(stdTx) if err != nil { return err } - res, err := cliCtx.BroadcastTx(txBytes) + res, err := clientCtx.BroadcastTx(txBytes) if err != nil { return err } - return cliCtx.PrintOutput(res) + return clientCtx.PrintOutput(res) }, } diff --git a/x/auth/client/cli/decode.go b/x/auth/client/cli/decode.go index 9e12507e4bcc..efd124921b52 100644 --- a/x/auth/client/cli/decode.go +++ b/x/auth/client/cli/decode.go @@ -7,7 +7,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -31,7 +31,7 @@ func GetDecodeCommand(codec *codec.Codec) *cobra.Command { func runDecodeTxString(codec *codec.Codec) func(cmd *cobra.Command, args []string) (err error) { return func(cmd *cobra.Command, args []string) (err error) { - cliCtx := context.NewCLIContext().WithCodec(codec).WithOutput(cmd.OutOrStdout()) + clientCtx := client.NewContext().WithCodec(codec).WithOutput(cmd.OutOrStdout()) var txBytes []byte if viper.GetBool(flagHex) { @@ -44,11 +44,11 @@ func runDecodeTxString(codec *codec.Codec) func(cmd *cobra.Command, args []strin } var stdTx authtypes.StdTx - err = cliCtx.Codec.UnmarshalBinaryBare(txBytes, &stdTx) + err = clientCtx.Codec.UnmarshalBinaryBare(txBytes, &stdTx) if err != nil { return err } - return cliCtx.PrintOutput(stdTx) + return clientCtx.PrintOutput(stdTx) } } diff --git a/x/auth/client/cli/encode.go b/x/auth/client/cli/encode.go index 245bb0e0f675..c97533c859ef 100644 --- a/x/auth/client/cli/encode.go +++ b/x/auth/client/cli/encode.go @@ -5,10 +5,10 @@ import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/auth/client" + authclient "github.com/cosmos/cosmos-sdk/x/auth/client" ) // txEncodeRespStr implements a simple Stringer wrapper for a encoded tx. @@ -29,15 +29,15 @@ 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(cdc) + clientCtx := client.NewContext().WithCodec(cdc) - stdTx, err := client.ReadStdTxFromFile(cliCtx.Codec, args[0]) + stdTx, err := authclient.ReadStdTxFromFile(clientCtx.Codec, args[0]) if err != nil { return } // re-encode it via the Amino wire protocol - txBytes, err := cliCtx.Codec.MarshalBinaryBare(stdTx) + txBytes, err := clientCtx.Codec.MarshalBinaryBare(stdTx) if err != nil { return err } @@ -46,7 +46,7 @@ If you supply a dash (-) argument in place of an input filename, the command rea txBytesBase64 := base64.StdEncoding.EncodeToString(txBytes) response := txEncodeRespStr(txBytesBase64) - return cliCtx.PrintOutput(response) + return clientCtx.PrintOutput(response) }, } diff --git a/x/auth/client/cli/query.go b/x/auth/client/cli/query.go index 2e428e1e543e..581a00cfe2ce 100644 --- a/x/auth/client/cli/query.go +++ b/x/auth/client/cli/query.go @@ -9,7 +9,6 @@ import ( tmtypes "github.com/tendermint/tendermint/types" "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" @@ -54,10 +53,10 @@ func QueryParamsCmd(cdc *codec.Codec) *cobra.Command { $ query auth params `), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParams) - res, _, err := cliCtx.QueryWithData(route, nil) + res, _, err := clientCtx.QueryWithData(route, nil) if err != nil { return err } @@ -67,7 +66,7 @@ $ query auth params return fmt.Errorf("failed to unmarshal params: %w", err) } - return cliCtx.PrintOutput(params) + return clientCtx.PrintOutput(params) }, } @@ -82,7 +81,7 @@ func GetAccountCmd(cdc *codec.Codec) *cobra.Command { Short: "Query for account by address", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) accGetter := types.NewAccountRetriever(authclient.Codec) key, err := sdk.AccAddressFromBech32(args[0]) @@ -90,12 +89,12 @@ func GetAccountCmd(cdc *codec.Codec) *cobra.Command { return err } - acc, err := accGetter.GetAccount(cliCtx, key) + acc, err := accGetter.GetAccount(clientCtx, key) if err != nil { return err } - return cliCtx.PrintOutput(acc) + return clientCtx.PrintOutput(acc) }, } @@ -150,14 +149,14 @@ $ %s query txs --%s 'message.sender=cosmos1...&message.action=withdraw_delegator page := viper.GetInt(flags.FlagPage) limit := viper.GetInt(flags.FlagLimit) - cliCtx := context.NewCLIContext().WithCodec(cdc) - txs, err := authclient.QueryTxsByEvents(cliCtx, tmEvents, page, limit, "") + clientCtx := client.NewContext().WithCodec(cdc) + txs, err := authclient.QueryTxsByEvents(clientCtx, tmEvents, page, limit, "") if err != nil { return err } var output []byte - if cliCtx.Indent { + if clientCtx.Indent { output, err = cdc.MarshalJSONIndent(txs, "", " ") } else { output, err = cdc.MarshalJSON(txs) @@ -196,9 +195,9 @@ func QueryTxCmd(cdc *codec.Codec) *cobra.Command { Short: "Query for a transaction by hash in a committed block", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) - output, err := authclient.QueryTx(cliCtx, args[0]) + output, err := authclient.QueryTx(clientCtx, args[0]) if err != nil { return err } @@ -207,7 +206,7 @@ func QueryTxCmd(cdc *codec.Codec) *cobra.Command { return fmt.Errorf("no transaction found with hash %s", args[0]) } - return cliCtx.PrintOutput(output) + return clientCtx.PrintOutput(output) }, } diff --git a/x/auth/client/cli/tx_multisign.go b/x/auth/client/cli/tx_multisign.go index 42b4daada567..8b58813adc03 100644 --- a/x/auth/client/cli/tx_multisign.go +++ b/x/auth/client/cli/tx_multisign.go @@ -12,13 +12,13 @@ import ( "github.com/tendermint/tendermint/crypto/multisig" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/auth/client" + authclient "github.com/cosmos/cosmos-sdk/x/auth/client" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -59,7 +59,7 @@ recommended to set such parameters manually. func makeMultiSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) (err error) { - stdTx, err := client.ReadStdTxFromFile(cdc, args[0]) + stdTx, err := authclient.ReadStdTxFromFile(cdc, args[0]) if err != nil { return } @@ -81,11 +81,11 @@ func makeMultiSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) multisigPub := multisigInfo.GetPubKey().(multisig.PubKeyMultisigThreshold) multisigSig := multisig.NewMultisig(len(multisigPub.PubKeys)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) txBldr := types.NewTxBuilderFromCLI(inBuf) - if !cliCtx.Offline { - accnum, seq, err := types.NewAccountRetriever(client.Codec).GetAccountNumberSequence(cliCtx, multisigInfo.GetAddress()) + if !clientCtx.Offline { + accnum, seq, err := types.NewAccountRetriever(authclient.Codec).GetAccountNumberSequence(clientCtx, multisigInfo.GetAddress()) if err != nil { return err } @@ -119,11 +119,11 @@ func makeMultiSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) sigOnly := viper.GetBool(flagSigOnly) var json []byte switch { - case sigOnly && cliCtx.Indent: + case sigOnly && clientCtx.Indent: json, err = cdc.MarshalJSONIndent(newTx.Signatures[0], "", " ") - case sigOnly && !cliCtx.Indent: + case sigOnly && !clientCtx.Indent: json, err = cdc.MarshalJSON(newTx.Signatures[0]) - case !sigOnly && cliCtx.Indent: + case !sigOnly && clientCtx.Indent: json, err = cdc.MarshalJSONIndent(newTx, "", " ") default: json, err = cdc.MarshalJSON(newTx) diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index dc118974a61c..c6bed8b846d7 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -73,7 +73,7 @@ func preSignCmd(cmd *cobra.Command, _ []string) { func makeSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { - cliCtx, txBldr, stdTx, err := readStdTxAndInitContexts(cdc, cmd, args[0]) + clientCtx, txBldr, stdTx, err := readStdTxAndInitContexts(cdc, cmd, args[0]) if err != nil { return err } @@ -91,19 +91,19 @@ func makeSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error return err } newTx, err = client.SignStdTxWithSignerAddress( - txBldr, cliCtx, multisigAddr, cliCtx.GetFromName(), stdTx, cliCtx.Offline, + txBldr, clientCtx, multisigAddr, clientCtx.GetFromName(), stdTx, clientCtx.Offline, ) generateSignatureOnly = true } else { appendSig := viper.GetBool(flagAppend) && !generateSignatureOnly - newTx, err = client.SignStdTx(txBldr, cliCtx, cliCtx.GetFromName(), stdTx, appendSig, cliCtx.Offline) + newTx, err = client.SignStdTx(txBldr, clientCtx, clientCtx.GetFromName(), stdTx, appendSig, clientCtx.Offline) } if err != nil { return err } - json, err := getSignatureJSON(cdc, newTx, cliCtx.Indent, generateSignatureOnly) + json, err := getSignatureJSON(cdc, newTx, clientCtx.Indent, generateSignatureOnly) if err != nil { return err } diff --git a/x/auth/client/cli/validate_sigs.go b/x/auth/client/cli/validate_sigs.go index 07846fc6e76c..c7d565c927bb 100644 --- a/x/auth/client/cli/validate_sigs.go +++ b/x/auth/client/cli/validate_sigs.go @@ -8,11 +8,11 @@ import ( "github.com/spf13/cobra" "github.com/tendermint/tendermint/crypto/multisig" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "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/client" + authclient "github.com/cosmos/cosmos-sdk/x/auth/client" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -38,12 +38,12 @@ transaction will be not be performed as that will require RPC communication with func makeValidateSignaturesCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { - cliCtx, txBldr, stdTx, err := readStdTxAndInitContexts(cdc, cmd, args[0]) + clientCtx, txBldr, stdTx, err := readStdTxAndInitContexts(cdc, cmd, args[0]) if err != nil { return err } - if !printAndValidateSigs(cmd, cliCtx, txBldr.ChainID(), stdTx, cliCtx.Offline) { + if !printAndValidateSigs(cmd, clientCtx, txBldr.ChainID(), stdTx, clientCtx.Offline) { return fmt.Errorf("signatures validation failed") } @@ -55,7 +55,7 @@ func makeValidateSignaturesCmd(cdc *codec.Codec) func(cmd *cobra.Command, args [ // expected signers. In addition, if offline has not been supplied, the signature is // verified over the transaction sign bytes. Returns false if the validation fails. func printAndValidateSigs( - cmd *cobra.Command, cliCtx context.CLIContext, chainID string, stdTx types.StdTx, offline bool, + cmd *cobra.Command, clientCtx client.Context, chainID string, stdTx types.StdTx, offline bool, ) bool { cmd.Println("Signers:") signers := stdTx.GetSigners() @@ -89,7 +89,7 @@ func printAndValidateSigs( // Validate the actual signature over the transaction bytes since we can // reach out to a full node to query accounts. if !offline && success { - acc, err := types.NewAccountRetriever(client.Codec).GetAccount(cliCtx, sigAddr) + acc, err := types.NewAccountRetriever(authclient.Codec).GetAccount(clientCtx, sigAddr) if err != nil { cmd.Printf("failed to get account: %s\n", sigAddr) return false @@ -109,7 +109,7 @@ func printAndValidateSigs( multiPK, ok := sig.GetPubKey().(multisig.PubKeyMultisigThreshold) if ok { var multiSig multisig.Multisignature - cliCtx.Codec.MustUnmarshalBinaryBare(sig.Signature, &multiSig) + clientCtx.Codec.MustUnmarshalBinaryBare(sig.Signature, &multiSig) var b strings.Builder b.WriteString("\n MultiSig Signatures:\n") @@ -134,16 +134,16 @@ func printAndValidateSigs( } func readStdTxAndInitContexts(cdc *codec.Codec, cmd *cobra.Command, filename string) ( - context.CLIContext, types.TxBuilder, types.StdTx, error, + client.Context, types.TxBuilder, types.StdTx, error, ) { - stdTx, err := client.ReadStdTxFromFile(cdc, filename) + stdTx, err := authclient.ReadStdTxFromFile(cdc, filename) if err != nil { - return context.CLIContext{}, types.TxBuilder{}, types.StdTx{}, err + return client.Context{}, types.TxBuilder{}, types.StdTx{}, err } inBuf := bufio.NewReader(cmd.InOrStdin()) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) txBldr := types.NewTxBuilderFromCLI(inBuf) - return cliCtx, txBldr, stdTx, nil + return clientCtx, txBldr, stdTx, nil } diff --git a/x/auth/client/query.go b/x/auth/client/query.go index 85bd747bc3c5..7d5cbacb88a1 100644 --- a/x/auth/client/query.go +++ b/x/auth/client/query.go @@ -8,7 +8,7 @@ import ( ctypes "github.com/tendermint/tendermint/rpc/core/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -20,7 +20,7 @@ import ( // concatenated with an 'AND' operand. It returns a slice of Info object // containing txs and metadata. An error is returned if the query fails. // If an empty string is provided it will order txs by asc -func QueryTxsByEvents(cliCtx context.CLIContext, events []string, page, limit int, orderBy string) (*sdk.SearchTxsResult, error) { +func QueryTxsByEvents(clientCtx client.Context, events []string, page, limit int, orderBy string) (*sdk.SearchTxsResult, error) { if len(events) == 0 { return nil, errors.New("must declare at least one event to search") } @@ -36,12 +36,12 @@ func QueryTxsByEvents(cliCtx context.CLIContext, events []string, page, limit in // XXX: implement ANY query := strings.Join(events, " AND ") - node, err := cliCtx.GetNode() + node, err := clientCtx.GetNode() if err != nil { return nil, err } - prove := !cliCtx.TrustNode + prove := !clientCtx.TrustNode resTxs, err := node.TxSearch(query, prove, page, limit, orderBy) if err != nil { @@ -50,19 +50,19 @@ func QueryTxsByEvents(cliCtx context.CLIContext, events []string, page, limit in if prove { for _, tx := range resTxs.Txs { - err := ValidateTxResult(cliCtx, tx) + err := ValidateTxResult(clientCtx, tx) if err != nil { return nil, err } } } - resBlocks, err := getBlocksForTxResults(cliCtx, resTxs.Txs) + resBlocks, err := getBlocksForTxResults(clientCtx, resTxs.Txs) if err != nil { return nil, err } - txs, err := formatTxResults(cliCtx.Codec, resTxs.Txs, resBlocks) + txs, err := formatTxResults(clientCtx.Codec, resTxs.Txs, resBlocks) if err != nil { return nil, err } @@ -74,34 +74,34 @@ func QueryTxsByEvents(cliCtx context.CLIContext, events []string, page, limit in // QueryTx queries for a single transaction by a hash string in hex format. An // error is returned if the transaction does not exist or cannot be queried. -func QueryTx(cliCtx context.CLIContext, hashHexStr string) (sdk.TxResponse, error) { +func QueryTx(clientCtx client.Context, hashHexStr string) (sdk.TxResponse, error) { hash, err := hex.DecodeString(hashHexStr) if err != nil { return sdk.TxResponse{}, err } - node, err := cliCtx.GetNode() + node, err := clientCtx.GetNode() if err != nil { return sdk.TxResponse{}, err } - resTx, err := node.Tx(hash, !cliCtx.TrustNode) + resTx, err := node.Tx(hash, !clientCtx.TrustNode) if err != nil { return sdk.TxResponse{}, err } - if !cliCtx.TrustNode { - if err = ValidateTxResult(cliCtx, resTx); err != nil { + if !clientCtx.TrustNode { + if err = ValidateTxResult(clientCtx, resTx); err != nil { return sdk.TxResponse{}, err } } - resBlocks, err := getBlocksForTxResults(cliCtx, []*ctypes.ResultTx{resTx}) + resBlocks, err := getBlocksForTxResults(clientCtx, []*ctypes.ResultTx{resTx}) if err != nil { return sdk.TxResponse{}, err } - out, err := formatTxResult(cliCtx.Codec, resTx, resBlocks[resTx.Height]) + out, err := formatTxResult(clientCtx.Codec, resTx, resBlocks[resTx.Height]) if err != nil { return out, err } @@ -124,9 +124,9 @@ func formatTxResults(cdc *codec.Codec, resTxs []*ctypes.ResultTx, resBlocks map[ } // ValidateTxResult performs transaction verification. -func ValidateTxResult(cliCtx context.CLIContext, resTx *ctypes.ResultTx) error { - if !cliCtx.TrustNode { - check, err := cliCtx.Verify(resTx.Height) +func ValidateTxResult(clientCtx client.Context, resTx *ctypes.ResultTx) error { + if !clientCtx.TrustNode { + check, err := clientCtx.Verify(resTx.Height) if err != nil { return err } @@ -138,8 +138,8 @@ func ValidateTxResult(cliCtx context.CLIContext, resTx *ctypes.ResultTx) error { return nil } -func getBlocksForTxResults(cliCtx context.CLIContext, resTxs []*ctypes.ResultTx) (map[int64]*ctypes.ResultBlock, error) { - node, err := cliCtx.GetNode() +func getBlocksForTxResults(clientCtx client.Context, resTxs []*ctypes.ResultTx) (map[int64]*ctypes.ResultBlock, error) { + node, err := clientCtx.GetNode() if err != nil { return nil, err } diff --git a/x/auth/client/rest.go b/x/auth/client/rest.go index e451e121b2b9..98f40786bcf6 100644 --- a/x/auth/client/rest.go +++ b/x/auth/client/rest.go @@ -4,7 +4,7 @@ import ( "log" "net/http" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/errors" @@ -13,7 +13,7 @@ import ( ) // WriteGenerateStdTxResponse writes response for the generate only mode. -func WriteGenerateStdTxResponse(w http.ResponseWriter, cliCtx context.CLIContext, br rest.BaseReq, msgs []sdk.Msg) { +func WriteGenerateStdTxResponse(w http.ResponseWriter, clientCtx client.Context, br rest.BaseReq, msgs []sdk.Msg) { gasAdj, ok := rest.ParseFloat64OrReturnBadRequest(w, br.GasAdjustment, flags.DefaultGasAdjustment) if !ok { return @@ -25,7 +25,7 @@ func WriteGenerateStdTxResponse(w http.ResponseWriter, cliCtx context.CLIContext } txBldr := types.NewTxBuilder( - GetTxEncoder(cliCtx.Codec), br.AccountNumber, br.Sequence, gas, gasAdj, + GetTxEncoder(clientCtx.Codec), br.AccountNumber, br.Sequence, gas, gasAdj, br.Simulate, br.ChainID, br.Memo, br.Fees, br.GasPrices, ) @@ -35,13 +35,13 @@ func WriteGenerateStdTxResponse(w http.ResponseWriter, cliCtx context.CLIContext return } - txBldr, err = EnrichWithGas(txBldr, cliCtx, msgs) + txBldr, err = EnrichWithGas(txBldr, clientCtx, msgs) if rest.CheckInternalServerError(w, err) { return } if br.Simulate { - rest.WriteSimulationResponse(w, cliCtx.Codec, txBldr.Gas()) + rest.WriteSimulationResponse(w, clientCtx.Codec, txBldr.Gas()) return } } @@ -51,7 +51,7 @@ func WriteGenerateStdTxResponse(w http.ResponseWriter, cliCtx context.CLIContext return } - output, err := cliCtx.Codec.MarshalJSON(types.NewStdTx(stdMsg.Msgs, stdMsg.Fee, nil, stdMsg.Memo)) + output, err := clientCtx.Codec.MarshalJSON(types.NewStdTx(stdMsg.Msgs, stdMsg.Fee, nil, stdMsg.Memo)) if rest.CheckInternalServerError(w, err) { return } diff --git a/x/auth/client/rest/broadcast.go b/x/auth/client/rest/broadcast.go index 5ce235ab1a61..1c988c58e7d0 100644 --- a/x/auth/client/rest/broadcast.go +++ b/x/auth/client/rest/broadcast.go @@ -4,7 +4,7 @@ import ( "io/ioutil" "net/http" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -18,7 +18,7 @@ type BroadcastReq struct { // BroadcastTxRequest implements a tx broadcasting handler that is responsible // for broadcasting a valid and signed tx to a full node. The tx can be // broadcasted via a sync|async|block mechanism. -func BroadcastTxRequest(cliCtx context.CLIContext) http.HandlerFunc { +func BroadcastTxRequest(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req BroadcastReq @@ -27,22 +27,22 @@ func BroadcastTxRequest(cliCtx context.CLIContext) http.HandlerFunc { return } - if err := cliCtx.Codec.UnmarshalJSON(body, &req); rest.CheckBadRequestError(w, err) { + if err := clientCtx.Codec.UnmarshalJSON(body, &req); rest.CheckBadRequestError(w, err) { return } - txBytes, err := cliCtx.Codec.MarshalBinaryBare(req.Tx) + txBytes, err := clientCtx.Codec.MarshalBinaryBare(req.Tx) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithBroadcastMode(req.Mode) + clientCtx = clientCtx.WithBroadcastMode(req.Mode) - res, err := cliCtx.BroadcastTx(txBytes) + res, err := clientCtx.BroadcastTx(txBytes) if rest.CheckInternalServerError(w, err) { return } - rest.PostProcessResponseBare(w, cliCtx, res) + rest.PostProcessResponseBare(w, clientCtx, res) } } diff --git a/x/auth/client/rest/decode.go b/x/auth/client/rest/decode.go index 2a71e83ff865..9d42d10f950a 100644 --- a/x/auth/client/rest/decode.go +++ b/x/auth/client/rest/decode.go @@ -5,7 +5,7 @@ import ( "io/ioutil" "net/http" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/types/rest" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -23,7 +23,7 @@ type ( // DecodeTxRequestHandlerFn returns the decode tx REST handler. In particular, // it takes base64-decoded bytes, decodes it from the Amino wire protocol, // and responds with a json-formatted transaction. -func DecodeTxRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func DecodeTxRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req DecodeReq @@ -32,7 +32,7 @@ func DecodeTxRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - err = cliCtx.Codec.UnmarshalJSON(body, &req) + err = clientCtx.Codec.UnmarshalJSON(body, &req) if rest.CheckBadRequestError(w, err) { return } @@ -43,12 +43,12 @@ func DecodeTxRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } var stdTx authtypes.StdTx - err = cliCtx.Codec.UnmarshalBinaryBare(txBytes, &stdTx) + err = clientCtx.Codec.UnmarshalBinaryBare(txBytes, &stdTx) if rest.CheckBadRequestError(w, err) { return } response := DecodeResp(stdTx) - rest.PostProcessResponse(w, cliCtx, response) + rest.PostProcessResponse(w, clientCtx, response) } } diff --git a/x/auth/client/rest/encode.go b/x/auth/client/rest/encode.go index 1ffebeab6066..fd1d48fc84a1 100644 --- a/x/auth/client/rest/encode.go +++ b/x/auth/client/rest/encode.go @@ -5,7 +5,7 @@ import ( "io/ioutil" "net/http" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -18,7 +18,7 @@ type EncodeResp struct { // EncodeTxRequestHandlerFn returns the encode tx REST handler. In particular, // it takes a json-formatted transaction, encodes it to the Amino wire protocol, // and responds with base64-encoded bytes. -func EncodeTxRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func EncodeTxRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req types.StdTx @@ -27,13 +27,13 @@ func EncodeTxRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - err = cliCtx.Codec.UnmarshalJSON(body, &req) + err = clientCtx.Codec.UnmarshalJSON(body, &req) if rest.CheckBadRequestError(w, err) { return } // re-encode it via the Amino wire protocol - txBytes, err := cliCtx.Codec.MarshalBinaryBare(req) + txBytes, err := clientCtx.Codec.MarshalBinaryBare(req) if rest.CheckInternalServerError(w, err) { return } @@ -42,6 +42,6 @@ func EncodeTxRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { txBytesBase64 := base64.StdEncoding.EncodeToString(txBytes) response := EncodeResp{Tx: txBytesBase64} - rest.PostProcessResponseBare(w, cliCtx, response) + rest.PostProcessResponseBare(w, clientCtx, response) } } diff --git a/x/auth/client/rest/query.go b/x/auth/client/rest/query.go index 1107fd92a817..07c440e6935d 100644 --- a/x/auth/client/rest/query.go +++ b/x/auth/client/rest/query.go @@ -8,16 +8,16 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/client" + authclient "github.com/cosmos/cosmos-sdk/x/auth/client" "github.com/cosmos/cosmos-sdk/x/auth/types" genutilrest "github.com/cosmos/cosmos-sdk/x/genutil/client/rest" ) // query accountREST Handler -func QueryAccountRequestHandlerFn(storeName string, cliCtx context.CLIContext) http.HandlerFunc { +func QueryAccountRequestHandlerFn(storeName string, clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) bech32addr := vars["address"] @@ -27,20 +27,20 @@ func QueryAccountRequestHandlerFn(storeName string, cliCtx context.CLIContext) h return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - accGetter := types.NewAccountRetriever(client.Codec) + accGetter := types.NewAccountRetriever(authclient.Codec) - account, height, err := accGetter.GetAccountWithHeight(cliCtx, addr) + account, height, err := accGetter.GetAccountWithHeight(clientCtx, addr) if err != nil { // TODO: Handle more appropriately based on the error type. // Ref: https://github.com/cosmos/cosmos-sdk/issues/4923 - if err := accGetter.EnsureExists(cliCtx, addr); err != nil { - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, types.BaseAccount{}) + if err := accGetter.EnsureExists(clientCtx, addr); err != nil { + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, types.BaseAccount{}) return } @@ -48,15 +48,15 @@ func QueryAccountRequestHandlerFn(storeName string, cliCtx context.CLIContext) h return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, account) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, account) } } // QueryTxsHandlerFn implements a REST handler that searches for transactions. // Genesis transactions are returned if the height parameter is set to zero, // otherwise the transactions are searched for by events. -func QueryTxsRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func QueryTxsRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { err := r.ParseForm() if err != nil { @@ -71,7 +71,7 @@ func QueryTxsRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { heightStr := r.FormValue("height") if heightStr != "" { if height, err := strconv.ParseInt(heightStr, 10, 64); err == nil && height == 0 { - genutilrest.QueryGenesisTxs(cliCtx, w) + genutilrest.QueryGenesisTxs(clientCtx, w) return } } @@ -82,13 +82,13 @@ func QueryTxsRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { page, limit int ) - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } if len(r.Form) == 0 { - rest.PostProcessResponseBare(w, cliCtx, txs) + rest.PostProcessResponseBare(w, clientCtx, txs) return } @@ -97,28 +97,28 @@ func QueryTxsRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - searchResult, err := client.QueryTxsByEvents(cliCtx, events, page, limit, "") + searchResult, err := authclient.QueryTxsByEvents(clientCtx, events, page, limit, "") if rest.CheckInternalServerError(w, err) { return } - rest.PostProcessResponseBare(w, cliCtx, searchResult) + rest.PostProcessResponseBare(w, clientCtx, searchResult) } } // QueryTxRequestHandlerFn implements a REST handler that queries a transaction // by hash in a committed block. -func QueryTxRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func QueryTxRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) hashHexStr := vars["hash"] - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - output, err := client.QueryTx(cliCtx, hashHexStr) + output, err := authclient.QueryTx(clientCtx, hashHexStr) if err != nil { if strings.Contains(err.Error(), hashHexStr) { rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) @@ -132,24 +132,24 @@ func QueryTxRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { rest.WriteErrorResponse(w, http.StatusNotFound, fmt.Sprintf("no transaction found with hash %s", hashHexStr)) } - rest.PostProcessResponseBare(w, cliCtx, output) + rest.PostProcessResponseBare(w, clientCtx, output) } } -func queryParamsHandler(cliCtx context.CLIContext) http.HandlerFunc { +func queryParamsHandler(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParams) - res, height, err := cliCtx.QueryWithData(route, nil) + res, height, err := clientCtx.QueryWithData(route, nil) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } diff --git a/x/auth/client/rest/rest.go b/x/auth/client/rest/rest.go index e69388dc41a4..d3106edca229 100644 --- a/x/auth/client/rest/rest.go +++ b/x/auth/client/rest/rest.go @@ -3,7 +3,7 @@ package rest import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" ) // REST query and parameter values @@ -12,22 +12,22 @@ const ( ) // RegisterRoutes registers the auth module REST routes. -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, storeName string) { +func RegisterRoutes(clientCtx client.Context, r *mux.Router, storeName string) { r.HandleFunc( - "/auth/accounts/{address}", QueryAccountRequestHandlerFn(storeName, cliCtx), + "/auth/accounts/{address}", QueryAccountRequestHandlerFn(storeName, clientCtx), ).Methods(MethodGet) r.HandleFunc( "/auth/params", - queryParamsHandler(cliCtx), + queryParamsHandler(clientCtx), ).Methods(MethodGet) } // RegisterTxRoutes registers all transaction routes on the provided router. -func RegisterTxRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/txs/{hash}", QueryTxRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/txs", QueryTxsRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/txs", BroadcastTxRequest(cliCtx)).Methods("POST") - r.HandleFunc("/txs/encode", EncodeTxRequestHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc("/txs/decode", DecodeTxRequestHandlerFn(cliCtx)).Methods("POST") +func RegisterTxRoutes(clientCtx client.Context, r *mux.Router) { + r.HandleFunc("/txs/{hash}", QueryTxRequestHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc("/txs", QueryTxsRequestHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc("/txs", BroadcastTxRequest(clientCtx)).Methods("POST") + r.HandleFunc("/txs/encode", EncodeTxRequestHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc("/txs/decode", DecodeTxRequestHandlerFn(clientCtx)).Methods("POST") } diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index 82b47082d56c..a503854e7594 100644 --- a/x/auth/client/tx.go +++ b/x/auth/client/tx.go @@ -12,7 +12,7 @@ import ( "github.com/pkg/errors" "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/input" "github.com/cosmos/cosmos-sdk/codec" @@ -43,12 +43,12 @@ 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 authtypes.TxBuilder, msgs []sdk.Msg) error { - if cliCtx.GenerateOnly { - return PrintUnsignedStdTx(txBldr, cliCtx, msgs) +func GenerateOrBroadcastMsgs(clientCtx client.Context, txBldr authtypes.TxBuilder, msgs []sdk.Msg) error { + if clientCtx.GenerateOnly { + return PrintUnsignedStdTx(txBldr, clientCtx, msgs) } - return CompleteAndBroadcastTxCLI(txBldr, cliCtx, msgs) + return CompleteAndBroadcastTxCLI(txBldr, clientCtx, msgs) } // CompleteAndBroadcastTxCLI implements a utility function that facilitates @@ -56,16 +56,16 @@ func GenerateOrBroadcastMsgs(cliCtx context.CLIContext, txBldr authtypes.TxBuild // 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 authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) error { - txBldr, err := PrepareTxBuilder(txBldr, cliCtx) +func CompleteAndBroadcastTxCLI(txBldr authtypes.TxBuilder, clientCtx client.Context, msgs []sdk.Msg) error { + txBldr, err := PrepareTxBuilder(txBldr, clientCtx) if err != nil { return err } - fromName := cliCtx.GetFromName() + fromName := clientCtx.GetFromName() - if txBldr.SimulateAndExecute() || cliCtx.Simulate { - txBldr, err = EnrichWithGas(txBldr, cliCtx, msgs) + if txBldr.SimulateAndExecute() || clientCtx.Simulate { + txBldr, err = EnrichWithGas(txBldr, clientCtx, msgs) if err != nil { return err } @@ -74,11 +74,11 @@ func CompleteAndBroadcastTxCLI(txBldr authtypes.TxBuilder, cliCtx context.CLICon _, _ = fmt.Fprintf(os.Stderr, "%s\n", gasEst.String()) } - if cliCtx.Simulate { + if clientCtx.Simulate { return nil } - if !cliCtx.SkipConfirm { + if !clientCtx.SkipConfirm { stdSignMsg, err := txBldr.BuildSignMsg(msgs) if err != nil { return err @@ -86,12 +86,12 @@ func CompleteAndBroadcastTxCLI(txBldr authtypes.TxBuilder, cliCtx context.CLICon var json []byte if viper.GetBool(flags.FlagIndentResponse) { - json, err = cliCtx.Codec.MarshalJSONIndent(stdSignMsg, "", " ") + json, err = clientCtx.Codec.MarshalJSONIndent(stdSignMsg, "", " ") if err != nil { panic(err) } } else { - json = cliCtx.Codec.MustMarshalJSON(stdSignMsg) + json = clientCtx.Codec.MustMarshalJSON(stdSignMsg) } _, _ = fmt.Fprintf(os.Stderr, "%s\n\n", json) @@ -111,18 +111,18 @@ func CompleteAndBroadcastTxCLI(txBldr authtypes.TxBuilder, cliCtx context.CLICon } // broadcast to a Tendermint node - res, err := cliCtx.BroadcastTx(txBytes) + res, err := clientCtx.BroadcastTx(txBytes) if err != nil { return err } - return cliCtx.PrintOutput(res) + return clientCtx.PrintOutput(res) } // EnrichWithGas calculates the gas estimate that would be consumed by the // transaction and set the transaction's respective value accordingly. -func EnrichWithGas(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (authtypes.TxBuilder, error) { - _, adjusted, err := simulateMsgs(txBldr, cliCtx, msgs) +func EnrichWithGas(txBldr authtypes.TxBuilder, clientCtx client.Context, msgs []sdk.Msg) (authtypes.TxBuilder, error) { + _, adjusted, err := simulateMsgs(txBldr, clientCtx, msgs) if err != nil { return txBldr, err } @@ -154,23 +154,23 @@ func CalculateGas( } // PrintUnsignedStdTx builds an unsigned StdTx and prints it to os.Stdout. -func PrintUnsignedStdTx(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) error { - stdTx, err := buildUnsignedStdTxOffline(txBldr, cliCtx, msgs) +func PrintUnsignedStdTx(txBldr authtypes.TxBuilder, clientCtx client.Context, msgs []sdk.Msg) error { + stdTx, err := buildUnsignedStdTxOffline(txBldr, clientCtx, msgs) if err != nil { return err } var json []byte if viper.GetBool(flags.FlagIndentResponse) { - json, err = cliCtx.Codec.MarshalJSONIndent(stdTx, "", " ") + json, err = clientCtx.Codec.MarshalJSONIndent(stdTx, "", " ") } else { - json, err = cliCtx.Codec.MarshalJSON(stdTx) + json, err = clientCtx.Codec.MarshalJSON(stdTx) } if err != nil { return err } - _, _ = fmt.Fprintf(cliCtx.Output, "%s\n", json) + _, _ = fmt.Fprintf(clientCtx.Output, "%s\n", json) return nil } @@ -178,7 +178,7 @@ func PrintUnsignedStdTx(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, m // 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 authtypes.TxBuilder, cliCtx context.CLIContext, name string, + txBldr authtypes.TxBuilder, clientCtx client.Context, name string, stdTx authtypes.StdTx, appendSig bool, offline bool, ) (authtypes.StdTx, error) { @@ -197,7 +197,7 @@ func SignStdTx( } if !offline { - txBldr, err = populateAccountFromState(txBldr, cliCtx, sdk.AccAddress(addr)) + txBldr, err = populateAccountFromState(txBldr, clientCtx, sdk.AccAddress(addr)) if err != nil { return signedStdTx, err } @@ -210,7 +210,7 @@ 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 authtypes.TxBuilder, cliCtx context.CLIContext, + txBldr authtypes.TxBuilder, clientCtx client.Context, addr sdk.AccAddress, name string, stdTx authtypes.StdTx, offline bool, ) (signedStdTx authtypes.StdTx, err error) { @@ -220,7 +220,7 @@ func SignStdTxWithSignerAddress( } if !offline { - txBldr, err = populateAccountFromState(txBldr, cliCtx, addr) + txBldr, err = populateAccountFromState(txBldr, clientCtx, addr) if err != nil { return signedStdTx, err } @@ -251,10 +251,10 @@ func ReadStdTxFromFile(cdc *codec.Codec, filename string) (stdTx authtypes.StdTx } func populateAccountFromState( - txBldr authtypes.TxBuilder, cliCtx context.CLIContext, addr sdk.AccAddress, + txBldr authtypes.TxBuilder, clientCtx client.Context, addr sdk.AccAddress, ) (authtypes.TxBuilder, error) { - num, seq, err := authtypes.NewAccountRetriever(Codec).GetAccountNumberSequence(cliCtx, addr) + num, seq, err := authtypes.NewAccountRetriever(Codec).GetAccountNumberSequence(clientCtx, addr) if err != nil { return txBldr, err } @@ -275,13 +275,13 @@ func GetTxEncoder(cdc *codec.Codec) (encoder sdk.TxEncoder) { // simulateMsgs simulates the transaction and returns the simulation response and // the adjusted gas value. -func simulateMsgs(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (sdk.SimulationResponse, uint64, error) { +func simulateMsgs(txBldr authtypes.TxBuilder, clientCtx client.Context, msgs []sdk.Msg) (sdk.SimulationResponse, uint64, error) { txBytes, err := txBldr.BuildTxForSim(msgs) if err != nil { return sdk.SimulationResponse{}, 0, err } - return CalculateGas(cliCtx.QueryWithData, cliCtx.Codec, txBytes, txBldr.GasAdjustment()) + return CalculateGas(clientCtx.QueryWithData, clientCtx.Codec, txBytes, txBldr.GasAdjustment()) } func adjustGasEstimate(estimate uint64, adjustment float64) uint64 { @@ -298,11 +298,11 @@ func parseQueryResponse(bz []byte) (sdk.SimulationResponse, error) { } // PrepareTxBuilder populates a TxBuilder in preparation for the build of a Tx. -func PrepareTxBuilder(txBldr authtypes.TxBuilder, cliCtx context.CLIContext) (authtypes.TxBuilder, error) { - from := cliCtx.GetFromAddress() +func PrepareTxBuilder(txBldr authtypes.TxBuilder, clientCtx client.Context) (authtypes.TxBuilder, error) { + from := clientCtx.GetFromAddress() accGetter := authtypes.NewAccountRetriever(Codec) - if err := accGetter.EnsureExists(cliCtx, from); err != nil { + if err := accGetter.EnsureExists(clientCtx, from); err != nil { return txBldr, err } @@ -310,7 +310,7 @@ func PrepareTxBuilder(txBldr authtypes.TxBuilder, cliCtx context.CLIContext) (au // TODO: (ref #1903) Allow for user supplied account number without // automatically doing a manual lookup. if txbldrAccNum == 0 || txbldrAccSeq == 0 { - num, seq, err := authtypes.NewAccountRetriever(Codec).GetAccountNumberSequence(cliCtx, from) + num, seq, err := authtypes.NewAccountRetriever(Codec).GetAccountNumberSequence(clientCtx, from) if err != nil { return txBldr, err } @@ -326,13 +326,13 @@ func PrepareTxBuilder(txBldr authtypes.TxBuilder, cliCtx context.CLIContext) (au return txBldr, nil } -func buildUnsignedStdTxOffline(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (stdTx authtypes.StdTx, err error) { +func buildUnsignedStdTxOffline(txBldr authtypes.TxBuilder, clientCtx client.Context, msgs []sdk.Msg) (stdTx authtypes.StdTx, err error) { if txBldr.SimulateAndExecute() { - if cliCtx.Offline { + if clientCtx.Offline { return stdTx, errors.New("cannot estimate gas in offline mode") } - txBldr, err = EnrichWithGas(txBldr, cliCtx, msgs) + txBldr, err = EnrichWithGas(txBldr, clientCtx, msgs) if err != nil { return stdTx, err } diff --git a/x/auth/module.go b/x/auth/module.go index 4b7eac343cf4..8ec50779d76c 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -9,7 +9,7 @@ import ( "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -58,13 +58,13 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessag } // RegisterRESTRoutes registers the REST routes for the auth module. -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { - rest.RegisterRoutes(ctx, rtr, authtypes.StoreKey) +func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { + rest.RegisterRoutes(clientCtx, rtr, authtypes.StoreKey) } // GetTxCmd returns the root tx command for the auth module. -func (AppModuleBasic) GetTxCmd(ctx context.CLIContext) *cobra.Command { - return cli.GetTxCmd(ctx.Codec) +func (AppModuleBasic) GetTxCmd(clientCtx client.Context) *cobra.Command { + return cli.GetTxCmd(clientCtx.Codec) } // GetQueryCmd returns the root query command for the auth module. diff --git a/x/auth/types/account_retriever.go b/x/auth/types/account_retriever.go index 90884b0a6017..ec7464f6c4d8 100644 --- a/x/auth/types/account_retriever.go +++ b/x/auth/types/account_retriever.go @@ -3,7 +3,7 @@ package types import ( "fmt" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -21,7 +21,7 @@ func NewAccountRetriever(codec codec.Marshaler) AccountRetriever { // GetAccount queries for an account given an address and a block height. An // error is returned if the query or decoding fails. -func (ar AccountRetriever) GetAccount(querier context.NodeQuerier, addr sdk.AccAddress) (AccountI, error) { +func (ar AccountRetriever) GetAccount(querier client.NodeQuerier, addr sdk.AccAddress) (AccountI, error) { account, _, err := ar.GetAccountWithHeight(querier, addr) return account, err } @@ -29,7 +29,7 @@ func (ar AccountRetriever) GetAccount(querier context.NodeQuerier, addr sdk.AccA // GetAccountWithHeight queries for an account given an address. Returns the // height of the query with the account. An error is returned if the query // or decoding fails. -func (ar AccountRetriever) GetAccountWithHeight(querier context.NodeQuerier, addr sdk.AccAddress) (AccountI, int64, error) { +func (ar AccountRetriever) GetAccountWithHeight(querier client.NodeQuerier, addr sdk.AccAddress) (AccountI, int64, error) { bs, err := ar.codec.MarshalJSON(NewQueryAccountParams(addr)) if err != nil { return nil, 0, err @@ -49,7 +49,7 @@ func (ar AccountRetriever) GetAccountWithHeight(querier context.NodeQuerier, add } // EnsureExists returns an error if no account exists for the given address else nil. -func (ar AccountRetriever) EnsureExists(querier context.NodeQuerier, addr sdk.AccAddress) error { +func (ar AccountRetriever) EnsureExists(querier client.NodeQuerier, addr sdk.AccAddress) error { if _, err := ar.GetAccount(querier, addr); err != nil { return err } @@ -58,7 +58,7 @@ func (ar AccountRetriever) EnsureExists(querier context.NodeQuerier, addr sdk.Ac // GetAccountNumberSequence returns sequence and account number for the given address. // It returns an error if the account couldn't be retrieved from the state. -func (ar AccountRetriever) GetAccountNumberSequence(nodeQuerier context.NodeQuerier, addr sdk.AccAddress) (uint64, uint64, error) { +func (ar AccountRetriever) GetAccountNumberSequence(nodeQuerier client.NodeQuerier, addr sdk.AccAddress) (uint64, uint64, error) { acc, err := ar.GetAccount(nodeQuerier, addr) if err != nil { return 0, 0, err diff --git a/x/auth/types/client_tx.go b/x/auth/types/client_tx.go index ccc0618f064c..0dcbe3ffc7d2 100644 --- a/x/auth/types/client_tx.go +++ b/x/auth/types/client_tx.go @@ -3,7 +3,7 @@ package types import ( "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -13,7 +13,7 @@ type StdTxBuilder struct { StdTx } -var _ context.TxBuilder = &StdTxBuilder{} +var _ client.TxBuilder = &StdTxBuilder{} // GetTx implements TxBuilder.GetTx func (s *StdTxBuilder) GetTx() sdk.Tx { @@ -36,7 +36,7 @@ func (s StdTxBuilder) GetSignatures() []sdk.Signature { } // SetSignatures implements TxBuilder.SetSignatures -func (s *StdTxBuilder) SetSignatures(signatures ...context.ClientSignature) error { +func (s *StdTxBuilder) SetSignatures(signatures ...client.Signature) error { sigs := make([]StdSignature, len(signatures)) for i, sig := range signatures { pubKey := sig.GetPubKey() @@ -59,7 +59,7 @@ func (s StdTxBuilder) GetFee() sdk.Fee { } // SetFee implements TxBuilder.SetFee -func (s *StdTxBuilder) SetFee(fee context.ClientFee) error { +func (s *StdTxBuilder) SetFee(fee client.Fee) error { s.Fee = StdFee{Amount: fee.GetAmount(), Gas: fee.GetGas()} return nil } @@ -79,20 +79,20 @@ type StdTxGenerator struct { Cdc *codec.Codec } -var _ context.TxGenerator = StdTxGenerator{} +var _ client.TxGenerator = StdTxGenerator{} // NewTx implements TxGenerator.NewTx -func (s StdTxGenerator) NewTx() context.TxBuilder { +func (s StdTxGenerator) NewTx() client.TxBuilder { return &StdTxBuilder{} } // NewFee implements TxGenerator.NewFee -func (s StdTxGenerator) NewFee() context.ClientFee { +func (s StdTxGenerator) NewFee() client.Fee { return &StdFee{} } // NewSignature implements TxGenerator.NewSignature -func (s StdTxGenerator) NewSignature() context.ClientSignature { +func (s StdTxGenerator) NewSignature() client.Signature { return &StdSignature{} } @@ -101,27 +101,27 @@ func (s StdTxGenerator) MarshalTx(tx sdk.Tx) ([]byte, error) { return DefaultTxEncoder(s.Cdc)(tx) } -var _ context.ClientFee = &StdFee{} +var _ client.Fee = &StdFee{} -// SetGas implements ClientFee.SetGas +// SetGas implements Fee.SetGas func (fee *StdFee) SetGas(gas uint64) { fee.Gas = gas } -// SetAmount implements ClientFee.SetAmount +// SetAmount implements Fee.SetAmount func (fee *StdFee) SetAmount(coins sdk.Coins) { fee.Amount = coins } -var _ context.ClientSignature = &StdSignature{} +var _ client.Signature = &StdSignature{} -// SetPubKey implements ClientSignature.SetPubKey +// SetPubKey implements Signature.SetPubKey func (ss *StdSignature) SetPubKey(key crypto.PubKey) error { ss.PubKey = key.Bytes() return nil } -// SetSignature implements ClientSignature.SetSignature +// SetSignature implements Signature.SetSignature func (ss *StdSignature) SetSignature(bytes []byte) { ss.Signature = bytes } diff --git a/x/bank/client/cli/query.go b/x/bank/client/cli/query.go index ae5ed39d13d4..03378be26544 100644 --- a/x/bank/client/cli/query.go +++ b/x/bank/client/cli/query.go @@ -8,7 +8,6 @@ import ( "github.com/spf13/viper" "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" @@ -58,7 +57,7 @@ func GetBalancesCmd(cdc *codec.Codec) *cobra.Command { Short: "Query for account balances by address", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) addr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -85,7 +84,7 @@ func GetBalancesCmd(cdc *codec.Codec) *cobra.Command { return fmt.Errorf("failed to marshal params: %w", err) } - res, _, err := cliCtx.QueryWithData(route, bz) + res, _, err := clientCtx.QueryWithData(route, bz) if err != nil { return err } @@ -106,7 +105,7 @@ func GetBalancesCmd(cdc *codec.Codec) *cobra.Command { result = balance } - return cliCtx.PrintOutput(result) + return clientCtx.PrintOutput(result) }, } @@ -136,13 +135,13 @@ $ %s query %s total stake ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) if len(args) == 0 { - return queryTotalSupply(cliCtx, cdc) + return queryTotalSupply(clientCtx, cdc) } - return querySupplyOf(cliCtx, cdc, args[0]) + return querySupplyOf(clientCtx, cdc, args[0]) }, } diff --git a/x/bank/client/cli/tx.go b/x/bank/client/cli/tx.go index f0ddf275e033..8ad3b8057343 100644 --- a/x/bank/client/cli/tx.go +++ b/x/bank/client/cli/tx.go @@ -4,7 +4,6 @@ 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/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" @@ -12,7 +11,7 @@ import ( ) // NewTxCmd returns a root CLI command handler for all x/bank transaction commands. -func NewTxCmd(cliCtx context.CLIContext) *cobra.Command { +func NewTxCmd(clientCtx client.Context) *cobra.Command { txCmd := &cobra.Command{ Use: types.ModuleName, Short: "Bank transaction subcommands", @@ -21,19 +20,19 @@ func NewTxCmd(cliCtx context.CLIContext) *cobra.Command { RunE: client.ValidateCmd, } - txCmd.AddCommand(NewSendTxCmd(cliCtx)) + txCmd.AddCommand(NewSendTxCmd(clientCtx)) return txCmd } // NewSendTxCmd returns a CLI command handler for creating a MsgSend transaction. -func NewSendTxCmd(cliCtx context.CLIContext) *cobra.Command { +func NewSendTxCmd(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "send [from_key_or_address] [to_address] [amount]", Short: "Create and/or sign and broadcast a MsgSend transaction", Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx = cliCtx.InitWithInputAndFrom(cmd.InOrStdin(), args[0]) + clientCtx = clientCtx.InitWithInputAndFrom(cmd.InOrStdin(), args[0]) toAddr, err := sdk.AccAddressFromBech32(args[1]) if err != nil { @@ -45,12 +44,12 @@ func NewSendTxCmd(cliCtx context.CLIContext) *cobra.Command { return err } - msg := types.NewMsgSend(cliCtx.GetFromAddress(), toAddr, coins) + msg := types.NewMsgSend(clientCtx.GetFromAddress(), toAddr, coins) if err := msg.ValidateBasic(); err != nil { return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } diff --git a/x/bank/client/cli/util.go b/x/bank/client/cli/util.go index 65c7c02d8b36..c2b68accd2c6 100644 --- a/x/bank/client/cli/util.go +++ b/x/bank/client/cli/util.go @@ -3,20 +3,20 @@ package cli import ( "fmt" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/bank/types" ) -func queryTotalSupply(cliCtx context.CLIContext, cdc *codec.Codec) error { +func queryTotalSupply(clientCtx client.Context, cdc *codec.Codec) error { params := types.NewQueryTotalSupplyParams(1, 0) // no pagination bz, err := cdc.MarshalJSON(params) if err != nil { return err } - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryTotalSupply), bz) + res, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryTotalSupply), bz) if err != nil { return err } @@ -27,17 +27,17 @@ func queryTotalSupply(cliCtx context.CLIContext, cdc *codec.Codec) error { return err } - return cliCtx.PrintOutput(totalSupply) + return clientCtx.PrintOutput(totalSupply) } -func querySupplyOf(cliCtx context.CLIContext, cdc *codec.Codec, denom string) error { +func querySupplyOf(clientCtx client.Context, cdc *codec.Codec, denom string) error { params := types.NewQuerySupplyOfParams(denom) bz, err := cdc.MarshalJSON(params) if err != nil { return err } - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySupplyOf), bz) + res, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySupplyOf), bz) if err != nil { return err } @@ -48,5 +48,5 @@ func querySupplyOf(cliCtx context.CLIContext, cdc *codec.Codec, denom string) er return err } - return cliCtx.PrintOutput(supply) + return clientCtx.PrintOutput(supply) } diff --git a/x/bank/client/rest/query.go b/x/bank/client/rest/query.go index aec6ed7be528..55ddb6338fd0 100644 --- a/x/bank/client/rest/query.go +++ b/x/bank/client/rest/query.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" @@ -15,7 +15,7 @@ import ( // QueryBalancesRequestHandlerFn returns a REST handler that queries for all // account balances or a specific balance by denomination. -func QueryBalancesRequestHandlerFn(ctx context.CLIContext) http.HandlerFunc { +func QueryBalancesRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") @@ -27,7 +27,7 @@ func QueryBalancesRequestHandlerFn(ctx context.CLIContext) http.HandlerFunc { return } - ctx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, ctx, r) + ctx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } @@ -72,58 +72,58 @@ func QueryBalancesRequestHandlerFn(ctx context.CLIContext) http.HandlerFunc { } // HTTP request handler to query the total supply of coins -func totalSupplyHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func totalSupplyHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { _, page, limit, err := rest.ParseHTTPArgsWithLimit(r, 0) if rest.CheckBadRequestError(w, err) { return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQueryTotalSupplyParams(page, limit) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryTotalSupply), bz) + res, height, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryTotalSupply), bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } // HTTP request handler to query the supply of a single denom -func supplyOfHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func supplyOfHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { denom := mux.Vars(r)["denom"] - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQuerySupplyOfParams(denom) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySupplyOf), bz) + res, height, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySupplyOf), bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } diff --git a/x/bank/client/rest/rest.go b/x/bank/client/rest/rest.go index 28bdec6907b6..9ef91b82adca 100644 --- a/x/bank/client/rest/rest.go +++ b/x/bank/client/rest/rest.go @@ -3,16 +3,16 @@ package rest import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" ) // RegisterHandlers registers all x/bank transaction and query HTTP REST handlers // on the provided mux router. -func RegisterHandlers(ctx context.CLIContext, r *mux.Router) { - r.HandleFunc("/bank/accounts/{address}/transfers", NewSendRequestHandlerFn(ctx)).Methods("POST") - r.HandleFunc("/bank/balances/{address}", QueryBalancesRequestHandlerFn(ctx)).Methods("GET") - r.HandleFunc("/bank/total", totalSupplyHandlerFn(ctx)).Methods("GET") - r.HandleFunc("/bank/total/{denom}", supplyOfHandlerFn(ctx)).Methods("GET") +func RegisterHandlers(clientCtx client.Context, r *mux.Router) { + r.HandleFunc("/bank/accounts/{address}/transfers", NewSendRequestHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc("/bank/balances/{address}", QueryBalancesRequestHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc("/bank/total", totalSupplyHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc("/bank/total/{denom}", supplyOfHandlerFn(clientCtx)).Methods("GET") } // --------------------------------------------------------------------------- @@ -22,9 +22,9 @@ func RegisterHandlers(ctx context.CLIContext, r *mux.Router) { // --------------------------------------------------------------------------- // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/bank/accounts/{address}/transfers", SendRequestHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc("/bank/balances/{address}", QueryBalancesRequestHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/bank/total", totalSupplyHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/bank/total/{denom}", supplyOfHandlerFn(cliCtx)).Methods("GET") +func RegisterRoutes(clientCtx client.Context, r *mux.Router) { + r.HandleFunc("/bank/accounts/{address}/transfers", SendRequestHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc("/bank/balances/{address}", QueryBalancesRequestHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc("/bank/total", totalSupplyHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc("/bank/total/{denom}", supplyOfHandlerFn(clientCtx)).Methods("GET") } diff --git a/x/bank/client/rest/tx.go b/x/bank/client/rest/tx.go index 60202c9aa4ab..50565db3ae35 100644 --- a/x/bank/client/rest/tx.go +++ b/x/bank/client/rest/tx.go @@ -5,7 +5,7 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" @@ -21,7 +21,7 @@ type SendReq struct { // NewSendRequestHandlerFn returns an HTTP REST handler for creating a MsgSend // transaction. -func NewSendRequestHandlerFn(ctx context.CLIContext) http.HandlerFunc { +func NewSendRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) bech32Addr := vars["address"] @@ -32,7 +32,7 @@ func NewSendRequestHandlerFn(ctx context.CLIContext) http.HandlerFunc { } var req SendReq - if !rest.ReadRESTReq(w, r, ctx.JSONMarshaler, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.JSONMarshaler, &req) { return } @@ -47,7 +47,7 @@ func NewSendRequestHandlerFn(ctx context.CLIContext) http.HandlerFunc { } msg := types.NewMsgSend(fromAddr, toAddr, req.Amount) - tx.WriteGeneratedTxResponse(ctx, w, req.BaseReq, msg) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) } } @@ -61,7 +61,7 @@ func NewSendRequestHandlerFn(ctx context.CLIContext) http.HandlerFunc { // // TODO: Remove once client-side Protobuf migration has been completed. // ref: https://github.com/cosmos/cosmos-sdk/issues/5864 -func SendRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func SendRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) bech32Addr := vars["address"] @@ -72,7 +72,7 @@ func SendRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } var req SendReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -87,6 +87,6 @@ func SendRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } msg := types.NewMsgSend(fromAddr, toAddr, req.Amount) - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/bank/module.go b/x/bank/module.go index 71721fb65800..9af9d684f267 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -9,7 +9,7 @@ import ( "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -57,13 +57,13 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessag } // RegisterRESTRoutes registers the REST routes for the bank module. -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { - rest.RegisterHandlers(ctx, rtr) +func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { + rest.RegisterHandlers(clientCtx, rtr) } // GetTxCmd returns the root tx command for the bank module. -func (AppModuleBasic) GetTxCmd(ctx context.CLIContext) *cobra.Command { - return cli.NewTxCmd(ctx) +func (AppModuleBasic) GetTxCmd(clientCtx client.Context) *cobra.Command { + return cli.NewTxCmd(clientCtx) } // GetQueryCmd returns no root query command for the bank module. diff --git a/x/capability/module.go b/x/capability/module.go index 911d6921cee5..db6ae3487385 100644 --- a/x/capability/module.go +++ b/x/capability/module.go @@ -5,7 +5,7 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -62,10 +62,10 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessag } // RegisterRESTRoutes registers the capability module's REST service handlers. -func (a AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router) {} +func (a AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) {} // GetTxCmd returns the capability module's root tx command. -func (a AppModuleBasic) GetTxCmd(_ context.CLIContext) *cobra.Command { return nil } +func (a AppModuleBasic) GetTxCmd(_ client.Context) *cobra.Command { return nil } // GetQueryCmd returns the capability module's root query command. func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } diff --git a/x/crisis/client/cli/tx.go b/x/crisis/client/cli/tx.go index 2d6780a7cf21..faab5390b44c 100644 --- a/x/crisis/client/cli/tx.go +++ b/x/crisis/client/cli/tx.go @@ -4,14 +4,13 @@ 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/client/tx" "github.com/cosmos/cosmos-sdk/x/crisis/types" ) // NewTxCmd returns a root CLI command handler for all x/crisis transaction commands. -func NewTxCmd(ctx context.CLIContext) *cobra.Command { +func NewTxCmd(clientCtx client.Context) *cobra.Command { txCmd := &cobra.Command{ Use: types.ModuleName, Short: "Crisis transactions subcommands", @@ -20,22 +19,22 @@ func NewTxCmd(ctx context.CLIContext) *cobra.Command { RunE: client.ValidateCmd, } - txCmd.AddCommand(NewMsgVerifyInvariantTxCmd(ctx)) + txCmd.AddCommand(NewMsgVerifyInvariantTxCmd(clientCtx)) return txCmd } // NewMsgVerifyInvariantTxCmd returns a CLI command handler for creating a // MsgVerifyInvariant transaction. -func NewMsgVerifyInvariantTxCmd(ctx context.CLIContext) *cobra.Command { +func NewMsgVerifyInvariantTxCmd(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "invariant-broken [module-name] [invariant-route]", Short: "Submit proof that an invariant broken to halt the chain", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) - senderAddr := cliCtx.GetFromAddress() + senderAddr := clientCtx.GetFromAddress() moduleName, route := args[0], args[1] msg := types.NewMsgVerifyInvariant(senderAddr, moduleName, route) @@ -43,7 +42,7 @@ func NewMsgVerifyInvariantTxCmd(ctx context.CLIContext) *cobra.Command { return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } diff --git a/x/crisis/module.go b/x/crisis/module.go index 52393973faae..304673fc1444 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -9,7 +9,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -53,11 +53,11 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessag } // RegisterRESTRoutes registers no REST routes for the crisis module. -func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router) {} +func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) {} // GetTxCmd returns the root tx command for the crisis module. -func (b AppModuleBasic) GetTxCmd(ctx context.CLIContext) *cobra.Command { - return cli.NewTxCmd(ctx) +func (b AppModuleBasic) GetTxCmd(clientCtx client.Context) *cobra.Command { + return cli.NewTxCmd(clientCtx) } // GetQueryCmd returns no root query command for the crisis module. diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index 92af18275233..dc76ed679911 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -8,7 +8,6 @@ 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" @@ -46,10 +45,10 @@ func GetCmdQueryParams(queryRoute string, cdc *codec.Codec) *cobra.Command { Args: cobra.NoArgs, Short: "Query distribution params", RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParams) - res, _, err := cliCtx.QueryWithData(route, nil) + res, _, err := clientCtx.QueryWithData(route, nil) if err != nil { return err } @@ -59,7 +58,7 @@ func GetCmdQueryParams(queryRoute string, cdc *codec.Codec) *cobra.Command { return fmt.Errorf("failed to unmarshal params: %w", err) } - return cliCtx.PrintOutput(params) + return clientCtx.PrintOutput(params) }, } } @@ -81,7 +80,7 @@ $ %s query distribution validator-outstanding-rewards cosmosvaloper1lwjmdnks33xw ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) valAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { @@ -94,7 +93,7 @@ $ %s query distribution validator-outstanding-rewards cosmosvaloper1lwjmdnks33xw return err } - resp, _, err := cliCtx.QueryWithData( + resp, _, err := clientCtx.QueryWithData( fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryValidatorOutstandingRewards), bz, ) @@ -107,7 +106,7 @@ $ %s query distribution validator-outstanding-rewards cosmosvaloper1lwjmdnks33xw return err } - return cliCtx.PrintOutput(outstandingRewards) + return clientCtx.PrintOutput(outstandingRewards) }, } } @@ -128,21 +127,21 @@ $ %s query distribution commission cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9l ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) validatorAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err } - res, err := common.QueryValidatorCommission(cliCtx, queryRoute, validatorAddr) + res, err := common.QueryValidatorCommission(clientCtx, queryRoute, validatorAddr) if err != nil { return err } var valCom types.ValidatorAccumulatedCommission cdc.MustUnmarshalJSON(res, &valCom) - return cliCtx.PrintOutput(valCom) + return clientCtx.PrintOutput(valCom) }, } } @@ -163,7 +162,7 @@ $ %s query distribution slashes cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmq ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) validatorAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { @@ -186,14 +185,14 @@ $ %s query distribution slashes cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmq return err } - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/validator_slashes", queryRoute), bz) + res, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/validator_slashes", queryRoute), bz) if err != nil { return err } var slashes types.ValidatorSlashEvents cdc.MustUnmarshalJSON(res, &slashes) - return cliCtx.PrintOutput(slashes) + return clientCtx.PrintOutput(slashes) }, } } @@ -215,11 +214,11 @@ $ %s query distribution rewards cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) // query for rewards from a particular delegation if len(args) == 2 { - resp, _, err := common.QueryDelegationRewards(cliCtx, queryRoute, args[0], args[1]) + resp, _, err := common.QueryDelegationRewards(clientCtx, queryRoute, args[0], args[1]) if err != nil { return err } @@ -229,7 +228,7 @@ $ %s query distribution rewards cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co return fmt.Errorf("failed to unmarshal response: %w", err) } - return cliCtx.PrintOutput(result) + return clientCtx.PrintOutput(result) } delegatorAddr, err := sdk.AccAddressFromBech32(args[0]) @@ -245,7 +244,7 @@ $ %s query distribution rewards cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co // query for delegator total rewards route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorTotalRewards) - res, _, err := cliCtx.QueryWithData(route, bz) + res, _, err := clientCtx.QueryWithData(route, bz) if err != nil { return err } @@ -255,7 +254,7 @@ $ %s query distribution rewards cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co return fmt.Errorf("failed to unmarshal response: %w", err) } - return cliCtx.PrintOutput(result) + return clientCtx.PrintOutput(result) }, } } @@ -276,16 +275,16 @@ $ %s query distribution community-pool ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/community_pool", queryRoute), nil) + res, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/community_pool", queryRoute), nil) if err != nil { return err } var result sdk.DecCoins cdc.MustUnmarshalJSON(res, &result) - return cliCtx.PrintOutput(result) + return clientCtx.PrintOutput(result) }, } } diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index d050387cef85..43f6ef81d2dc 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -9,7 +9,6 @@ import ( "github.com/spf13/viper" "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/tx" sdk "github.com/cosmos/cosmos-sdk/types" @@ -31,7 +30,7 @@ const ( ) // NewTxCmd returns a root CLI command handler for all x/distribution transaction commands. -func NewTxCmd(ctx context.CLIContext) *cobra.Command { +func NewTxCmd(clientCtx client.Context) *cobra.Command { distTxCmd := &cobra.Command{ Use: types.ModuleName, Short: "Distribution transactions subcommands", @@ -41,25 +40,25 @@ func NewTxCmd(ctx context.CLIContext) *cobra.Command { } distTxCmd.AddCommand(flags.PostCommands( - NewWithdrawRewardsCmd(ctx), - NewWithdrawAllRewardsCmd(ctx), - NewSetWithdrawAddrCmd(ctx), - NewFundCommunityPoolCmd(ctx), + NewWithdrawRewardsCmd(clientCtx), + NewWithdrawAllRewardsCmd(clientCtx), + NewSetWithdrawAddrCmd(clientCtx), + NewFundCommunityPoolCmd(clientCtx), )...) return distTxCmd } -type newGenerateOrBroadcastFunc func(ctx context.CLIContext, msgs ...sdk.Msg) error +type newGenerateOrBroadcastFunc func(clientCtx client.Context, msgs ...sdk.Msg) error func newSplitAndApply( newGenerateOrBroadcast newGenerateOrBroadcastFunc, - cliCtx context.CLIContext, + clientCtx client.Context, msgs []sdk.Msg, chunkSize int, ) error { if chunkSize == 0 { - return newGenerateOrBroadcast(cliCtx, msgs...) + return newGenerateOrBroadcast(clientCtx, msgs...) } // split messages into slices of length chunkSize @@ -72,7 +71,7 @@ func newSplitAndApply( } msgChunk := msgs[i:sliceEnd] - if err := newGenerateOrBroadcast(cliCtx, msgChunk...); err != nil { + if err := newGenerateOrBroadcast(clientCtx, msgChunk...); err != nil { return err } } @@ -80,7 +79,7 @@ func newSplitAndApply( return nil } -func NewWithdrawRewardsCmd(ctx context.CLIContext) *cobra.Command { +func NewWithdrawRewardsCmd(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "withdraw-rewards [validator-addr]", Short: "Withdraw rewards from a given delegation address, and optionally withdraw validator commission if the delegation address given is a validator operator", @@ -97,9 +96,9 @@ $ %s tx distribution withdraw-rewards cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fx ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) - delAddr := cliCtx.GetFromAddress() + delAddr := clientCtx.GetFromAddress() valAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err @@ -116,14 +115,14 @@ $ %s tx distribution withdraw-rewards cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fx } } - return tx.GenerateOrBroadcastTx(cliCtx, msgs...) + return tx.GenerateOrBroadcastTx(clientCtx, msgs...) }, } cmd.Flags().Bool(flagCommission, false, "also withdraw validator's commission") return cmd } -func NewWithdrawAllRewardsCmd(ctx context.CLIContext) *cobra.Command { +func NewWithdrawAllRewardsCmd(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "withdraw-all-rewards", Short: "withdraw all delegations rewards for a delegator", @@ -138,29 +137,29 @@ $ %s tx distribution withdraw-all-rewards --from mykey ), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) - delAddr := cliCtx.GetFromAddress() + delAddr := clientCtx.GetFromAddress() // The transaction cannot be generated offline since it requires a query // to get all the validators. - if cliCtx.Offline { + if clientCtx.Offline { return fmt.Errorf("cannot generate tx in offline mode") } - msgs, err := common.WithdrawAllDelegatorRewards(cliCtx, types.QuerierRoute, delAddr) + msgs, err := common.WithdrawAllDelegatorRewards(clientCtx, types.QuerierRoute, delAddr) if err != nil { return err } chunkSize := viper.GetInt(flagMaxMessagesPerTx) - return newSplitAndApply(tx.GenerateOrBroadcastTx, cliCtx, msgs, chunkSize) + return newSplitAndApply(tx.GenerateOrBroadcastTx, clientCtx, msgs, chunkSize) }, } return cmd } -func NewSetWithdrawAddrCmd(ctx context.CLIContext) *cobra.Command { +func NewSetWithdrawAddrCmd(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "set-withdraw-addr [withdraw-addr]", Short: "change the default withdraw address for rewards associated with an address", @@ -175,9 +174,9 @@ $ %s tx distribution set-withdraw-addr cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75 ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) - delAddr := cliCtx.GetFromAddress() + delAddr := clientCtx.GetFromAddress() withdrawAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return err @@ -188,13 +187,13 @@ $ %s tx distribution set-withdraw-addr cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75 return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } return cmd } -func NewFundCommunityPoolCmd(ctx context.CLIContext) *cobra.Command { +func NewFundCommunityPoolCmd(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "community-pool-spend [proposal-file]", Args: cobra.ExactArgs(1), @@ -220,9 +219,9 @@ Where proposal.json contains: ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) - depositorAddr := cliCtx.GetFromAddress() + depositorAddr := clientCtx.GetFromAddress() amount, err := sdk.ParseCoins(args[0]) if err != nil { return err @@ -233,14 +232,14 @@ Where proposal.json contains: return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } return cmd } // GetCmdSubmitProposal implements the command to submit a community-pool-spend proposal -func GetCmdSubmitProposal(ctx context.CLIContext) *cobra.Command { +func GetCmdSubmitProposal(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "community-pool-spend [proposal-file]", Args: cobra.ExactArgs(1), @@ -266,14 +265,14 @@ Where proposal.json contains: ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) - proposal, err := ParseCommunityPoolSpendProposalJSON(ctx.JSONMarshaler, args[0]) + proposal, err := ParseCommunityPoolSpendProposalJSON(clientCtx.JSONMarshaler, args[0]) if err != nil { return err } - from := cliCtx.GetFromAddress() + from := clientCtx.GetFromAddress() amount, err := sdk.ParseCoins(proposal.Amount) if err != nil { @@ -293,24 +292,24 @@ Where proposal.json contains: return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } return cmd } -type generateOrBroadcastFunc func(context.CLIContext, []sdk.Msg) error +type generateOrBroadcastFunc func(client.Context, []sdk.Msg) error func splitAndApply( generateOrBroadcast generateOrBroadcastFunc, - cliCtx context.CLIContext, + clientCtx client.Context, msgs []sdk.Msg, chunkSize int, ) error { if chunkSize == 0 { - return generateOrBroadcast(cliCtx, msgs) + return generateOrBroadcast(clientCtx, msgs) } // split messages into slices of length chunkSize @@ -323,7 +322,7 @@ func splitAndApply( } msgChunk := msgs[i:sliceEnd] - if err := generateOrBroadcast(cliCtx, msgChunk); err != nil { + if err := generateOrBroadcast(clientCtx, msgChunk); err != nil { return err } } diff --git a/x/distribution/client/cli/tx_test.go b/x/distribution/client/cli/tx_test.go index f07478a54662..f7b1e58921e2 100644 --- a/x/distribution/client/cli/tx_test.go +++ b/x/distribution/client/cli/tx_test.go @@ -9,20 +9,20 @@ import ( "github.com/stretchr/testify/assert" "github.com/tendermint/tendermint/crypto/secp256k1" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" ) func Test_splitAndCall_NoMessages(t *testing.T) { - ctx := context.CLIContext{} + clientCtx := client.Context{} - err := splitAndApply(nil, ctx, nil, 10) + err := splitAndApply(nil, clientCtx, nil, 10) assert.NoError(t, err, "") } func Test_splitAndCall_Splitting(t *testing.T) { - ctx := context.CLIContext{} + clientCtx := client.Context{} addr := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) @@ -40,10 +40,10 @@ func Test_splitAndCall_Splitting(t *testing.T) { callCount := 0 err := splitAndApply( - func(ctx context.CLIContext, msgs []sdk.Msg) error { + func(clientCtx client.Context, msgs []sdk.Msg) error { callCount++ - assert.NotNil(t, ctx) + assert.NotNil(t, clientCtx) assert.NotNil(t, msgs) if callCount < 3 { @@ -54,7 +54,7 @@ func Test_splitAndCall_Splitting(t *testing.T) { return nil }, - ctx, msgs, chunkSize) + clientCtx, msgs, chunkSize) assert.NoError(t, err, "") assert.Equal(t, 3, callCount) diff --git a/x/distribution/client/common/common.go b/x/distribution/client/common/common.go index 06860012c8cf..ab2c267ba931 100644 --- a/x/distribution/client/common/common.go +++ b/x/distribution/client/common/common.go @@ -3,14 +3,14 @@ package common import ( "fmt" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/types" ) // QueryDelegationRewards queries a delegation rewards between a delegator and a // validator. -func QueryDelegationRewards(cliCtx context.CLIContext, queryRoute, delAddr, valAddr string) ([]byte, int64, error) { +func QueryDelegationRewards(clientCtx client.Context, queryRoute, delAddr, valAddr string) ([]byte, int64, error) { delegatorAddr, err := sdk.AccAddressFromBech32(delAddr) if err != nil { return nil, 0, err @@ -22,46 +22,46 @@ func QueryDelegationRewards(cliCtx context.CLIContext, queryRoute, delAddr, valA } params := types.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if err != nil { return nil, 0, fmt.Errorf("failed to marshal params: %w", err) } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegationRewards) - return cliCtx.QueryWithData(route, bz) + return clientCtx.QueryWithData(route, bz) } // QueryDelegatorValidators returns delegator's list of validators // it submitted delegations to. -func QueryDelegatorValidators(cliCtx context.CLIContext, queryRoute string, delegatorAddr sdk.AccAddress) ([]byte, error) { - res, _, err := cliCtx.QueryWithData( +func QueryDelegatorValidators(clientCtx client.Context, queryRoute string, delegatorAddr sdk.AccAddress) ([]byte, error) { + res, _, err := clientCtx.QueryWithData( fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorValidators), - cliCtx.Codec.MustMarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)), + clientCtx.Codec.MustMarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)), ) return res, err } // QueryValidatorCommission returns a validator's commission. -func QueryValidatorCommission(cliCtx context.CLIContext, queryRoute string, validatorAddr sdk.ValAddress) ([]byte, error) { - res, _, err := cliCtx.QueryWithData( +func QueryValidatorCommission(clientCtx client.Context, queryRoute string, validatorAddr sdk.ValAddress) ([]byte, error) { + res, _, err := clientCtx.QueryWithData( fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryValidatorCommission), - cliCtx.Codec.MustMarshalJSON(types.NewQueryValidatorCommissionParams(validatorAddr)), + clientCtx.Codec.MustMarshalJSON(types.NewQueryValidatorCommissionParams(validatorAddr)), ) return res, err } // WithdrawAllDelegatorRewards builds a multi-message slice to be used // to withdraw all delegations rewards for the given delegator. -func WithdrawAllDelegatorRewards(cliCtx context.CLIContext, queryRoute string, delegatorAddr sdk.AccAddress) ([]sdk.Msg, error) { +func WithdrawAllDelegatorRewards(clientCtx client.Context, queryRoute string, delegatorAddr sdk.AccAddress) ([]sdk.Msg, error) { // retrieve the comprehensive list of all validators which the // delegator had submitted delegations to - bz, err := QueryDelegatorValidators(cliCtx, queryRoute, delegatorAddr) + bz, err := QueryDelegatorValidators(clientCtx, queryRoute, delegatorAddr) if err != nil { return nil, err } var validators []sdk.ValAddress - if err := cliCtx.Codec.UnmarshalJSON(bz, &validators); err != nil { + if err := clientCtx.Codec.UnmarshalJSON(bz, &validators); err != nil { return nil, err } diff --git a/x/distribution/client/common/common_test.go b/x/distribution/client/common/common_test.go index ea7ed8527280..b08fde7e8004 100644 --- a/x/distribution/client/common/common_test.go +++ b/x/distribution/client/common/common_test.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/viper" "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" ) @@ -14,7 +14,7 @@ import ( func TestQueryDelegationRewardsAddrValidation(t *testing.T) { cdc := codec.New() viper.Set(flags.FlagOffline, true) - ctx := context.NewCLIContext().WithCodec(cdc) + ctx := client.NewContext().WithCodec(cdc) type args struct { delAddr string valAddr string diff --git a/x/distribution/client/rest/query.go b/x/distribution/client/rest/query.go index 4f0c203ee721..f3a889a946cd 100644 --- a/x/distribution/client/rest/query.go +++ b/x/distribution/client/rest/query.go @@ -9,66 +9,66 @@ import ( "github.com/cosmos/cosmos-sdk/x/distribution/client/common" "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" ) -func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) { +func registerQueryRoutes(clientCtx client.Context, r *mux.Router) { // Get the total rewards balance from all delegations r.HandleFunc( "/distribution/delegators/{delegatorAddr}/rewards", - delegatorRewardsHandlerFn(cliCtx), + delegatorRewardsHandlerFn(clientCtx), ).Methods("GET") // Query a delegation reward r.HandleFunc( "/distribution/delegators/{delegatorAddr}/rewards/{validatorAddr}", - delegationRewardsHandlerFn(cliCtx), + delegationRewardsHandlerFn(clientCtx), ).Methods("GET") // Get the rewards withdrawal address r.HandleFunc( "/distribution/delegators/{delegatorAddr}/withdraw_address", - delegatorWithdrawalAddrHandlerFn(cliCtx), + delegatorWithdrawalAddrHandlerFn(clientCtx), ).Methods("GET") // Validator distribution information r.HandleFunc( "/distribution/validators/{validatorAddr}", - validatorInfoHandlerFn(cliCtx), + validatorInfoHandlerFn(clientCtx), ).Methods("GET") // Commission and self-delegation rewards of a single a validator r.HandleFunc( "/distribution/validators/{validatorAddr}/rewards", - validatorRewardsHandlerFn(cliCtx), + validatorRewardsHandlerFn(clientCtx), ).Methods("GET") // Outstanding rewards of a single validator r.HandleFunc( "/distribution/validators/{validatorAddr}/outstanding_rewards", - outstandingRewardsHandlerFn(cliCtx), + outstandingRewardsHandlerFn(clientCtx), ).Methods("GET") // Get the current distribution parameter values r.HandleFunc( "/distribution/parameters", - paramsHandlerFn(cliCtx), + paramsHandlerFn(clientCtx), ).Methods("GET") // Get the amount held in the community pool r.HandleFunc( "/distribution/community_pool", - communityPoolHandler(cliCtx), + communityPoolHandler(clientCtx), ).Methods("GET") } // HTTP request handler to query the total rewards balance from all delegations -func delegatorRewardsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func delegatorRewardsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } @@ -79,27 +79,27 @@ func delegatorRewardsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } params := types.NewQueryDelegatorParams(delegatorAddr) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("failed to marshal params: %s", err)) return } route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegatorTotalRewards) - res, height, err := cliCtx.QueryWithData(route, bz) + res, height, err := clientCtx.QueryWithData(route, bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } // HTTP request handler to query a delegation rewards -func delegationRewardsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func delegationRewardsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } @@ -108,37 +108,37 @@ func delegationRewardsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { valAddr := mux.Vars(r)["validatorAddr"] // query for rewards from a particular delegation - res, height, ok := checkResponseQueryDelegationRewards(w, cliCtx, types.QuerierRoute, delAddr, valAddr) + res, height, ok := checkResponseQueryDelegationRewards(w, clientCtx, types.QuerierRoute, delAddr, valAddr) if !ok { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } // HTTP request handler to query a delegation rewards -func delegatorWithdrawalAddrHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func delegatorWithdrawalAddrHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { delegatorAddr, ok := checkDelegatorAddressVar(w, r) if !ok { return } - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - bz := cliCtx.Codec.MustMarshalJSON(types.NewQueryDelegatorWithdrawAddrParams(delegatorAddr)) - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/withdraw_addr", types.QuerierRoute), bz) + bz := clientCtx.Codec.MustMarshalJSON(types.NewQueryDelegatorWithdrawAddrParams(delegatorAddr)) + res, height, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/withdraw_addr", types.QuerierRoute), bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } @@ -161,53 +161,53 @@ func NewValidatorDistInfo(operatorAddr sdk.AccAddress, rewards sdk.DecCoins, } // HTTP request handler to query validator's distribution information -func validatorInfoHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func validatorInfoHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { valAddr, ok := checkValidatorAddressVar(w, r) if !ok { return } - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } // query commission - bz, err := common.QueryValidatorCommission(cliCtx, types.QuerierRoute, valAddr) + bz, err := common.QueryValidatorCommission(clientCtx, types.QuerierRoute, valAddr) if rest.CheckInternalServerError(w, err) { return } var commission types.ValidatorAccumulatedCommission - if rest.CheckInternalServerError(w, cliCtx.Codec.UnmarshalJSON(bz, &commission)) { + if rest.CheckInternalServerError(w, clientCtx.Codec.UnmarshalJSON(bz, &commission)) { return } // self bond rewards delAddr := sdk.AccAddress(valAddr) - bz, height, ok := checkResponseQueryDelegationRewards(w, cliCtx, types.QuerierRoute, delAddr.String(), valAddr.String()) + bz, height, ok := checkResponseQueryDelegationRewards(w, clientCtx, types.QuerierRoute, delAddr.String(), valAddr.String()) if !ok { return } var rewards sdk.DecCoins - if rest.CheckInternalServerError(w, cliCtx.Codec.UnmarshalJSON(bz, &rewards)) { + if rest.CheckInternalServerError(w, clientCtx.Codec.UnmarshalJSON(bz, &rewards)) { return } - bz, err = cliCtx.Codec.MarshalJSON(NewValidatorDistInfo(delAddr, rewards, commission)) + bz, err = clientCtx.Codec.MarshalJSON(NewValidatorDistInfo(delAddr, rewards, commission)) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, bz) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, bz) } } // HTTP request handler to query validator's commission and self-delegation rewards -func validatorRewardsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func validatorRewardsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { valAddr := mux.Vars(r)["validatorAddr"] validatorAddr, ok := checkValidatorAddressVar(w, r) @@ -215,92 +215,92 @@ func validatorRewardsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } delAddr := sdk.AccAddress(validatorAddr).String() - bz, height, ok := checkResponseQueryDelegationRewards(w, cliCtx, types.QuerierRoute, delAddr, valAddr) + bz, height, ok := checkResponseQueryDelegationRewards(w, clientCtx, types.QuerierRoute, delAddr, valAddr) if !ok { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, bz) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, bz) } } // HTTP request handler to query the distribution params values -func paramsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func paramsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParams) - res, height, err := cliCtx.QueryWithData(route, nil) + res, height, err := clientCtx.QueryWithData(route, nil) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } -func communityPoolHandler(cliCtx context.CLIContext) http.HandlerFunc { +func communityPoolHandler(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/community_pool", types.QuerierRoute), nil) + res, height, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/community_pool", types.QuerierRoute), nil) if rest.CheckInternalServerError(w, err) { return } var result sdk.DecCoins - if rest.CheckInternalServerError(w, cliCtx.Codec.UnmarshalJSON(res, &result)) { + if rest.CheckInternalServerError(w, clientCtx.Codec.UnmarshalJSON(res, &result)) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, result) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, result) } } // HTTP request handler to query the outstanding rewards -func outstandingRewardsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func outstandingRewardsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { validatorAddr, ok := checkValidatorAddressVar(w, r) if !ok { return } - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - bin := cliCtx.Codec.MustMarshalJSON(types.NewQueryValidatorOutstandingRewardsParams(validatorAddr)) - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/validator_outstanding_rewards", types.QuerierRoute), bin) + bin := clientCtx.Codec.MustMarshalJSON(types.NewQueryValidatorOutstandingRewardsParams(validatorAddr)) + res, height, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/validator_outstanding_rewards", types.QuerierRoute), bin) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } func checkResponseQueryDelegationRewards( - w http.ResponseWriter, cliCtx context.CLIContext, queryRoute, delAddr, valAddr string, + w http.ResponseWriter, clientCtx client.Context, queryRoute, delAddr, valAddr string, ) (res []byte, height int64, ok bool) { - res, height, err := common.QueryDelegationRewards(cliCtx, queryRoute, delAddr, valAddr) + res, height, err := common.QueryDelegationRewards(clientCtx, queryRoute, delAddr, valAddr) if rest.CheckInternalServerError(w, err) { return nil, 0, false } diff --git a/x/distribution/client/rest/rest.go b/x/distribution/client/rest/rest.go index a1db89d41dd1..dde615818522 100644 --- a/x/distribution/client/rest/rest.go +++ b/x/distribution/client/rest/rest.go @@ -5,7 +5,7 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" @@ -14,30 +14,30 @@ import ( govrest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" ) -func RegisterHandlers(cliCtx context.CLIContext, r *mux.Router) { - registerQueryRoutes(cliCtx, r) - registerTxHandlers(cliCtx, r) +func RegisterHandlers(clientCtx client.Context, r *mux.Router) { + registerQueryRoutes(clientCtx, r) + registerTxHandlers(clientCtx, r) } // RegisterRoutes register distribution REST routes. -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, queryRoute string) { - registerQueryRoutes(cliCtx, r) - registerTxRoutes(cliCtx, r, queryRoute) +func RegisterRoutes(clientCtx client.Context, r *mux.Router, queryRoute string) { + registerQueryRoutes(clientCtx, r) + registerTxRoutes(clientCtx, r, queryRoute) } // TODO add proto compatible Handler after x/gov migration // ProposalRESTHandler returns a ProposalRESTHandler that exposes the community pool spend REST handler with a given sub-route. -func ProposalRESTHandler(cliCtx context.CLIContext) govrest.ProposalRESTHandler { +func ProposalRESTHandler(clientCtx client.Context) govrest.ProposalRESTHandler { return govrest.ProposalRESTHandler{ SubRoute: "community_pool_spend", - Handler: postProposalHandlerFn(cliCtx), + Handler: postProposalHandlerFn(clientCtx), } } -func postProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func postProposalHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req CommunityPoolSpendProposalReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -56,6 +56,6 @@ func postProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/distribution/client/rest/tx.go b/x/distribution/client/rest/tx.go index 86d6d0d4b2be..f9c199b96912 100644 --- a/x/distribution/client/rest/tx.go +++ b/x/distribution/client/rest/tx.go @@ -5,7 +5,7 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" @@ -30,42 +30,42 @@ type ( } ) -func registerTxHandlers(cliCtx context.CLIContext, r *mux.Router) { +func registerTxHandlers(clientCtx client.Context, r *mux.Router) { // Withdraw all delegator rewards r.HandleFunc( "/distribution/delegators/{delegatorAddr}/rewards", - newWithdrawDelegatorRewardsHandlerFn(cliCtx), + newWithdrawDelegatorRewardsHandlerFn(clientCtx), ).Methods("POST") // Withdraw delegation rewards r.HandleFunc( "/distribution/delegators/{delegatorAddr}/rewards/{validatorAddr}", - newWithdrawDelegationRewardsHandlerFn(cliCtx), + newWithdrawDelegationRewardsHandlerFn(clientCtx), ).Methods("POST") // Replace the rewards withdrawal address r.HandleFunc( "/distribution/delegators/{delegatorAddr}/withdraw_address", - newSetDelegatorWithdrawalAddrHandlerFn(cliCtx), + newSetDelegatorWithdrawalAddrHandlerFn(clientCtx), ).Methods("POST") // Withdraw validator rewards and commission r.HandleFunc( "/distribution/validators/{validatorAddr}/rewards", - newWithdrawValidatorRewardsHandlerFn(cliCtx), + newWithdrawValidatorRewardsHandlerFn(clientCtx), ).Methods("POST") // Fund the community pool r.HandleFunc( "/distribution/community_pool", - newFundCommunityPoolHandlerFn(cliCtx), + newFundCommunityPoolHandlerFn(clientCtx), ).Methods("POST") } -func newWithdrawDelegatorRewardsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func newWithdrawDelegatorRewardsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req withdrawRewardsReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -80,19 +80,19 @@ func newWithdrawDelegatorRewardsHandlerFn(cliCtx context.CLIContext) http.Handle return } - msgs, err := common.WithdrawAllDelegatorRewards(cliCtx, types.QuerierRoute, delAddr) + msgs, err := common.WithdrawAllDelegatorRewards(clientCtx, types.QuerierRoute, delAddr) if rest.CheckInternalServerError(w, err) { return } - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msgs...) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msgs...) } } -func newWithdrawDelegationRewardsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func newWithdrawDelegationRewardsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req withdrawRewardsReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -117,14 +117,14 @@ func newWithdrawDelegationRewardsHandlerFn(cliCtx context.CLIContext) http.Handl return } - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) } } -func newSetDelegatorWithdrawalAddrHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func newSetDelegatorWithdrawalAddrHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req setWithdrawalAddrReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -144,14 +144,14 @@ func newSetDelegatorWithdrawalAddrHandlerFn(cliCtx context.CLIContext) http.Hand return } - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) } } -func newWithdrawValidatorRewardsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func newWithdrawValidatorRewardsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req withdrawRewardsReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -172,14 +172,14 @@ func newWithdrawValidatorRewardsHandlerFn(cliCtx context.CLIContext) http.Handle return } - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msgs...) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msgs...) } } -func newFundCommunityPoolHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func newFundCommunityPoolHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req fundCommunityPoolReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -198,7 +198,7 @@ func newFundCommunityPoolHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) } } @@ -207,44 +207,44 @@ func newFundCommunityPoolHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // // TODO: Remove once client-side Protobuf migration has been completed. // --------------------------------------------------------------------------- -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, queryRoute string) { +func registerTxRoutes(clientCtx client.Context, r *mux.Router, queryRoute string) { // Withdraw all delegator rewards r.HandleFunc( "/distribution/delegators/{delegatorAddr}/rewards", - withdrawDelegatorRewardsHandlerFn(cliCtx, queryRoute), + withdrawDelegatorRewardsHandlerFn(clientCtx, queryRoute), ).Methods("POST") // Withdraw delegation rewards r.HandleFunc( "/distribution/delegators/{delegatorAddr}/rewards/{validatorAddr}", - withdrawDelegationRewardsHandlerFn(cliCtx), + withdrawDelegationRewardsHandlerFn(clientCtx), ).Methods("POST") // Replace the rewards withdrawal address r.HandleFunc( "/distribution/delegators/{delegatorAddr}/withdraw_address", - setDelegatorWithdrawalAddrHandlerFn(cliCtx), + setDelegatorWithdrawalAddrHandlerFn(clientCtx), ).Methods("POST") // Withdraw validator rewards and commission r.HandleFunc( "/distribution/validators/{validatorAddr}/rewards", - withdrawValidatorRewardsHandlerFn(cliCtx), + withdrawValidatorRewardsHandlerFn(clientCtx), ).Methods("POST") // Fund the community pool r.HandleFunc( "/distribution/community_pool", - fundCommunityPoolHandlerFn(cliCtx), + fundCommunityPoolHandlerFn(clientCtx), ).Methods("POST") } // Withdraw delegator rewards -func withdrawDelegatorRewardsHandlerFn(cliCtx context.CLIContext, queryRoute string) http.HandlerFunc { +func withdrawDelegatorRewardsHandlerFn(clientCtx client.Context, queryRoute string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req withdrawRewardsReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -259,21 +259,21 @@ func withdrawDelegatorRewardsHandlerFn(cliCtx context.CLIContext, queryRoute str return } - msgs, err := common.WithdrawAllDelegatorRewards(cliCtx, queryRoute, delAddr) + msgs, err := common.WithdrawAllDelegatorRewards(clientCtx, queryRoute, delAddr) if rest.CheckInternalServerError(w, err) { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, msgs) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, msgs) } } // Withdraw delegation rewards -func withdrawDelegationRewardsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func withdrawDelegationRewardsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req withdrawRewardsReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -298,16 +298,16 @@ func withdrawDelegationRewardsHandlerFn(cliCtx context.CLIContext) http.HandlerF return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } // Replace the rewards withdrawal address -func setDelegatorWithdrawalAddrHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func setDelegatorWithdrawalAddrHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req setWithdrawalAddrReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -327,16 +327,16 @@ func setDelegatorWithdrawalAddrHandlerFn(cliCtx context.CLIContext) http.Handler return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } // Withdraw validator rewards and commission -func withdrawValidatorRewardsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func withdrawValidatorRewardsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req withdrawRewardsReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -357,14 +357,14 @@ func withdrawValidatorRewardsHandlerFn(cliCtx context.CLIContext) http.HandlerFu return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, msgs) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, msgs) } } -func fundCommunityPoolHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func fundCommunityPoolHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req fundCommunityPoolReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -383,7 +383,7 @@ func fundCommunityPoolHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/distribution/keeper/params.go b/x/distribution/keeper/params.go index 63d6ecedc8ba..23b4bbeb8118 100644 --- a/x/distribution/keeper/params.go +++ b/x/distribution/keeper/params.go @@ -6,8 +6,8 @@ import ( ) // GetParams returns the total set of distribution parameters. -func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { - k.paramSpace.GetParamSet(ctx, ¶ms) +func (k Keeper) GetParams(clientCtx sdk.Context) (params types.Params) { + k.paramSpace.GetParamSet(clientCtx, ¶ms) return params } diff --git a/x/distribution/module.go b/x/distribution/module.go index 1a7206ce1b7c..71a6cd2324cf 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -9,7 +9,7 @@ import ( "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -61,13 +61,13 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessag } // RegisterRESTRoutes registers the REST routes for the distribution module. -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { - rest.RegisterHandlers(ctx, rtr) +func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { + rest.RegisterHandlers(clientCtx, rtr) } // GetTxCmd returns the root tx command for the distribution module. -func (AppModuleBasic) GetTxCmd(ctx context.CLIContext) *cobra.Command { - return cli.NewTxCmd(ctx) +func (AppModuleBasic) GetTxCmd(clientCtx client.Context) *cobra.Command { + return cli.NewTxCmd(clientCtx) } // GetQueryCmd returns the root query command for the distribution module. diff --git a/x/evidence/client/cli/query.go b/x/evidence/client/cli/query.go index 36b217c62220..4eb1b4e51b74 100644 --- a/x/evidence/client/cli/query.go +++ b/x/evidence/client/cli/query.go @@ -9,7 +9,6 @@ import ( "github.com/spf13/viper" "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" "github.com/cosmos/cosmos-sdk/version" @@ -53,17 +52,17 @@ func QueryEvidenceCmd(cdc *codec.Codec) func(*cobra.Command, []string) error { return err } - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) if hash := args[0]; hash != "" { - return queryEvidence(cdc, cliCtx, hash) + return queryEvidence(cdc, clientCtx, hash) } - return queryAllEvidence(cdc, cliCtx) + return queryAllEvidence(cdc, clientCtx) } } -func queryEvidence(cdc *codec.Codec, cliCtx context.CLIContext, hash string) error { +func queryEvidence(cdc *codec.Codec, clientCtx client.Context, hash string) error { if _, err := hex.DecodeString(hash); err != nil { return fmt.Errorf("invalid evidence hash: %w", err) } @@ -75,7 +74,7 @@ func queryEvidence(cdc *codec.Codec, cliCtx context.CLIContext, hash string) err } route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryEvidence) - res, _, err := cliCtx.QueryWithData(route, bz) + res, _, err := clientCtx.QueryWithData(route, bz) if err != nil { return err } @@ -86,10 +85,10 @@ func queryEvidence(cdc *codec.Codec, cliCtx context.CLIContext, hash string) err return fmt.Errorf("failed to unmarshal evidence: %w", err) } - return cliCtx.PrintOutput(evidence) + return clientCtx.PrintOutput(evidence) } -func queryAllEvidence(cdc *codec.Codec, cliCtx context.CLIContext) error { +func queryAllEvidence(cdc *codec.Codec, clientCtx client.Context) error { params := types.NewQueryAllEvidenceParams(viper.GetInt(flags.FlagPage), viper.GetInt(flags.FlagLimit)) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -97,7 +96,7 @@ func queryAllEvidence(cdc *codec.Codec, cliCtx context.CLIContext) error { } route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAllEvidence) - res, _, err := cliCtx.QueryWithData(route, bz) + res, _, err := clientCtx.QueryWithData(route, bz) if err != nil { return err } @@ -108,5 +107,5 @@ func queryAllEvidence(cdc *codec.Codec, cliCtx context.CLIContext) error { return fmt.Errorf("failed to unmarshal evidence: %w", err) } - return cliCtx.PrintOutput(evidence) + return clientCtx.PrintOutput(evidence) } diff --git a/x/evidence/client/cli/tx.go b/x/evidence/client/cli/tx.go index 3ee0dcd963fd..3e03042c2711 100644 --- a/x/evidence/client/cli/tx.go +++ b/x/evidence/client/cli/tx.go @@ -2,7 +2,6 @@ package cli import ( "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/x/evidence/types" @@ -14,7 +13,7 @@ import ( // modules, under a sub-command. This allows external modules to implement custom // Evidence types and Handlers while having the ability to create and sign txs // containing them all from a single root command. -func GetTxCmd(ctx context.CLIContext, childCmds []*cobra.Command) *cobra.Command { +func GetTxCmd(clientCtx client.Context, childCmds []*cobra.Command) *cobra.Command { cmd := &cobra.Command{ Use: types.ModuleName, Short: "Evidence transaction subcommands", @@ -23,7 +22,7 @@ func GetTxCmd(ctx context.CLIContext, childCmds []*cobra.Command) *cobra.Command RunE: client.ValidateCmd, } - submitEvidenceCmd := SubmitEvidenceCmd(ctx) + submitEvidenceCmd := SubmitEvidenceCmd(clientCtx) for _, childCmd := range childCmds { submitEvidenceCmd.AddCommand(flags.PostCommands(childCmd)[0]) } @@ -36,7 +35,7 @@ func GetTxCmd(ctx context.CLIContext, childCmds []*cobra.Command) *cobra.Command // SubmitEvidenceCmd returns the top-level evidence submission command handler. // All concrete evidence submission child command handlers should be registered // under this command. -func SubmitEvidenceCmd(_ context.CLIContext) *cobra.Command { +func SubmitEvidenceCmd(_ client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "submit", Short: "Submit arbitrary evidence of misbehavior", diff --git a/x/evidence/client/evidence_handler.go b/x/evidence/client/evidence_handler.go index 335894a567c0..4942d14805b6 100644 --- a/x/evidence/client/evidence_handler.go +++ b/x/evidence/client/evidence_handler.go @@ -3,16 +3,16 @@ package client import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/x/evidence/client/rest" ) type ( // RESTHandlerFn defines a REST service handler for evidence submission - RESTHandlerFn func(context.CLIContext) rest.EvidenceRESTHandler + RESTHandlerFn func(client.Context) rest.EvidenceRESTHandler // CLIHandlerFn defines a CLI command handler for evidence submission - CLIHandlerFn func(context.CLIContext) *cobra.Command + CLIHandlerFn func(client.Context) *cobra.Command // EvidenceHandler defines a type that exposes REST and CLI client handlers for // evidence submission. diff --git a/x/evidence/client/rest/query.go b/x/evidence/client/rest/query.go index 784941e12f4c..5e8ed2aeeffa 100644 --- a/x/evidence/client/rest/query.go +++ b/x/evidence/client/rest/query.go @@ -5,26 +5,26 @@ import ( "net/http" "strings" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/evidence/types" "github.com/gorilla/mux" ) -func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) { +func registerQueryRoutes(clientCtx client.Context, r *mux.Router) { r.HandleFunc( fmt.Sprintf("/evidence/{%s}", RestParamEvidenceHash), - queryEvidenceHandler(cliCtx), + queryEvidenceHandler(clientCtx), ).Methods(MethodGet) r.HandleFunc( "/evidence", - queryAllEvidenceHandler(cliCtx), + queryAllEvidenceHandler(clientCtx), ).Methods(MethodGet) } -func queryEvidenceHandler(cliCtx context.CLIContext) http.HandlerFunc { +func queryEvidenceHandler(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) evidenceHash := vars[RestParamEvidenceHash] @@ -34,55 +34,55 @@ func queryEvidenceHandler(cliCtx context.CLIContext) http.HandlerFunc { return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQueryEvidenceParams(evidenceHash) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("failed to marshal query params: %s", err)) return } route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryEvidence) - res, height, err := cliCtx.QueryWithData(route, bz) + res, height, err := clientCtx.QueryWithData(route, bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } -func queryAllEvidenceHandler(cliCtx context.CLIContext) http.HandlerFunc { +func queryAllEvidenceHandler(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { _, page, limit, err := rest.ParseHTTPArgsWithLimit(r, 0) if rest.CheckBadRequestError(w, err) { return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQueryAllEvidenceParams(page, limit) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("failed to marshal query params: %s", err)) return } route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAllEvidence) - res, height, err := cliCtx.QueryWithData(route, bz) + res, height, err := clientCtx.QueryWithData(route, bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } diff --git a/x/evidence/client/rest/rest.go b/x/evidence/client/rest/rest.go index bb66afbbc073..89756eb58aa0 100644 --- a/x/evidence/client/rest/rest.go +++ b/x/evidence/client/rest/rest.go @@ -3,7 +3,7 @@ package rest import ( "net/http" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/gorilla/mux" ) @@ -24,7 +24,7 @@ type EvidenceRESTHandler struct { // RegisterRoutes registers all Evidence submission handlers for the evidence module's // REST service handler. -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, handlers []EvidenceRESTHandler) { - registerQueryRoutes(cliCtx, r) - registerTxRoutes(cliCtx, r, handlers) +func RegisterRoutes(clientCtx client.Context, r *mux.Router, handlers []EvidenceRESTHandler) { + registerQueryRoutes(clientCtx, r) + registerTxRoutes(clientCtx, r, handlers) } diff --git a/x/evidence/client/rest/tx.go b/x/evidence/client/rest/tx.go index b053e4fca6b8..0c3c0966a3d0 100644 --- a/x/evidence/client/rest/tx.go +++ b/x/evidence/client/rest/tx.go @@ -1,11 +1,11 @@ package rest import ( - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/gorilla/mux" ) -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, handlers []EvidenceRESTHandler) { +func registerTxRoutes(clientCtx client.Context, r *mux.Router, handlers []EvidenceRESTHandler) { // TODO: Register tx handlers. } diff --git a/x/evidence/module.go b/x/evidence/module.go index 6e1380985c90..ee8afdcd552c 100644 --- a/x/evidence/module.go +++ b/x/evidence/module.go @@ -5,21 +5,21 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec/types" + "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/client" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/evidence/client" + eviclient "github.com/cosmos/cosmos-sdk/x/evidence/client" "github.com/cosmos/cosmos-sdk/x/evidence/client/cli" "github.com/cosmos/cosmos-sdk/x/evidence/client/rest" "github.com/cosmos/cosmos-sdk/x/evidence/simulation" - - "github.com/gorilla/mux" - "github.com/spf13/cobra" - abci "github.com/tendermint/tendermint/abci/types" ) var ( @@ -35,11 +35,11 @@ var ( // AppModuleBasic implements the AppModuleBasic interface for the evidence module. type AppModuleBasic struct { - evidenceHandlers []client.EvidenceHandler // client evidence submission handlers + evidenceHandlers []eviclient.EvidenceHandler // eviclient evidence submission handlers } // NewAppModuleBasic crates a AppModuleBasic without the codec. -func NewAppModuleBasic(evidenceHandlers ...client.EvidenceHandler) AppModuleBasic { +func NewAppModuleBasic(evidenceHandlers ...eviclient.EvidenceHandler) AppModuleBasic { return AppModuleBasic{ evidenceHandlers: evidenceHandlers, } @@ -71,25 +71,25 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessag } // RegisterRESTRoutes registers the evidence module's REST service handlers. -func (a AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { +func (a AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { evidenceRESTHandlers := make([]rest.EvidenceRESTHandler, len(a.evidenceHandlers)) for i, evidenceHandler := range a.evidenceHandlers { - evidenceRESTHandlers[i] = evidenceHandler.RESTHandler(ctx) + evidenceRESTHandlers[i] = evidenceHandler.RESTHandler(clientCtx) } - rest.RegisterRoutes(ctx, rtr, evidenceRESTHandlers) + rest.RegisterRoutes(clientCtx, rtr, evidenceRESTHandlers) } // GetTxCmd returns the evidence module's root tx command. -func (a AppModuleBasic) GetTxCmd(ctx context.CLIContext) *cobra.Command { +func (a AppModuleBasic) GetTxCmd(clientCtx client.Context) *cobra.Command { evidenceCLIHandlers := make([]*cobra.Command, len(a.evidenceHandlers)) for i, evidenceHandler := range a.evidenceHandlers { - evidenceCLIHandlers[i] = evidenceHandler.CLIHandler(ctx) + evidenceCLIHandlers[i] = evidenceHandler.CLIHandler(clientCtx) } - return cli.GetTxCmd(ctx, evidenceCLIHandlers) + return cli.GetTxCmd(clientCtx, evidenceCLIHandlers) } // GetTxCmd returns the evidence module's root query command. diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 6b5a799043e9..5de254415358 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -19,7 +19,7 @@ import ( tmos "github.com/tendermint/tendermint/libs/os" tmtypes "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -36,7 +36,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 auth.TxBuilder) (auth.TxBuilder, sdk.Msg, error) + BuildCreateValidatorMsg(clientCtx client.Context, txBldr auth.TxBuilder) (auth.TxBuilder, sdk.Msg, error) } // GenTxCmd builds the application's gentx command. @@ -121,7 +121,7 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, sm } txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) // Set the generate-only flag here after the CLI context has // been created. This allows the from name/key to be correctly populated. @@ -131,21 +131,21 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, sm viper.Set(flags.FlagGenerateOnly, true) // create a 'create-validator' message - txBldr, msg, err := smbh.BuildCreateValidatorMsg(cliCtx, txBldr) + txBldr, msg, err := smbh.BuildCreateValidatorMsg(clientCtx, txBldr) if err != nil { return errors.Wrap(err, "failed to build create-validator message") } if key.GetType() == keyring.TypeOffline || key.GetType() == keyring.TypeMulti { cmd.PrintErrln("Offline key passed in. Use `tx sign` command to sign.") - return authclient.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg}) + return authclient.PrintUnsignedStdTx(txBldr, clientCtx, []sdk.Msg{msg}) } // write the unsigned transaction to the buffer w := bytes.NewBuffer([]byte{}) - cliCtx = cliCtx.WithOutput(w) + clientCtx = clientCtx.WithOutput(w) - if err = authclient.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg}); err != nil { + if err = authclient.PrintUnsignedStdTx(txBldr, clientCtx, []sdk.Msg{msg}); err != nil { return errors.Wrap(err, "failed to print unsigned std tx") } @@ -156,7 +156,7 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, sm } // sign the transaction and write it to the output file - signedTx, err := authclient.SignStdTx(txBldr, cliCtx, name, stdTx, false, true) + signedTx, err := authclient.SignStdTx(txBldr, clientCtx, name, stdTx, false, true) if err != nil { return errors.Wrap(err, "failed to sign std tx") } diff --git a/x/genutil/client/rest/query.go b/x/genutil/client/rest/query.go index 0159223e8e7c..dcb932be5034 100644 --- a/x/genutil/client/rest/query.go +++ b/x/genutil/client/rest/query.go @@ -4,7 +4,7 @@ import ( "fmt" "net/http" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/genutil/types" @@ -12,8 +12,8 @@ import ( // QueryGenesisTxs writes the genesis transactions to the response if no error // occurs. -func QueryGenesisTxs(cliCtx context.CLIContext, w http.ResponseWriter) { - resultGenesis, err := cliCtx.Client.Genesis() +func QueryGenesisTxs(clientCtx client.Context, w http.ResponseWriter) { + resultGenesis, err := clientCtx.Client.Genesis() if err != nil { rest.WriteErrorResponse( w, http.StatusInternalServerError, @@ -22,7 +22,7 @@ func QueryGenesisTxs(cliCtx context.CLIContext, w http.ResponseWriter) { return } - appState, err := types.GenesisStateFromGenDoc(cliCtx.Codec, *resultGenesis.Genesis) + appState, err := types.GenesisStateFromGenDoc(clientCtx.Codec, *resultGenesis.Genesis) if err != nil { rest.WriteErrorResponse( w, http.StatusInternalServerError, @@ -31,10 +31,10 @@ func QueryGenesisTxs(cliCtx context.CLIContext, w http.ResponseWriter) { return } - genState := types.GetGenesisStateFromAppState(cliCtx.Codec, appState) + genState := types.GetGenesisStateFromAppState(clientCtx.Codec, appState) genTxs := make([]sdk.Tx, len(genState.GenTxs)) for i, tx := range genState.GenTxs { - err := cliCtx.Codec.UnmarshalJSON(tx, &genTxs[i]) + err := clientCtx.Codec.UnmarshalJSON(tx, &genTxs[i]) if err != nil { rest.WriteErrorResponse( w, http.StatusInternalServerError, @@ -44,5 +44,5 @@ func QueryGenesisTxs(cliCtx context.CLIContext, w http.ResponseWriter) { } } - rest.PostProcessResponseBare(w, cliCtx, genTxs) + rest.PostProcessResponseBare(w, clientCtx, genTxs) } diff --git a/x/genutil/module.go b/x/genutil/module.go index 11fd49381b4d..f0a7d866aa17 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -9,7 +9,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -49,10 +49,10 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessag } // RegisterRESTRoutes registers the REST routes for the genutil module. -func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router) {} +func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) {} // GetTxCmd returns no root tx command for the genutil module. -func (AppModuleBasic) GetTxCmd(_ context.CLIContext) *cobra.Command { return nil } +func (AppModuleBasic) GetTxCmd(_ client.Context) *cobra.Command { return nil } // GetQueryCmd returns no root query command for the genutil module. func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index 52a238dfb48b..a064549fae3b 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -9,7 +9,6 @@ import ( "github.com/spf13/viper" "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" @@ -61,7 +60,7 @@ $ %s query gov proposal 1 ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) // validate that the proposal id is a uint proposalID, err := strconv.ParseUint(args[0], 10, 64) @@ -70,14 +69,14 @@ $ %s query gov proposal 1 } // Query the proposal - res, err := gcutils.QueryProposalByID(proposalID, cliCtx, queryRoute) + res, err := gcutils.QueryProposalByID(proposalID, clientCtx, queryRoute) if err != nil { return err } var proposal types.Proposal cdc.MustUnmarshalJSON(res, &proposal) - return cliCtx.PrintOutput(proposal) // nolint:errcheck + return clientCtx.PrintOutput(proposal) // nolint:errcheck }, } } @@ -141,9 +140,9 @@ $ %s query gov proposals --page=2 --limit=100 return err } - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/proposals", queryRoute), bz) + res, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/proposals", queryRoute), bz) if err != nil { return err } @@ -158,7 +157,7 @@ $ %s query gov proposals --page=2 --limit=100 return fmt.Errorf("no matching proposals found") } - return cliCtx.PrintOutput(matchingProposals) // nolint:errcheck + return clientCtx.PrintOutput(matchingProposals) // nolint:errcheck }, } @@ -188,7 +187,7 @@ $ %s query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) // validate that the proposal id is a uint proposalID, err := strconv.ParseUint(args[0], 10, 64) @@ -197,7 +196,7 @@ $ %s query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk } // check to see if the proposal is in the store - _, err = gcutils.QueryProposalByID(proposalID, cliCtx, queryRoute) + _, err = gcutils.QueryProposalByID(proposalID, clientCtx, queryRoute) if err != nil { return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) } @@ -213,7 +212,7 @@ $ %s query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return err } - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/vote", queryRoute), bz) + res, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/vote", queryRoute), bz) if err != nil { return err } @@ -226,7 +225,7 @@ $ %s query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk _ = cdc.UnmarshalJSON(res, &vote) if vote.Empty() { - res, err = gcutils.QueryVoteByTxQuery(cliCtx, params) + res, err = gcutils.QueryVoteByTxQuery(clientCtx, params) if err != nil { return err } @@ -236,7 +235,7 @@ $ %s query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk } } - return cliCtx.PrintOutput(vote) + return clientCtx.PrintOutput(vote) }, } } @@ -258,7 +257,7 @@ $ %[1]s query gov votes 1 --page=2 --limit=100 ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) // validate that the proposal id is a uint proposalID, err := strconv.ParseUint(args[0], 10, 64) @@ -276,7 +275,7 @@ $ %[1]s query gov votes 1 --page=2 --limit=100 } // check to see if the proposal is in the store - res, err := gcutils.QueryProposalByID(proposalID, cliCtx, queryRoute) + res, err := gcutils.QueryProposalByID(proposalID, clientCtx, queryRoute) if err != nil { return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) } @@ -286,9 +285,9 @@ $ %[1]s query gov votes 1 --page=2 --limit=100 propStatus := proposal.Status if !(propStatus == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { - res, err = gcutils.QueryVotesByTxQuery(cliCtx, params) + res, err = gcutils.QueryVotesByTxQuery(clientCtx, params) } else { - res, _, err = cliCtx.QueryWithData(fmt.Sprintf("custom/%s/votes", queryRoute), bz) + res, _, err = clientCtx.QueryWithData(fmt.Sprintf("custom/%s/votes", queryRoute), bz) } if err != nil { @@ -297,7 +296,7 @@ $ %[1]s query gov votes 1 --page=2 --limit=100 var votes types.Votes cdc.MustUnmarshalJSON(res, &votes) - return cliCtx.PrintOutput(votes) + return clientCtx.PrintOutput(votes) }, } cmd.Flags().Int(flags.FlagPage, 1, "pagination page of votes to to query for") @@ -322,7 +321,7 @@ $ %s query gov deposit 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) // validate that the proposal id is a uint proposalID, err := strconv.ParseUint(args[0], 10, 64) @@ -331,7 +330,7 @@ $ %s query gov deposit 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk } // check to see if the proposal is in the store - _, err = gcutils.QueryProposalByID(proposalID, cliCtx, queryRoute) + _, err = gcutils.QueryProposalByID(proposalID, clientCtx, queryRoute) if err != nil { return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) } @@ -347,7 +346,7 @@ $ %s query gov deposit 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return err } - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/deposit", queryRoute), bz) + res, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/deposit", queryRoute), bz) if err != nil { return err } @@ -356,14 +355,14 @@ $ %s query gov deposit 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk cdc.MustUnmarshalJSON(res, &deposit) if deposit.Empty() { - res, err = gcutils.QueryDepositByTxQuery(cliCtx, params) + res, err = gcutils.QueryDepositByTxQuery(clientCtx, params) if err != nil { return err } cdc.MustUnmarshalJSON(res, &deposit) } - return cliCtx.PrintOutput(deposit) + return clientCtx.PrintOutput(deposit) }, } } @@ -385,7 +384,7 @@ $ %s query gov deposits 1 ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) // validate that the proposal id is a uint proposalID, err := strconv.ParseUint(args[0], 10, 64) @@ -400,7 +399,7 @@ $ %s query gov deposits 1 } // check to see if the proposal is in the store - res, err := gcutils.QueryProposalByID(proposalID, cliCtx, queryRoute) + res, err := gcutils.QueryProposalByID(proposalID, clientCtx, queryRoute) if err != nil { return fmt.Errorf("failed to fetch proposal with id %d: %s", proposalID, err) } @@ -410,9 +409,9 @@ $ %s query gov deposits 1 propStatus := proposal.Status if !(propStatus == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { - res, err = gcutils.QueryDepositsByTxQuery(cliCtx, params) + res, err = gcutils.QueryDepositsByTxQuery(clientCtx, params) } else { - res, _, err = cliCtx.QueryWithData(fmt.Sprintf("custom/%s/deposits", queryRoute), bz) + res, _, err = clientCtx.QueryWithData(fmt.Sprintf("custom/%s/deposits", queryRoute), bz) } if err != nil { @@ -421,7 +420,7 @@ $ %s query gov deposits 1 var dep types.Deposits cdc.MustUnmarshalJSON(res, &dep) - return cliCtx.PrintOutput(dep) + return clientCtx.PrintOutput(dep) }, } } @@ -443,7 +442,7 @@ $ %s query gov tally 1 ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) // validate that the proposal id is a uint proposalID, err := strconv.ParseUint(args[0], 10, 64) @@ -452,7 +451,7 @@ $ %s query gov tally 1 } // check to see if the proposal is in the store - _, err = gcutils.QueryProposalByID(proposalID, cliCtx, queryRoute) + _, err = gcutils.QueryProposalByID(proposalID, clientCtx, queryRoute) if err != nil { return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) } @@ -465,14 +464,14 @@ $ %s query gov tally 1 } // Query store - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/tally", queryRoute), bz) + res, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/tally", queryRoute), bz) if err != nil { return err } var tally types.TallyResult cdc.MustUnmarshalJSON(res, &tally) - return cliCtx.PrintOutput(tally) + return clientCtx.PrintOutput(tally) }, } } @@ -493,16 +492,16 @@ $ %s query gov params ), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - tp, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/params/tallying", queryRoute), nil) + clientCtx := client.NewContext().WithCodec(cdc) + tp, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/params/tallying", queryRoute), nil) if err != nil { return err } - dp, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/params/deposit", queryRoute), nil) + dp, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/params/deposit", queryRoute), nil) if err != nil { return err } - vp, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/params/voting", queryRoute), nil) + vp, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/params/voting", queryRoute), nil) if err != nil { return err } @@ -514,7 +513,7 @@ $ %s query gov params var votingParams types.VotingParams cdc.MustUnmarshalJSON(vp, &votingParams) - return cliCtx.PrintOutput(types.NewParams(votingParams, tallyParams, depositParams)) + return clientCtx.PrintOutput(types.NewParams(votingParams, tallyParams, depositParams)) }, } } @@ -537,10 +536,10 @@ $ %s query gov param deposit ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) // Query store - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/params/%s", queryRoute, args[0]), nil) + res, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/params/%s", queryRoute, args[0]), nil) if err != nil { return err } @@ -562,7 +561,7 @@ $ %s query gov param deposit return fmt.Errorf("argument must be one of (voting|tallying|deposit), was %s", args[0]) } - return cliCtx.PrintOutput(out) + return clientCtx.PrintOutput(out) }, } } @@ -583,7 +582,7 @@ $ %s query gov proposer 1 ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) // validate that the proposalID is a uint proposalID, err := strconv.ParseUint(args[0], 10, 64) @@ -591,12 +590,12 @@ $ %s query gov proposer 1 return fmt.Errorf("proposal-id %s is not a valid uint", args[0]) } - prop, err := gcutils.QueryProposerByTxQuery(cliCtx, proposalID) + prop, err := gcutils.QueryProposerByTxQuery(clientCtx, proposalID) if err != nil { return err } - return cliCtx.PrintOutput(prop) + return clientCtx.PrintOutput(prop) }, } } diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index d36fbff83922..83ab6eecfe1f 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -8,7 +8,6 @@ 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/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" @@ -52,7 +51,7 @@ var ProposalFlags = []string{ // to proposal type handlers that are implemented in other modules but are mounted // under the governance CLI (eg. parameter change proposals). func NewTxCmd( - ctx context.CLIContext, + ctx client.Context, pcmds []*cobra.Command, ) *cobra.Command { govTxCmd := &cobra.Command{ @@ -78,7 +77,7 @@ func NewTxCmd( } // NewCmdSubmitProposal implements submitting a proposal transaction command. -func NewCmdSubmitProposal(ctx context.CLIContext) *cobra.Command { +func NewCmdSubmitProposal(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "submit-proposal", Short: "Submit a proposal along with an initial deposit", @@ -106,7 +105,7 @@ $ %s tx gov submit-proposal --title="Test Proposal" --description="My awesome pr ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) proposal, err := parseSubmitProposalFlags() if err != nil { @@ -120,7 +119,7 @@ $ %s tx gov submit-proposal --title="Test Proposal" --description="My awesome pr content := types.ContentFromProposalType(proposal.Title, proposal.Description, proposal.Type) - msg, err := types.NewMsgSubmitProposal(content, amount, cliCtx.FromAddress) + msg, err := types.NewMsgSubmitProposal(content, amount, clientCtx.FromAddress) if err != nil { return err } @@ -129,7 +128,7 @@ $ %s tx gov submit-proposal --title="Test Proposal" --description="My awesome pr return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } @@ -143,7 +142,7 @@ $ %s tx gov submit-proposal --title="Test Proposal" --description="My awesome pr } // NewCmdDeposit implements depositing tokens for an active proposal. -func NewCmdDeposit(ctx context.CLIContext) *cobra.Command { +func NewCmdDeposit(clientCtx client.Context) *cobra.Command { return &cobra.Command{ Use: "deposit [proposal-id] [deposit]", Args: cobra.ExactArgs(2), @@ -159,7 +158,7 @@ $ %s tx gov deposit 1 10stake --from mykey ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) // validate that the proposal id is a uint proposalID, err := strconv.ParseUint(args[0], 10, 64) @@ -168,7 +167,7 @@ $ %s tx gov deposit 1 10stake --from mykey } // Get depositor address - from := cliCtx.GetFromAddress() + from := clientCtx.GetFromAddress() // Get amount of coins amount, err := sdk.ParseCoins(args[1]) @@ -182,13 +181,13 @@ $ %s tx gov deposit 1 10stake --from mykey return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } } // NewCmdVote implements creating a new vote command. -func NewCmdVote(ctx context.CLIContext) *cobra.Command { +func NewCmdVote(clientCtx client.Context) *cobra.Command { return &cobra.Command{ Use: "vote [proposal-id] [option]", Args: cobra.ExactArgs(2), @@ -205,10 +204,10 @@ $ %s tx gov vote 1 yes --from mykey ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) // Get voting address - from := cliCtx.GetFromAddress() + from := clientCtx.GetFromAddress() // validate that the proposal id is a uint proposalID, err := strconv.ParseUint(args[0], 10, 64) @@ -229,7 +228,7 @@ $ %s tx gov vote 1 yes --from mykey return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } } diff --git a/x/gov/client/proposal_handler.go b/x/gov/client/proposal_handler.go index 10de527db6c3..8cac280a591e 100644 --- a/x/gov/client/proposal_handler.go +++ b/x/gov/client/proposal_handler.go @@ -3,15 +3,15 @@ package client import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/x/gov/client/rest" ) // function to create the rest handler -type RESTHandlerFn func(context.CLIContext) rest.ProposalRESTHandler +type RESTHandlerFn func(client.Context) rest.ProposalRESTHandler // function to create the cli handler -type CLIHandlerFn func(context.CLIContext) *cobra.Command +type CLIHandlerFn func(client.Context) *cobra.Command // The combined type for a proposal handler for both cli and rest type ProposalHandler struct { diff --git a/x/gov/client/rest/query.go b/x/gov/client/rest/query.go index 4b7f42bfa5e0..793f6646996e 100644 --- a/x/gov/client/rest/query.go +++ b/x/gov/client/rest/query.go @@ -7,46 +7,46 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" "github.com/cosmos/cosmos-sdk/x/gov/types" ) -func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc(fmt.Sprintf("/gov/parameters/{%s}", RestParamsType), queryParamsHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/gov/proposals", queryProposalsWithParameterFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}", RestProposalID), queryProposalHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/proposer", RestProposalID), queryProposerHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), queryDepositsHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits/{%s}", RestProposalID, RestDepositor), queryDepositHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/tally", RestProposalID), queryTallyOnProposalHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), queryVotesOnProposalHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes/{%s}", RestProposalID, RestVoter), queryVoteHandlerFn(cliCtx)).Methods("GET") +func registerQueryRoutes(clientCtx client.Context, r *mux.Router) { + r.HandleFunc(fmt.Sprintf("/gov/parameters/{%s}", RestParamsType), queryParamsHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc("/gov/proposals", queryProposalsWithParameterFn(clientCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}", RestProposalID), queryProposalHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/proposer", RestProposalID), queryProposerHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), queryDepositsHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits/{%s}", RestProposalID, RestDepositor), queryDepositHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/tally", RestProposalID), queryTallyOnProposalHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), queryVotesOnProposalHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes/{%s}", RestProposalID, RestVoter), queryVoteHandlerFn(clientCtx)).Methods("GET") } -func queryParamsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryParamsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) paramType := vars[RestParamsType] - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/gov/%s/%s", types.QueryParams, paramType), nil) + res, height, err := clientCtx.QueryWithData(fmt.Sprintf("custom/gov/%s/%s", types.QueryParams, paramType), nil) if rest.CheckNotFoundError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } -func queryProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryProposalHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -62,29 +62,29 @@ func queryProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQueryProposalParams(proposalID) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } - res, height, err := cliCtx.QueryWithData("custom/gov/proposal", bz) + res, height, err := clientCtx.QueryWithData("custom/gov/proposal", bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } -func queryDepositsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryDepositsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -94,25 +94,25 @@ func queryDepositsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQueryProposalParams(proposalID) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } - res, _, err := cliCtx.QueryWithData("custom/gov/proposal", bz) + res, _, err := clientCtx.QueryWithData("custom/gov/proposal", bz) if rest.CheckInternalServerError(w, err) { return } var proposal types.Proposal - if rest.CheckInternalServerError(w, cliCtx.Codec.UnmarshalJSON(res, &proposal)) { + if rest.CheckInternalServerError(w, clientCtx.Codec.UnmarshalJSON(res, &proposal)) { return } @@ -120,20 +120,20 @@ func queryDepositsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // as they're no longer in state. propStatus := proposal.Status if !(propStatus == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { - res, err = gcutils.QueryDepositsByTxQuery(cliCtx, params) + res, err = gcutils.QueryDepositsByTxQuery(clientCtx, params) } else { - res, _, err = cliCtx.QueryWithData("custom/gov/deposits", bz) + res, _, err = clientCtx.QueryWithData("custom/gov/deposits", bz) } if rest.CheckInternalServerError(w, err) { return } - rest.PostProcessResponse(w, cliCtx, res) + rest.PostProcessResponse(w, clientCtx, res) } } -func queryProposerHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryProposerHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -143,21 +143,21 @@ func queryProposerHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - res, err := gcutils.QueryProposerByTxQuery(cliCtx, proposalID) + res, err := gcutils.QueryProposerByTxQuery(clientCtx, proposalID) if rest.CheckInternalServerError(w, err) { return } - rest.PostProcessResponse(w, cliCtx, res) + rest.PostProcessResponse(w, clientCtx, res) } } -func queryDepositHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryDepositHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -185,25 +185,25 @@ func queryDepositHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQueryDepositParams(proposalID, depositorAddr) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } - res, _, err := cliCtx.QueryWithData("custom/gov/deposit", bz) + res, _, err := clientCtx.QueryWithData("custom/gov/deposit", bz) if rest.CheckInternalServerError(w, err) { return } var deposit types.Deposit - if rest.CheckBadRequestError(w, cliCtx.Codec.UnmarshalJSON(res, &deposit)) { + if rest.CheckBadRequestError(w, clientCtx.Codec.UnmarshalJSON(res, &deposit)) { return } @@ -211,29 +211,29 @@ func queryDepositHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // which case the deposit would be removed from state and should be queried // for directly via a txs query. if deposit.Empty() { - bz, err := cliCtx.Codec.MarshalJSON(types.NewQueryProposalParams(proposalID)) + bz, err := clientCtx.Codec.MarshalJSON(types.NewQueryProposalParams(proposalID)) if rest.CheckBadRequestError(w, err) { return } - res, _, err = cliCtx.QueryWithData("custom/gov/proposal", bz) + res, _, err = clientCtx.QueryWithData("custom/gov/proposal", bz) if err != nil || len(res) == 0 { err := fmt.Errorf("proposalID %d does not exist", proposalID) rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) return } - res, err = gcutils.QueryDepositByTxQuery(cliCtx, params) + res, err = gcutils.QueryDepositByTxQuery(clientCtx, params) if rest.CheckInternalServerError(w, err) { return } } - rest.PostProcessResponse(w, cliCtx, res) + rest.PostProcessResponse(w, clientCtx, res) } } -func queryVoteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryVoteHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -262,25 +262,25 @@ func queryVoteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQueryVoteParams(proposalID, voterAddr) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } - res, _, err := cliCtx.QueryWithData("custom/gov/vote", bz) + res, _, err := clientCtx.QueryWithData("custom/gov/vote", bz) if rest.CheckInternalServerError(w, err) { return } var vote types.Vote - if rest.CheckBadRequestError(w, cliCtx.Codec.UnmarshalJSON(res, &vote)) { + if rest.CheckBadRequestError(w, clientCtx.Codec.UnmarshalJSON(res, &vote)) { return } @@ -288,30 +288,30 @@ func queryVoteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // which case the vote would be removed from state and should be queried for // directly via a txs query. if vote.Empty() { - bz, err := cliCtx.Codec.MarshalJSON(types.NewQueryProposalParams(proposalID)) + bz, err := clientCtx.Codec.MarshalJSON(types.NewQueryProposalParams(proposalID)) if rest.CheckBadRequestError(w, err) { return } - res, _, err = cliCtx.QueryWithData("custom/gov/proposal", bz) + res, _, err = clientCtx.QueryWithData("custom/gov/proposal", bz) if err != nil || len(res) == 0 { err := fmt.Errorf("proposalID %d does not exist", proposalID) rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) return } - res, err = gcutils.QueryVoteByTxQuery(cliCtx, params) + res, err = gcutils.QueryVoteByTxQuery(clientCtx, params) if rest.CheckInternalServerError(w, err) { return } } - rest.PostProcessResponse(w, cliCtx, res) + rest.PostProcessResponse(w, clientCtx, res) } } // todo: Split this functionality into helper functions to remove the above -func queryVotesOnProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryVotesOnProposalHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { _, page, limit, err := rest.ParseHTTPArgsWithLimit(r, 0) if rest.CheckBadRequestError(w, err) { @@ -332,25 +332,25 @@ func queryVotesOnProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQueryProposalVotesParams(proposalID, page, limit) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } - res, _, err := cliCtx.QueryWithData("custom/gov/proposal", bz) + res, _, err := clientCtx.QueryWithData("custom/gov/proposal", bz) if rest.CheckInternalServerError(w, err) { return } var proposal types.Proposal - if rest.CheckInternalServerError(w, cliCtx.Codec.UnmarshalJSON(res, &proposal)) { + if rest.CheckInternalServerError(w, clientCtx.Codec.UnmarshalJSON(res, &proposal)) { return } @@ -358,28 +358,28 @@ func queryVotesOnProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // as they're no longer in state. propStatus := proposal.Status if !(propStatus == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { - res, err = gcutils.QueryVotesByTxQuery(cliCtx, params) + res, err = gcutils.QueryVotesByTxQuery(clientCtx, params) } else { - res, _, err = cliCtx.QueryWithData("custom/gov/votes", bz) + res, _, err = clientCtx.QueryWithData("custom/gov/votes", bz) } if rest.CheckInternalServerError(w, err) { return } - rest.PostProcessResponse(w, cliCtx, res) + rest.PostProcessResponse(w, clientCtx, res) } } // HTTP request handler to query list of governance proposals -func queryProposalsWithParameterFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryProposalsWithParameterFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { _, page, limit, err := rest.ParseHTTPArgsWithLimit(r, 0) if rest.CheckBadRequestError(w, err) { return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } @@ -412,24 +412,24 @@ func queryProposalsWithParameterFn(cliCtx context.CLIContext) http.HandlerFunc { } params := types.NewQueryProposalsParams(page, limit, proposalStatus, voterAddr, depositorAddr) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryProposals) - res, height, err := cliCtx.QueryWithData(route, bz) + res, height, err := clientCtx.QueryWithData(route, bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } // todo: Split this functionality into helper functions to remove the above -func queryTallyOnProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryTallyOnProposalHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -445,24 +445,24 @@ func queryTallyOnProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQueryProposalParams(proposalID) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } - res, height, err := cliCtx.QueryWithData("custom/gov/tally", bz) + res, height, err := clientCtx.QueryWithData("custom/gov/tally", bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } diff --git a/x/gov/client/rest/rest.go b/x/gov/client/rest/rest.go index f56222da7641..36087e64a18c 100644 --- a/x/gov/client/rest/rest.go +++ b/x/gov/client/rest/rest.go @@ -5,7 +5,7 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" ) @@ -28,15 +28,15 @@ type ProposalRESTHandler struct { Handler func(http.ResponseWriter, *http.Request) } -func RegisterHandlers(cliCtx context.CLIContext, r *mux.Router, phs []ProposalRESTHandler) { - registerQueryRoutes(cliCtx, r) - registerTxHandlers(cliCtx, r, phs) +func RegisterHandlers(clientCtx client.Context, r *mux.Router, phs []ProposalRESTHandler) { + registerQueryRoutes(clientCtx, r) + registerTxHandlers(clientCtx, r, phs) } // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, phs []ProposalRESTHandler) { - registerQueryRoutes(cliCtx, r) - registerTxRoutes(cliCtx, r, phs) +func RegisterRoutes(clientCtx client.Context, r *mux.Router, phs []ProposalRESTHandler) { + registerQueryRoutes(clientCtx, r) + registerTxRoutes(clientCtx, r, phs) } // PostProposalReq defines the properties of a proposal request's body. diff --git a/x/gov/client/rest/tx.go b/x/gov/client/rest/tx.go index e40f107cf8fe..ec98780ccb80 100644 --- a/x/gov/client/rest/tx.go +++ b/x/gov/client/rest/tx.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" @@ -15,21 +15,21 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/types" ) -func registerTxHandlers(cliCtx context.CLIContext, r *mux.Router, phs []ProposalRESTHandler) { +func registerTxHandlers(clientCtx client.Context, r *mux.Router, phs []ProposalRESTHandler) { propSubRtr := r.PathPrefix("/gov/proposals").Subrouter() for _, ph := range phs { propSubRtr.HandleFunc(fmt.Sprintf("/%s", ph.SubRoute), ph.Handler).Methods("POST") } - r.HandleFunc("/gov/proposals", newPostProposalHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), newDepositHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), newVoteHandlerFn(cliCtx)).Methods("POST") + r.HandleFunc("/gov/proposals", newPostProposalHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), newDepositHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), newVoteHandlerFn(clientCtx)).Methods("POST") } -func newPostProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func newPostProposalHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req PostProposalReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -49,11 +49,11 @@ func newPostProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) } } -func newDepositHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func newDepositHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -69,7 +69,7 @@ func newDepositHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } var req DepositReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -84,11 +84,11 @@ func newDepositHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) } } -func newVoteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func newVoteHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -104,7 +104,7 @@ func newVoteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } var req VoteReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -124,7 +124,7 @@ func newVoteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) } } @@ -133,21 +133,21 @@ func newVoteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // // TODO: Remove once client-side Protobuf migration has been completed. // --------------------------------------------------------------------------- -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, phs []ProposalRESTHandler) { +func registerTxRoutes(clientCtx client.Context, r *mux.Router, phs []ProposalRESTHandler) { propSubRtr := r.PathPrefix("/gov/proposals").Subrouter() for _, ph := range phs { propSubRtr.HandleFunc(fmt.Sprintf("/%s", ph.SubRoute), ph.Handler).Methods("POST") } - r.HandleFunc("/gov/proposals", postProposalHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), depositHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), voteHandlerFn(cliCtx)).Methods("POST") + r.HandleFunc("/gov/proposals", postProposalHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), depositHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), voteHandlerFn(clientCtx)).Methods("POST") } -func postProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func postProposalHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req PostProposalReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -167,11 +167,11 @@ func postProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } -func depositHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func depositHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -187,7 +187,7 @@ func depositHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } var req DepositReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -202,11 +202,11 @@ func depositHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } -func voteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func voteHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -222,7 +222,7 @@ func voteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } var req VoteReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -242,6 +242,6 @@ func voteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/gov/client/utils/query.go b/x/gov/client/utils/query.go index 3b092ccccf0a..b65e1080f723 100644 --- a/x/gov/client/utils/query.go +++ b/x/gov/client/utils/query.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" sdk "github.com/cosmos/cosmos-sdk/types" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -37,7 +36,7 @@ func (p Proposer) String() string { // // NOTE: SearchTxs is used to facilitate the txs query which does not currently // support configurable pagination. -func QueryDepositsByTxQuery(cliCtx context.CLIContext, params types.QueryProposalParams) ([]byte, error) { +func QueryDepositsByTxQuery(clientCtx client.Context, params types.QueryProposalParams) ([]byte, error) { events := []string{ fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeMsgDeposit), fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalDeposit, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))), @@ -45,7 +44,7 @@ func QueryDepositsByTxQuery(cliCtx context.CLIContext, params types.QueryProposa // NOTE: SearchTxs is used to facilitate the txs query which does not currently // support configurable pagination. - searchResult, err := authclient.QueryTxsByEvents(cliCtx, events, defaultPage, defaultLimit, "") + searchResult, err := authclient.QueryTxsByEvents(clientCtx, events, defaultPage, defaultLimit, "") if err != nil { return nil, err } @@ -66,17 +65,17 @@ func QueryDepositsByTxQuery(cliCtx context.CLIContext, params types.QueryProposa } } - if cliCtx.Indent { - return cliCtx.Codec.MarshalJSONIndent(deposits, "", " ") + if clientCtx.Indent { + return clientCtx.Codec.MarshalJSONIndent(deposits, "", " ") } - return cliCtx.Codec.MarshalJSON(deposits) + return clientCtx.Codec.MarshalJSON(deposits) } // QueryVotesByTxQuery will query for votes via a direct txs tags query. It // will fetch and build votes directly from the returned txs and return a JSON // marshalled result or any error that occurred. -func QueryVotesByTxQuery(cliCtx context.CLIContext, params types.QueryProposalVotesParams) ([]byte, error) { +func QueryVotesByTxQuery(clientCtx client.Context, params types.QueryProposalVotesParams) ([]byte, error) { var ( events = []string{ fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeMsgVote), @@ -88,7 +87,7 @@ func QueryVotesByTxQuery(cliCtx context.CLIContext, params types.QueryProposalVo ) // query interrupted either if we collected enough votes or tx indexer run out of relevant txs for len(votes) < totalLimit { - searchResult, err := authclient.QueryTxsByEvents(cliCtx, events, nextTxPage, defaultLimit, "") + searchResult, err := authclient.QueryTxsByEvents(clientCtx, events, nextTxPage, defaultLimit, "") if err != nil { return nil, err } @@ -116,14 +115,14 @@ func QueryVotesByTxQuery(cliCtx context.CLIContext, params types.QueryProposalVo } else { votes = votes[start:end] } - if cliCtx.Indent { - return cliCtx.Codec.MarshalJSONIndent(votes, "", " ") + if clientCtx.Indent { + return clientCtx.Codec.MarshalJSONIndent(votes, "", " ") } - return cliCtx.Codec.MarshalJSON(votes) + return clientCtx.Codec.MarshalJSON(votes) } // QueryVoteByTxQuery will query for a single vote via a direct txs tags query. -func QueryVoteByTxQuery(cliCtx context.CLIContext, params types.QueryVoteParams) ([]byte, error) { +func QueryVoteByTxQuery(clientCtx client.Context, params types.QueryVoteParams) ([]byte, error) { events := []string{ fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeMsgVote), fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalVote, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))), @@ -132,7 +131,7 @@ func QueryVoteByTxQuery(cliCtx context.CLIContext, params types.QueryVoteParams) // NOTE: SearchTxs is used to facilitate the txs query which does not currently // support configurable pagination. - searchResult, err := authclient.QueryTxsByEvents(cliCtx, events, defaultPage, defaultLimit, "") + searchResult, err := authclient.QueryTxsByEvents(clientCtx, events, defaultPage, defaultLimit, "") if err != nil { return nil, err } @@ -148,11 +147,11 @@ func QueryVoteByTxQuery(cliCtx context.CLIContext, params types.QueryVoteParams) Option: voteMsg.Option, } - if cliCtx.Indent { - return cliCtx.Codec.MarshalJSONIndent(vote, "", " ") + if clientCtx.Indent { + return clientCtx.Codec.MarshalJSONIndent(vote, "", " ") } - return cliCtx.Codec.MarshalJSON(vote) + return clientCtx.Codec.MarshalJSON(vote) } } } @@ -162,7 +161,7 @@ func QueryVoteByTxQuery(cliCtx context.CLIContext, params types.QueryVoteParams) // QueryDepositByTxQuery will query for a single deposit via a direct txs tags // query. -func QueryDepositByTxQuery(cliCtx context.CLIContext, params types.QueryDepositParams) ([]byte, error) { +func QueryDepositByTxQuery(clientCtx client.Context, params types.QueryDepositParams) ([]byte, error) { events := []string{ fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeMsgDeposit), fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalDeposit, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))), @@ -171,7 +170,7 @@ func QueryDepositByTxQuery(cliCtx context.CLIContext, params types.QueryDepositP // NOTE: SearchTxs is used to facilitate the txs query which does not currently // support configurable pagination. - searchResult, err := authclient.QueryTxsByEvents(cliCtx, events, defaultPage, defaultLimit, "") + searchResult, err := authclient.QueryTxsByEvents(clientCtx, events, defaultPage, defaultLimit, "") if err != nil { return nil, err } @@ -188,11 +187,11 @@ func QueryDepositByTxQuery(cliCtx context.CLIContext, params types.QueryDepositP Amount: depMsg.Amount, } - if cliCtx.Indent { - return cliCtx.Codec.MarshalJSONIndent(deposit, "", " ") + if clientCtx.Indent { + return clientCtx.Codec.MarshalJSONIndent(deposit, "", " ") } - return cliCtx.Codec.MarshalJSON(deposit) + return clientCtx.Codec.MarshalJSON(deposit) } } } @@ -202,7 +201,7 @@ func QueryDepositByTxQuery(cliCtx context.CLIContext, params types.QueryDepositP // QueryProposerByTxQuery will query for a proposer of a governance proposal by // ID. -func QueryProposerByTxQuery(cliCtx context.CLIContext, proposalID uint64) (Proposer, error) { +func QueryProposerByTxQuery(clientCtx client.Context, proposalID uint64) (Proposer, error) { events := []string{ fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeMsgSubmitProposal), fmt.Sprintf("%s.%s='%s'", types.EventTypeSubmitProposal, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", proposalID))), @@ -210,7 +209,7 @@ func QueryProposerByTxQuery(cliCtx context.CLIContext, proposalID uint64) (Propo // NOTE: SearchTxs is used to facilitate the txs query which does not currently // support configurable pagination. - searchResult, err := authclient.QueryTxsByEvents(cliCtx, events, defaultPage, defaultLimit, "") + searchResult, err := authclient.QueryTxsByEvents(clientCtx, events, defaultPage, defaultLimit, "") if err != nil { return Proposer{}, err } @@ -229,14 +228,14 @@ func QueryProposerByTxQuery(cliCtx context.CLIContext, proposalID uint64) (Propo } // QueryProposalByID takes a proposalID and returns a proposal -func QueryProposalByID(proposalID uint64, cliCtx context.CLIContext, queryRoute string) ([]byte, error) { +func QueryProposalByID(proposalID uint64, clientCtx client.Context, queryRoute string) ([]byte, error) { params := types.NewQueryProposalParams(proposalID) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if err != nil { return nil, err } - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/proposal", queryRoute), bz) + res, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/proposal", queryRoute), bz) if err != nil { return nil, err } diff --git a/x/gov/client/utils/query_test.go b/x/gov/client/utils/query_test.go index adc83eb48a80..ede1abf09d0d 100644 --- a/x/gov/client/utils/query_test.go +++ b/x/gov/client/utils/query_test.go @@ -9,7 +9,6 @@ import ( tmtypes "github.com/tendermint/tendermint/types" "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" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -141,14 +140,14 @@ func TestGetPaginatedVotes(t *testing.T) { require.NoError(t, err) marshalled[i] = tx } - client := TxSearchMock{txs: marshalled} - ctx := context.CLIContext{}.WithCodec(cdc).WithTrustNode(true).WithClient(client) + cli := TxSearchMock{txs: marshalled} + clientCtx := client.Context{}.WithCodec(cdc).WithTrustNode(true).WithClient(cli) params := types.NewQueryProposalVotesParams(0, tc.page, tc.limit) - votesData, err := QueryVotesByTxQuery(ctx, params) + votesData, err := QueryVotesByTxQuery(clientCtx, params) require.NoError(t, err) votes := []types.Vote{} - require.NoError(t, ctx.Codec.UnmarshalJSON(votesData, &votes)) + require.NoError(t, clientCtx.Codec.UnmarshalJSON(votesData, &votes)) require.Equal(t, len(tc.votes), len(votes)) for i := range votes { require.Equal(t, tc.votes[i], votes[i]) diff --git a/x/gov/module.go b/x/gov/module.go index 9a47a3c9cc17..1908aa0018e4 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -12,13 +12,13 @@ import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/gov/client" + govclient "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/simulation" @@ -35,11 +35,11 @@ var ( // AppModuleBasic defines the basic application module used by the gov module. type AppModuleBasic struct { cdc codec.Marshaler - proposalHandlers []client.ProposalHandler // proposal handlers which live in governance cli and rest + proposalHandlers []govclient.ProposalHandler // proposal handlers which live in governance cli and rest } // NewAppModuleBasic creates a new AppModuleBasic object -func NewAppModuleBasic(proposalHandlers ...client.ProposalHandler) AppModuleBasic { +func NewAppModuleBasic(proposalHandlers ...govclient.ProposalHandler) AppModuleBasic { return AppModuleBasic{ proposalHandlers: proposalHandlers, } @@ -72,23 +72,23 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessag } // RegisterRESTRoutes registers the REST routes for the gov module. -func (a AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { +func (a AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { proposalRESTHandlers := make([]rest.ProposalRESTHandler, 0, len(a.proposalHandlers)) for _, proposalHandler := range a.proposalHandlers { - proposalRESTHandlers = append(proposalRESTHandlers, proposalHandler.RESTHandler(ctx)) + proposalRESTHandlers = append(proposalRESTHandlers, proposalHandler.RESTHandler(clientCtx)) } - rest.RegisterHandlers(ctx, rtr, proposalRESTHandlers) + rest.RegisterHandlers(clientCtx, rtr, proposalRESTHandlers) } // GetTxCmd returns the root tx command for the gov module. -func (a AppModuleBasic) GetTxCmd(ctx context.CLIContext) *cobra.Command { +func (a AppModuleBasic) GetTxCmd(clientCtx client.Context) *cobra.Command { proposalCLIHandlers := make([]*cobra.Command, 0, len(a.proposalHandlers)) for _, proposalHandler := range a.proposalHandlers { - proposalCLIHandlers = append(proposalCLIHandlers, proposalHandler.CLIHandler(ctx)) + proposalCLIHandlers = append(proposalCLIHandlers, proposalHandler.CLIHandler(clientCtx)) } - return cli.NewTxCmd(ctx, proposalCLIHandlers) + return cli.NewTxCmd(clientCtx, proposalCLIHandlers) } // GetQueryCmd returns the root query command for the gov module. diff --git a/x/ibc-transfer/client/cli/query.go b/x/ibc-transfer/client/cli/query.go index 8a9a15633e5e..7843286baddb 100644 --- a/x/ibc-transfer/client/cli/query.go +++ b/x/ibc-transfer/client/cli/query.go @@ -7,7 +7,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/version" @@ -28,18 +28,18 @@ $ %s query ibc channel next-recv [port-id] [channel-id] Example: fmt.Sprintf("%s query ibc channel next-recv [port-id] [channel-id]", version.ClientName), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) portID := args[0] channelID := args[1] prove := viper.GetBool(flags.FlagProve) - sequenceRes, err := utils.QueryNextSequenceRecv(cliCtx, portID, channelID, prove) + sequenceRes, err := utils.QueryNextSequenceRecv(clientCtx, portID, channelID, prove) if err != nil { return err } - cliCtx = cliCtx.WithHeight(int64(sequenceRes.ProofHeight)) - return cliCtx.PrintOutput(sequenceRes) + clientCtx = clientCtx.WithHeight(int64(sequenceRes.ProofHeight)) + return clientCtx.PrintOutput(sequenceRes) }, } cmd.Flags().Bool(flags.FlagProve, true, "show proofs for the query results") diff --git a/x/ibc-transfer/client/cli/tx.go b/x/ibc-transfer/client/cli/tx.go index daafae7bf443..634eb33500d7 100644 --- a/x/ibc-transfer/client/cli/tx.go +++ b/x/ibc-transfer/client/cli/tx.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -35,9 +35,9 @@ func GetTransferTxCmd(cdc *codec.Codec) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc).WithBroadcastMode(flags.BroadcastBlock) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc).WithBroadcastMode(flags.BroadcastBlock) - sender := cliCtx.GetFromAddress() + sender := clientCtx.GetFromAddress() srcPort := args[0] srcChannel := args[1] destHeight, err := strconv.Atoi(args[2]) @@ -56,7 +56,7 @@ func GetTransferTxCmd(cdc *codec.Codec) *cobra.Command { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } return cmd diff --git a/x/ibc-transfer/client/rest/query.go b/x/ibc-transfer/client/rest/query.go index 4c5c848d642b..514142c08957 100644 --- a/x/ibc-transfer/client/rest/query.go +++ b/x/ibc-transfer/client/rest/query.go @@ -6,14 +6,14 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/ibc-transfer/client/utils" ) -func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc(fmt.Sprintf("/ibc/ports/{%s}/channels/{%s}/next-sequence-recv", RestPortID, RestChannelID), queryNextSequenceRecvHandlerFn(cliCtx)).Methods("GET") +func registerQueryRoutes(clientCtx client.Context, r *mux.Router) { + r.HandleFunc(fmt.Sprintf("/ibc/ports/{%s}/channels/{%s}/next-sequence-recv", RestPortID, RestChannelID), queryNextSequenceRecvHandlerFn(clientCtx)).Methods("GET") } // queryNextSequenceRecvHandlerFn implements a next sequence receive querying route @@ -27,25 +27,25 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) { // @Failure 400 {object} rest.ErrorResponse "Invalid port id or channel id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/ports/{port-id}/channels/{channel-id}/next-sequence-recv [get] -func queryNextSequenceRecvHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryNextSequenceRecvHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) portID := vars[RestPortID] channelID := vars[RestChannelID] prove := rest.ParseQueryParamBool(r, flags.FlagProve) - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - sequenceRes, err := utils.QueryNextSequenceRecv(cliCtx, portID, channelID, prove) + sequenceRes, err := utils.QueryNextSequenceRecv(clientCtx, portID, channelID, prove) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - cliCtx = cliCtx.WithHeight(int64(sequenceRes.ProofHeight)) - rest.PostProcessResponse(w, cliCtx, sequenceRes) + clientCtx = clientCtx.WithHeight(int64(sequenceRes.ProofHeight)) + rest.PostProcessResponse(w, clientCtx, sequenceRes) } } diff --git a/x/ibc-transfer/client/rest/rest.go b/x/ibc-transfer/client/rest/rest.go index a5c098e26b05..a9c58394acbb 100644 --- a/x/ibc-transfer/client/rest/rest.go +++ b/x/ibc-transfer/client/rest/rest.go @@ -3,7 +3,7 @@ package rest import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" ) @@ -14,9 +14,9 @@ const ( ) // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { - registerQueryRoutes(cliCtx, r) - registerTxRoutes(cliCtx, r) +func RegisterRoutes(clientCtx client.Context, r *mux.Router) { + registerQueryRoutes(clientCtx, r) + registerTxRoutes(clientCtx, r) } // TransferTxReq defines the properties of a transfer tx request's body. diff --git a/x/ibc-transfer/client/rest/tx.go b/x/ibc-transfer/client/rest/tx.go index 372602f58f63..0849e76b0038 100644 --- a/x/ibc-transfer/client/rest/tx.go +++ b/x/ibc-transfer/client/rest/tx.go @@ -6,15 +6,15 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" "github.com/cosmos/cosmos-sdk/x/ibc-transfer/types" ) -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc(fmt.Sprintf("/ibc/ports/{%s}/channels/{%s}/transfer", RestPortID, RestChannelID), transferHandlerFn(cliCtx)).Methods("POST") +func registerTxRoutes(clientCtx client.Context, r *mux.Router) { + r.HandleFunc(fmt.Sprintf("/ibc/ports/{%s}/channels/{%s}/transfer", RestPortID, RestChannelID), transferHandlerFn(clientCtx)).Methods("POST") } // transferHandlerFn implements a transfer handler @@ -30,14 +30,14 @@ func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { // @Failure 400 {object} rest.ErrorResponse "Invalid port id or channel id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/ports/{port-id}/channels/{channel-id}/transfer [post] -func transferHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func transferHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) portID := vars[RestPortID] channelID := vars[RestChannelID] var req TransferTxReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -67,6 +67,6 @@ func transferHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/ibc-transfer/client/utils/utils.go b/x/ibc-transfer/client/utils/utils.go index 71d5165309e0..2028bd2ef747 100644 --- a/x/ibc-transfer/client/utils/utils.go +++ b/x/ibc-transfer/client/utils/utils.go @@ -5,7 +5,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/types" host "github.com/cosmos/cosmos-sdk/x/ibc/24-host" ) @@ -13,7 +13,7 @@ import ( // QueryNextSequenceRecv queries the store to get the next receive sequence and // a merkle proof. func QueryNextSequenceRecv( - cliCtx context.CLIContext, portID, channelID string, prove bool, + clientCtx client.Context, portID, channelID string, prove bool, ) (channeltypes.RecvResponse, error) { req := abci.RequestQuery{ Path: "store/ibc/key", @@ -21,7 +21,7 @@ func QueryNextSequenceRecv( Prove: prove, } - res, err := cliCtx.QueryABCI(req) + res, err := clientCtx.QueryABCI(req) if err != nil { return channeltypes.RecvResponse{}, err } diff --git a/x/ibc-transfer/module.go b/x/ibc-transfer/module.go index 2aa0b7dd6072..0118fa764382 100644 --- a/x/ibc-transfer/module.go +++ b/x/ibc-transfer/module.go @@ -10,7 +10,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -65,13 +65,13 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessag } // RegisterRESTRoutes implements AppModuleBasic interface -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { - rest.RegisterRoutes(ctx, rtr) +func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { + rest.RegisterRoutes(clientCtx, rtr) } // GetTxCmd implements AppModuleBasic interface -func (AppModuleBasic) GetTxCmd(ctx context.CLIContext) *cobra.Command { - return cli.GetTxCmd(ctx.Codec) +func (AppModuleBasic) GetTxCmd(clientCtx client.Context) *cobra.Command { + return cli.GetTxCmd(clientCtx.Codec) } // GetQueryCmd implements AppModuleBasic interface diff --git a/x/ibc/02-client/client/cli/query.go b/x/ibc/02-client/client/cli/query.go index 3325fc1a423a..a10ff1e2a870 100644 --- a/x/ibc/02-client/client/cli/query.go +++ b/x/ibc/02-client/client/cli/query.go @@ -9,7 +9,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/version" @@ -32,17 +32,17 @@ $ %s query ibc client states ), Example: fmt.Sprintf("%s query ibc client states", version.ClientName), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) page := viper.GetInt(flags.FlagPage) limit := viper.GetInt(flags.FlagLimit) - clientStates, height, err := utils.QueryAllClientStates(cliCtx, page, limit) + clientStates, height, err := utils.QueryAllClientStates(clientCtx, page, limit) if err != nil { return err } - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(clientStates) + clientCtx = clientCtx.WithHeight(height) + return clientCtx.PrintOutput(clientStates) }, } cmd.Flags().Int(flags.FlagPage, 1, "pagination page of light clients to to query for") @@ -65,7 +65,7 @@ $ %s query ibc client state [client-id] ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) clientID := args[0] if strings.TrimSpace(clientID) == "" { return errors.New("client ID can't be blank") @@ -73,13 +73,13 @@ $ %s query ibc client state [client-id] prove := viper.GetBool(flags.FlagProve) - clientStateRes, err := utils.QueryClientState(cliCtx, clientID, prove) + clientStateRes, err := utils.QueryClientState(clientCtx, clientID, prove) if err != nil { return err } - cliCtx = cliCtx.WithHeight(int64(clientStateRes.ProofHeight)) - return cliCtx.PrintOutput(clientStateRes) + clientCtx = clientCtx.WithHeight(int64(clientStateRes.ProofHeight)) + return clientCtx.PrintOutput(clientStateRes) }, } cmd.Flags().Bool(flags.FlagProve, true, "show proofs for the query results") @@ -96,7 +96,7 @@ func GetCmdQueryConsensusState(queryRoute string, cdc *codec.Codec) *cobra.Comma Example: fmt.Sprintf("%s query ibc client consensus-state [client-id] [height]", version.ClientName), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) clientID := args[0] if strings.TrimSpace(clientID) == "" { return errors.New("client ID can't be blank") @@ -109,13 +109,13 @@ func GetCmdQueryConsensusState(queryRoute string, cdc *codec.Codec) *cobra.Comma prove := viper.GetBool(flags.FlagProve) - csRes, err := utils.QueryConsensusState(cliCtx, clientID, height, prove) + csRes, err := utils.QueryConsensusState(clientCtx, clientID, height, prove) if err != nil { return err } - cliCtx = cliCtx.WithHeight(int64(csRes.ProofHeight)) - return cliCtx.PrintOutput(csRes) + clientCtx = clientCtx.WithHeight(int64(csRes.ProofHeight)) + return clientCtx.PrintOutput(csRes) }, } cmd.Flags().Bool(flags.FlagProve, true, "show proofs for the query results") @@ -130,15 +130,15 @@ func GetCmdQueryHeader(cdc *codec.Codec) *cobra.Command { Long: "Query the latest Tendermint header of the running chain", Example: fmt.Sprintf("%s query ibc client header", version.ClientName), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) - header, height, err := utils.QueryTendermintHeader(cliCtx) + header, height, err := utils.QueryTendermintHeader(clientCtx) if err != nil { return err } - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(header) + clientCtx = clientCtx.WithHeight(height) + return clientCtx.PrintOutput(header) }, } } @@ -158,15 +158,15 @@ $ %s query ibc client node-state ), Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) - state, height, err := utils.QueryNodeConsensusState(cliCtx) + state, height, err := utils.QueryNodeConsensusState(clientCtx) if err != nil { return err } - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(state) + clientCtx = clientCtx.WithHeight(height) + return clientCtx.PrintOutput(state) }, } } @@ -177,9 +177,9 @@ func GetCmdQueryPath(storeName string, cdc *codec.Codec) *cobra.Command { Use: "path", Short: "Query the commitment path of the running chain", RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCLIContext().WithCodec(cdc) + clienCtx := client.NewContext().WithCodec(cdc) path := commitmenttypes.NewMerklePrefix([]byte("ibc")) - return ctx.PrintOutput(path) + return clienCtx.PrintOutput(path) }, } } diff --git a/x/ibc/02-client/client/rest/query.go b/x/ibc/02-client/client/rest/query.go index f7aa357a1e7d..b3f115583552 100644 --- a/x/ibc/02-client/client/rest/query.go +++ b/x/ibc/02-client/client/rest/query.go @@ -7,18 +7,18 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/ibc/02-client/client/utils" ) -func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/ibc/clients", queryAllClientStatesFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/ibc/clients/{%s}/client-state", RestClientID), queryClientStateHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/ibc/clients/{%s}/consensus-state", RestClientID), queryConsensusStateHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/ibc/header", queryHeaderHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/ibc/node-state", queryNodeConsensusStateHandlerFn(cliCtx)).Methods("GET") +func registerQueryRoutes(clientCtx client.Context, r *mux.Router) { + r.HandleFunc("/ibc/clients", queryAllClientStatesFn(clientCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/ibc/clients/{%s}/client-state", RestClientID), queryClientStateHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/ibc/clients/{%s}/consensus-state", RestClientID), queryConsensusStateHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc("/ibc/header", queryHeaderHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc("/ibc/node-state", queryNodeConsensusStateHandlerFn(clientCtx)).Methods("GET") } // queryAllClientStatesFn queries all available light clients @@ -32,7 +32,7 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) { // @Failure 400 {object} rest.ErrorResponse "Bad Request" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/clients [get] -func queryAllClientStatesFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryAllClientStatesFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { _, page, limit, err := rest.ParseHTTPArgsWithLimit(r, 0) if err != nil { @@ -40,19 +40,19 @@ func queryAllClientStatesFn(cliCtx context.CLIContext) http.HandlerFunc { return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - clients, height, err := utils.QueryAllClientStates(cliCtx, page, limit) + clients, height, err := utils.QueryAllClientStates(clientCtx, page, limit) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, clients) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, clients) } } @@ -67,25 +67,25 @@ func queryAllClientStatesFn(cliCtx context.CLIContext) http.HandlerFunc { // @Failure 400 {object} rest.ErrorResponse "Invalid client id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/clients/{client-id}/client-state [get] -func queryClientStateHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryClientStateHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) clientID := vars[RestClientID] prove := rest.ParseQueryParamBool(r, flags.FlagProve) - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - clientStateRes, err := utils.QueryClientState(cliCtx, clientID, prove) + clientStateRes, err := utils.QueryClientState(clientCtx, clientID, prove) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - cliCtx = cliCtx.WithHeight(int64(clientStateRes.ProofHeight)) - rest.PostProcessResponse(w, cliCtx, clientStateRes) + clientCtx = clientCtx.WithHeight(int64(clientStateRes.ProofHeight)) + rest.PostProcessResponse(w, clientCtx, clientStateRes) } } @@ -101,7 +101,7 @@ func queryClientStateHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Failure 400 {object} rest.ErrorResponse "Invalid client id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/clients/{client-id}/consensus-state [get] -func queryConsensusStateHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryConsensusStateHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) clientID := vars[RestClientID] @@ -113,19 +113,19 @@ func queryConsensusStateHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { prove := rest.ParseQueryParamBool(r, flags.FlagProve) - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - csRes, err := utils.QueryConsensusState(cliCtx, clientID, height, prove) + csRes, err := utils.QueryConsensusState(clientCtx, clientID, height, prove) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - cliCtx = cliCtx.WithHeight(int64(csRes.ProofHeight)) - rest.PostProcessResponse(w, cliCtx, csRes) + clientCtx = clientCtx.WithHeight(int64(csRes.ProofHeight)) + rest.PostProcessResponse(w, clientCtx, csRes) } } @@ -137,17 +137,17 @@ func queryConsensusStateHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Success 200 {object} QueryHeader "OK" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/header [get] -func queryHeaderHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryHeaderHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - header, height, err := utils.QueryTendermintHeader(cliCtx) + header, height, err := utils.QueryTendermintHeader(clientCtx) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - res := cliCtx.Codec.MustMarshalJSON(header) - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + res := clientCtx.Codec.MustMarshalJSON(header) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } @@ -159,15 +159,15 @@ func queryHeaderHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Success 200 {object} QueryNodeConsensusState "OK" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/node-state [get] -func queryNodeConsensusStateHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryNodeConsensusStateHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - state, height, err := utils.QueryNodeConsensusState(cliCtx) + state, height, err := utils.QueryNodeConsensusState(clientCtx) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) } - res := cliCtx.Codec.MustMarshalJSON(state) - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + res := clientCtx.Codec.MustMarshalJSON(state) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } diff --git a/x/ibc/02-client/client/rest/rest.go b/x/ibc/02-client/client/rest/rest.go index a6b8b215b2c3..9295259bd97f 100644 --- a/x/ibc/02-client/client/rest/rest.go +++ b/x/ibc/02-client/client/rest/rest.go @@ -3,7 +3,7 @@ package rest import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" ) // REST client flags @@ -13,6 +13,6 @@ const ( ) // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, queryRoute string) { - registerQueryRoutes(cliCtx, r) +func RegisterRoutes(clientCtx client.Context, r *mux.Router, queryRoute string) { + registerQueryRoutes(clientCtx, r) } diff --git a/x/ibc/02-client/client/utils/utils.go b/x/ibc/02-client/client/utils/utils.go index ca26db298ea2..6acfac44a34d 100644 --- a/x/ibc/02-client/client/utils/utils.go +++ b/x/ibc/02-client/client/utils/utils.go @@ -6,7 +6,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" tmtypes "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/x/ibc/02-client/exported" "github.com/cosmos/cosmos-sdk/x/ibc/02-client/types" ibctmtypes "github.com/cosmos/cosmos-sdk/x/ibc/07-tendermint/types" @@ -16,21 +16,21 @@ import ( // QueryAllClientStates returns all the light client states. It _does not_ return // any merkle proof. -func QueryAllClientStates(cliCtx context.CLIContext, page, limit int) ([]exported.ClientState, int64, error) { +func QueryAllClientStates(clientCtx client.Context, page, limit int) ([]exported.ClientState, int64, error) { params := types.NewQueryAllClientsParams(page, limit) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if err != nil { return nil, 0, fmt.Errorf("failed to marshal query params: %w", err) } route := fmt.Sprintf("custom/%s/%s/%s", "ibc", types.QuerierRoute, types.QueryAllClients) - res, height, err := cliCtx.QueryWithData(route, bz) + res, height, err := clientCtx.QueryWithData(route, bz) if err != nil { return nil, 0, err } var clients []exported.ClientState - err = cliCtx.Codec.UnmarshalJSON(res, &clients) + err = clientCtx.Codec.UnmarshalJSON(res, &clients) if err != nil { return nil, 0, fmt.Errorf("failed to unmarshal light clients: %w", err) } @@ -40,7 +40,7 @@ func QueryAllClientStates(cliCtx context.CLIContext, page, limit int) ([]exporte // QueryClientState queries the store to get the light client state and a merkle // proof. func QueryClientState( - cliCtx context.CLIContext, clientID string, prove bool, + clientCtx client.Context, clientID string, prove bool, ) (types.StateResponse, error) { req := abci.RequestQuery{ Path: "store/ibc/key", @@ -48,13 +48,13 @@ func QueryClientState( Prove: prove, } - res, err := cliCtx.QueryABCI(req) + res, err := clientCtx.QueryABCI(req) if err != nil { return types.StateResponse{}, err } var clientState exported.ClientState - if err := cliCtx.Codec.UnmarshalBinaryBare(res.Value, &clientState); err != nil { + if err := clientCtx.Codec.UnmarshalBinaryBare(res.Value, &clientState); err != nil { return types.StateResponse{}, err } @@ -66,7 +66,7 @@ func QueryClientState( // QueryConsensusState queries the store to get the consensus state and a merkle // proof. func QueryConsensusState( - cliCtx context.CLIContext, clientID string, height uint64, prove bool, + clientCtx client.Context, clientID string, height uint64, prove bool, ) (types.ConsensusStateResponse, error) { var conStateRes types.ConsensusStateResponse @@ -76,13 +76,13 @@ func QueryConsensusState( Prove: prove, } - res, err := cliCtx.QueryABCI(req) + res, err := clientCtx.QueryABCI(req) if err != nil { return conStateRes, err } var cs exported.ConsensusState - if err := cliCtx.Codec.UnmarshalBinaryBare(res.Value, &cs); err != nil { + if err := clientCtx.Codec.UnmarshalBinaryBare(res.Value, &cs); err != nil { return conStateRes, err } @@ -91,8 +91,8 @@ func QueryConsensusState( // QueryTendermintHeader takes a client context and returns the appropriate // tendermint header -func QueryTendermintHeader(cliCtx context.CLIContext) (ibctmtypes.Header, int64, error) { - node, err := cliCtx.GetNode() +func QueryTendermintHeader(clientCtx client.Context) (ibctmtypes.Header, int64, error) { + node, err := clientCtx.GetNode() if err != nil { return ibctmtypes.Header{}, 0, err } @@ -124,8 +124,8 @@ func QueryTendermintHeader(cliCtx context.CLIContext) (ibctmtypes.Header, int64, // QueryNodeConsensusState takes a client context and returns the appropriate // tendermint consensus state -func QueryNodeConsensusState(cliCtx context.CLIContext) (ibctmtypes.ConsensusState, int64, error) { - node, err := cliCtx.GetNode() +func QueryNodeConsensusState(clientCtx client.Context) (ibctmtypes.ConsensusState, int64, error) { + node, err := clientCtx.GetNode() if err != nil { return ibctmtypes.ConsensusState{}, 0, err } diff --git a/x/ibc/02-client/module.go b/x/ibc/02-client/module.go index fd1fd48c06b2..86dd2831f5c1 100644 --- a/x/ibc/02-client/module.go +++ b/x/ibc/02-client/module.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/mux" "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/ibc/02-client/client/cli" "github.com/cosmos/cosmos-sdk/x/ibc/02-client/client/rest" @@ -18,8 +18,8 @@ func Name() string { } // RegisterRESTRoutes registers the REST routes for the IBC client -func RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, queryRoute string) { - rest.RegisterRoutes(ctx, rtr, fmt.Sprintf("%s/%s", queryRoute, SubModuleName)) +func RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router, queryRoute string) { + rest.RegisterRoutes(clientCtx, rtr, fmt.Sprintf("%s/%s", queryRoute, SubModuleName)) } // GetQueryCmd returns no root query command for the IBC client diff --git a/x/ibc/03-connection/client/cli/query.go b/x/ibc/03-connection/client/cli/query.go index 4950dbfd6056..57373f1ea8a9 100644 --- a/x/ibc/03-connection/client/cli/query.go +++ b/x/ibc/03-connection/client/cli/query.go @@ -7,7 +7,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/version" @@ -30,17 +30,17 @@ $ %s query ibc connection connections Example: fmt.Sprintf("%s query ibc connection connections", version.ClientName), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) page := viper.GetInt(flags.FlagPage) limit := viper.GetInt(flags.FlagLimit) - connections, height, err := utils.QueryAllConnections(cliCtx, page, limit) + connections, height, err := utils.QueryAllConnections(clientCtx, page, limit) if err != nil { return err } - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(connections) + clientCtx = clientCtx.WithHeight(height) + return clientCtx.PrintOutput(connections) }, } cmd.Flags().Int(flags.FlagPage, 1, "pagination page of light clients to to query for") @@ -63,17 +63,17 @@ $ %s query ibc connection end [connection-id] Example: fmt.Sprintf("%s query ibc connection end [connection-id]", version.ClientName), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) connectionID := args[0] prove := viper.GetBool(flags.FlagProve) - connRes, err := utils.QueryConnection(cliCtx, connectionID, prove) + connRes, err := utils.QueryConnection(clientCtx, connectionID, prove) if err != nil { return err } - cliCtx = cliCtx.WithHeight(int64(connRes.ProofHeight)) - return cliCtx.PrintOutput(connRes) + clientCtx = clientCtx.WithHeight(int64(connRes.ProofHeight)) + return clientCtx.PrintOutput(connRes) }, } cmd.Flags().Bool(flags.FlagProve, true, "show proofs for the query results") @@ -95,17 +95,17 @@ $ %s query ibc connection paths Example: fmt.Sprintf("%s query ibc connection paths", version.ClientName), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) page := viper.GetInt(flags.FlagPage) limit := viper.GetInt(flags.FlagLimit) - connectionPaths, height, err := utils.QueryAllClientConnectionPaths(cliCtx, page, limit) + connectionPaths, height, err := utils.QueryAllClientConnectionPaths(clientCtx, page, limit) if err != nil { return err } - cliCtx = cliCtx.WithHeight(height) - return cliCtx.PrintOutput(connectionPaths) + clientCtx = clientCtx.WithHeight(height) + return clientCtx.PrintOutput(connectionPaths) }, } cmd.Flags().Int(flags.FlagPage, 1, "pagination page of light clients to to query for") @@ -128,17 +128,17 @@ $ %s query ibc connection path [client-id] Example: fmt.Sprintf("%s query ibc connection path [client-id]", version.ClientName), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) clientID := args[0] prove := viper.GetBool(flags.FlagProve) - connPathsRes, err := utils.QueryClientConnections(cliCtx, clientID, prove) + connPathsRes, err := utils.QueryClientConnections(clientCtx, clientID, prove) if err != nil { return err } - cliCtx = cliCtx.WithHeight(int64(connPathsRes.ProofHeight)) - return cliCtx.PrintOutput(connPathsRes) + clientCtx = clientCtx.WithHeight(int64(connPathsRes.ProofHeight)) + return clientCtx.PrintOutput(connPathsRes) }, } } diff --git a/x/ibc/03-connection/client/cli/tx.go b/x/ibc/03-connection/client/cli/tx.go index bacb85c3a1b7..36d8eb1634af 100644 --- a/x/ibc/03-connection/client/cli/tx.go +++ b/x/ibc/03-connection/client/cli/tx.go @@ -8,7 +8,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -47,28 +47,28 @@ $ %s tx ibc connection open-init [connection-id] [client-id] \ RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) connectionID := args[0] clientID := args[1] counterpartyConnectionID := args[2] counterpartyClientID := args[3] - counterpartyPrefix, err := utils.ParsePrefix(cliCtx.Codec, args[4]) + counterpartyPrefix, err := utils.ParsePrefix(clientCtx.Codec, args[4]) if err != nil { return err } msg := types.NewMsgConnectionOpenInit( connectionID, clientID, counterpartyConnectionID, counterpartyClientID, - counterpartyPrefix, cliCtx.GetFromAddress(), + counterpartyPrefix, clientCtx.GetFromAddress(), ) if err := msg.ValidateBasic(); err != nil { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } @@ -96,7 +96,7 @@ $ %s tx ibc connection open-try connection-id] [client-id] \ RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf). + clientCtx := client.NewContextWithInput(inBuf). WithCodec(cdc). WithHeight(viper.GetInt64(flags.FlagHeight)) @@ -105,7 +105,7 @@ $ %s tx ibc connection open-try connection-id] [client-id] \ counterpartyConnectionID := args[2] counterpartyClientID := args[3] - counterpartyPrefix, err := utils.ParsePrefix(cliCtx.Codec, args[4]) + counterpartyPrefix, err := utils.ParsePrefix(clientCtx.Codec, args[4]) if err != nil { return err } @@ -113,13 +113,13 @@ $ %s tx ibc connection open-try connection-id] [client-id] \ // TODO: parse strings? counterpartyVersions := args[5] - proofInit, err := utils.ParseProof(cliCtx.Codec, args[1]) + proofInit, err := utils.ParseProof(clientCtx.Codec, args[1]) if err != nil { return err } - proofHeight := uint64(cliCtx.Height) - consensusHeight, err := lastHeight(cliCtx) + proofHeight := uint64(clientCtx.Height) + consensusHeight, err := lastHeight(clientCtx) if err != nil { return err } @@ -127,14 +127,14 @@ $ %s tx ibc connection open-try connection-id] [client-id] \ msg := types.NewMsgConnectionOpenTry( connectionID, clientID, counterpartyConnectionID, counterpartyClientID, counterpartyPrefix, []string{counterpartyVersions}, proofInit, proofInit, proofHeight, - consensusHeight, cliCtx.GetFromAddress(), + consensusHeight, clientCtx.GetFromAddress(), ) if err := msg.ValidateBasic(); err != nil { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } @@ -158,17 +158,17 @@ $ %s tx ibc connection open-ack [connection-id] [path/to/proof_try.json] [versio RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) connectionID := args[0] - proofTry, err := utils.ParseProof(cliCtx.Codec, args[1]) + proofTry, err := utils.ParseProof(clientCtx.Codec, args[1]) if err != nil { return err } - proofHeight := uint64(cliCtx.Height) - consensusHeight, err := lastHeight(cliCtx) + proofHeight := uint64(clientCtx.Height) + consensusHeight, err := lastHeight(clientCtx) if err != nil { return err } @@ -177,14 +177,14 @@ $ %s tx ibc connection open-ack [connection-id] [path/to/proof_try.json] [versio msg := types.NewMsgConnectionOpenAck( connectionID, proofTry, proofTry, proofHeight, - consensusHeight, version, cliCtx.GetFromAddress(), + consensusHeight, version, clientCtx.GetFromAddress(), ) if err := msg.ValidateBasic(); err != nil { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } @@ -208,31 +208,31 @@ $ %s tx ibc connection open-confirm [connection-id] [path/to/proof_ack.json] RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf). + clientCtx := client.NewContextWithInput(inBuf). WithCodec(cdc). WithHeight(viper.GetInt64(flags.FlagHeight)) connectionID := args[0] - proofAck, err := utils.ParseProof(cliCtx.Codec, args[1]) + proofAck, err := utils.ParseProof(clientCtx.Codec, args[1]) if err != nil { return err } - proofHeight := uint64(cliCtx.Height) + proofHeight := uint64(clientCtx.Height) if err != nil { return err } msg := types.NewMsgConnectionOpenConfirm( - connectionID, proofAck, proofHeight, cliCtx.GetFromAddress(), + connectionID, proofAck, proofHeight, clientCtx.GetFromAddress(), ) if err := msg.ValidateBasic(); err != nil { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } @@ -240,8 +240,8 @@ $ %s tx ibc connection open-confirm [connection-id] [path/to/proof_ack.json] } // lastHeight util function to get the consensus height from the node -func lastHeight(cliCtx context.CLIContext) (uint64, error) { - node, err := cliCtx.GetNode() +func lastHeight(clientCtx client.Context) (uint64, error) { + node, err := clientCtx.GetNode() if err != nil { return 0, err } diff --git a/x/ibc/03-connection/client/rest/query.go b/x/ibc/03-connection/client/rest/query.go index fe299cd46fc7..d42d2336e7cb 100644 --- a/x/ibc/03-connection/client/rest/query.go +++ b/x/ibc/03-connection/client/rest/query.go @@ -6,17 +6,17 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/ibc/03-connection/client/utils" ) -func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, queryRoute string) { - r.HandleFunc("/ibc/connections", queryConnectionsHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/ibc/connections/{%s}", RestConnectionID), queryConnectionHandlerFn(cliCtx, queryRoute)).Methods("GET") - r.HandleFunc("/ibc/clients/connections", queryClientsConnectionsHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/ibc/clients/{%s}/connections", RestClientID), queryClientConnectionsHandlerFn(cliCtx, queryRoute)).Methods("GET") +func registerQueryRoutes(clientCtx client.Context, r *mux.Router, queryRoute string) { + r.HandleFunc("/ibc/connections", queryConnectionsHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/ibc/connections/{%s}", RestConnectionID), queryConnectionHandlerFn(clientCtx, queryRoute)).Methods("GET") + r.HandleFunc("/ibc/clients/connections", queryClientsConnectionsHandlerFn(clientCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/ibc/clients/{%s}/connections", RestClientID), queryClientConnectionsHandlerFn(clientCtx, queryRoute)).Methods("GET") } // queryConnectionsHandlerFn implements connections querying route @@ -30,26 +30,26 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, queryRoute st // @Failure 400 {object} rest.ErrorResponse "Bad Request" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/connections [get] -func queryClientsConnectionsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryClientsConnectionsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { _, page, limit, err := rest.ParseHTTPArgsWithLimit(r, 0) if rest.CheckBadRequestError(w, err) { return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - connections, height, err := utils.QueryAllConnections(cliCtx, page, limit) + connections, height, err := utils.QueryAllConnections(clientCtx, page, limit) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, connections) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, connections) } } @@ -64,25 +64,25 @@ func queryClientsConnectionsHandlerFn(cliCtx context.CLIContext) http.HandlerFun // @Failure 400 {object} rest.ErrorResponse "Invalid connection id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/connections/{connection-id} [get] -func queryConnectionHandlerFn(cliCtx context.CLIContext, _ string) http.HandlerFunc { +func queryConnectionHandlerFn(clientCtx client.Context, _ string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) connectionID := vars[RestConnectionID] prove := rest.ParseQueryParamBool(r, flags.FlagProve) - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - connRes, err := utils.QueryConnection(cliCtx, connectionID, prove) + connRes, err := utils.QueryConnection(clientCtx, connectionID, prove) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - cliCtx = cliCtx.WithHeight(int64(connRes.ProofHeight)) - rest.PostProcessResponse(w, cliCtx, connRes) + clientCtx = clientCtx.WithHeight(int64(connRes.ProofHeight)) + rest.PostProcessResponse(w, clientCtx, connRes) } } @@ -97,26 +97,26 @@ func queryConnectionHandlerFn(cliCtx context.CLIContext, _ string) http.HandlerF // @Failure 400 {object} rest.ErrorResponse "Bad Request" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/clients/connections [get] -func queryConnectionsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryConnectionsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { _, page, limit, err := rest.ParseHTTPArgsWithLimit(r, 0) if rest.CheckBadRequestError(w, err) { return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - connectionsPaths, height, err := utils.QueryAllClientConnectionPaths(cliCtx, page, limit) + connectionsPaths, height, err := utils.QueryAllClientConnectionPaths(clientCtx, page, limit) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, connectionsPaths) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, connectionsPaths) } } @@ -131,24 +131,24 @@ func queryConnectionsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Failure 400 {object} rest.ErrorResponse "Invalid client id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/clients/{client-id}/connections [get] -func queryClientConnectionsHandlerFn(cliCtx context.CLIContext, _ string) http.HandlerFunc { +func queryClientConnectionsHandlerFn(clientCtx client.Context, _ string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) clientID := vars[RestClientID] prove := rest.ParseQueryParamBool(r, flags.FlagProve) - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - connPathsRes, err := utils.QueryClientConnections(cliCtx, clientID, prove) + connPathsRes, err := utils.QueryClientConnections(clientCtx, clientID, prove) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - cliCtx = cliCtx.WithHeight(int64(connPathsRes.ProofHeight)) - rest.PostProcessResponse(w, cliCtx, connPathsRes) + clientCtx = clientCtx.WithHeight(int64(connPathsRes.ProofHeight)) + rest.PostProcessResponse(w, clientCtx, connPathsRes) } } diff --git a/x/ibc/03-connection/client/rest/rest.go b/x/ibc/03-connection/client/rest/rest.go index 7d1a42f73b70..04e039d0d9d2 100644 --- a/x/ibc/03-connection/client/rest/rest.go +++ b/x/ibc/03-connection/client/rest/rest.go @@ -3,7 +3,7 @@ package rest import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/types/rest" commitmenttypes "github.com/cosmos/cosmos-sdk/x/ibc/23-commitment/types" ) @@ -14,9 +14,9 @@ const ( ) // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, queryRoute string) { - registerQueryRoutes(cliCtx, r, queryRoute) - registerTxRoutes(cliCtx, r) +func RegisterRoutes(clientCtx client.Context, r *mux.Router, queryRoute string) { + registerQueryRoutes(clientCtx, r, queryRoute) + registerTxRoutes(clientCtx, r) } // ConnectionOpenInitReq defines the properties of a connection open init request's body. diff --git a/x/ibc/03-connection/client/rest/tx.go b/x/ibc/03-connection/client/rest/tx.go index d119fde64785..ab74a0c7de60 100644 --- a/x/ibc/03-connection/client/rest/tx.go +++ b/x/ibc/03-connection/client/rest/tx.go @@ -6,18 +6,18 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" "github.com/cosmos/cosmos-sdk/x/ibc/03-connection/types" ) -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/ibc/connections/open-init", connectionOpenInitHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc("/ibc/connections/open-try", connectionOpenTryHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/ibc/connections/{%s}/open-ack", RestConnectionID), connectionOpenAckHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/ibc/connections/{%s}/open-confirm", RestConnectionID), connectionOpenConfirmHandlerFn(cliCtx)).Methods("POST") +func registerTxRoutes(clientCtx client.Context, r *mux.Router) { + r.HandleFunc("/ibc/connections/open-init", connectionOpenInitHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc("/ibc/connections/open-try", connectionOpenTryHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/ibc/connections/{%s}/open-ack", RestConnectionID), connectionOpenAckHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/ibc/connections/{%s}/open-confirm", RestConnectionID), connectionOpenConfirmHandlerFn(clientCtx)).Methods("POST") } // connectionOpenInitHandlerFn implements a connection open init handler @@ -30,10 +30,10 @@ func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { // @Success 200 {object} PostConnectionOpenInit "OK" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/connections/open-init [post] -func connectionOpenInitHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func connectionOpenInitHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req ConnectionOpenInitReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -59,7 +59,7 @@ func connectionOpenInitHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } @@ -73,10 +73,10 @@ func connectionOpenInitHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Success 200 {object} PostConnectionOpenTry "OK" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/connections/open-try [post] -func connectionOpenTryHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func connectionOpenTryHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req ConnectionOpenTryReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -104,7 +104,7 @@ func connectionOpenTryHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } @@ -120,13 +120,13 @@ func connectionOpenTryHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Failure 400 {object} rest.ErrorResponse "Invalid connection id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/connections/{connection-id}/open-ack [post] -func connectionOpenAckHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func connectionOpenAckHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) connectionID := vars[RestConnectionID] var req ConnectionOpenAckReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -152,7 +152,7 @@ func connectionOpenAckHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } @@ -168,13 +168,13 @@ func connectionOpenAckHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Failure 400 {object} rest.ErrorResponse "Invalid connection id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/connections/{connection-id}/open-confirm [post] -func connectionOpenConfirmHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func connectionOpenConfirmHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) connectionID := vars[RestConnectionID] var req ConnectionOpenConfirmReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -199,6 +199,6 @@ func connectionOpenConfirmHandlerFn(cliCtx context.CLIContext) http.HandlerFunc return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/ibc/03-connection/client/utils/utils.go b/x/ibc/03-connection/client/utils/utils.go index 28872046a7e4..c5e1c275e662 100644 --- a/x/ibc/03-connection/client/utils/utils.go +++ b/x/ibc/03-connection/client/utils/utils.go @@ -8,7 +8,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/ibc/03-connection/types" commitmenttypes "github.com/cosmos/cosmos-sdk/x/ibc/23-commitment/types" @@ -17,21 +17,21 @@ import ( // QueryAllConnections returns all the connections. It _does not_ return // any merkle proof. -func QueryAllConnections(cliCtx context.CLIContext, page, limit int) ([]types.ConnectionEnd, int64, error) { +func QueryAllConnections(clientCtx client.Context, page, limit int) ([]types.ConnectionEnd, int64, error) { params := types.NewQueryAllConnectionsParams(page, limit) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if err != nil { return nil, 0, fmt.Errorf("failed to marshal query params: %w", err) } route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAllConnections) - res, height, err := cliCtx.QueryWithData(route, bz) + res, height, err := clientCtx.QueryWithData(route, bz) if err != nil { return nil, 0, err } var connections []types.ConnectionEnd - err = cliCtx.Codec.UnmarshalJSON(res, &connections) + err = clientCtx.Codec.UnmarshalJSON(res, &connections) if err != nil { return nil, 0, fmt.Errorf("failed to unmarshal connections: %w", err) } @@ -41,7 +41,7 @@ func QueryAllConnections(cliCtx context.CLIContext, page, limit int) ([]types.Co // QueryConnection queries the store to get a connection end and a merkle // proof. func QueryConnection( - cliCtx context.CLIContext, connectionID string, prove bool, + clientCtx client.Context, connectionID string, prove bool, ) (types.ConnectionResponse, error) { req := abci.RequestQuery{ Path: "store/ibc/key", @@ -49,13 +49,13 @@ func QueryConnection( Prove: prove, } - res, err := cliCtx.QueryABCI(req) + res, err := clientCtx.QueryABCI(req) if err != nil { return types.ConnectionResponse{}, err } var connection types.ConnectionEnd - if err := cliCtx.Codec.UnmarshalBinaryBare(res.Value, &connection); err != nil { + if err := clientCtx.Codec.UnmarshalBinaryBare(res.Value, &connection); err != nil { return types.ConnectionResponse{}, err } @@ -66,21 +66,21 @@ func QueryConnection( // QueryAllClientConnectionPaths returns all the client connections paths. It // _does not_ return any merkle proof. -func QueryAllClientConnectionPaths(cliCtx context.CLIContext, page, limit int) ([]types.ConnectionPaths, int64, error) { +func QueryAllClientConnectionPaths(clientCtx client.Context, page, limit int) ([]types.ConnectionPaths, int64, error) { params := types.NewQueryAllConnectionsParams(page, limit) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if err != nil { return nil, 0, fmt.Errorf("failed to marshal query params: %w", err) } route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAllClientConnections) - res, height, err := cliCtx.QueryWithData(route, bz) + res, height, err := clientCtx.QueryWithData(route, bz) if err != nil { return nil, 0, err } var connectionPaths []types.ConnectionPaths - err = cliCtx.Codec.UnmarshalJSON(res, &connectionPaths) + err = clientCtx.Codec.UnmarshalJSON(res, &connectionPaths) if err != nil { return nil, 0, fmt.Errorf("failed to unmarshal client connection paths: %w", err) } @@ -90,7 +90,7 @@ func QueryAllClientConnectionPaths(cliCtx context.CLIContext, page, limit int) ( // QueryClientConnections queries the store to get the registered connection paths // registered for a particular client and a merkle proof. func QueryClientConnections( - cliCtx context.CLIContext, clientID string, prove bool, + clientCtx client.Context, clientID string, prove bool, ) (types.ClientConnectionsResponse, error) { req := abci.RequestQuery{ Path: "store/ibc/key", @@ -98,13 +98,13 @@ func QueryClientConnections( Prove: prove, } - res, err := cliCtx.QueryABCI(req) + res, err := clientCtx.QueryABCI(req) if err != nil { return types.ClientConnectionsResponse{}, err } var paths []string - if err := cliCtx.Codec.UnmarshalBinaryBare(res.Value, &paths); err != nil { + if err := clientCtx.Codec.UnmarshalBinaryBare(res.Value, &paths); err != nil { return types.ClientConnectionsResponse{}, err } diff --git a/x/ibc/03-connection/module.go b/x/ibc/03-connection/module.go index d4d7d931c97b..28ca1f89dc8a 100644 --- a/x/ibc/03-connection/module.go +++ b/x/ibc/03-connection/module.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/mux" "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/ibc/03-connection/client/cli" "github.com/cosmos/cosmos-sdk/x/ibc/03-connection/client/rest" @@ -28,6 +28,6 @@ func GetQueryCmd(cdc *codec.Codec, queryRoute string) *cobra.Command { } // RegisterRESTRoutes registers the REST routes for the IBC connections. -func RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, queryRoute string) { - rest.RegisterRoutes(ctx, rtr, fmt.Sprintf("%s/%s", queryRoute, SubModuleName)) +func RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router, queryRoute string) { + rest.RegisterRoutes(clientCtx, rtr, fmt.Sprintf("%s/%s", queryRoute, SubModuleName)) } diff --git a/x/ibc/04-channel/client/cli/query.go b/x/ibc/04-channel/client/cli/query.go index aecbde5b6f3a..e789b926281e 100644 --- a/x/ibc/04-channel/client/cli/query.go +++ b/x/ibc/04-channel/client/cli/query.go @@ -7,7 +7,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/version" @@ -28,18 +28,18 @@ $ %s query ibc channel end [port-id] [channel-id] Example: fmt.Sprintf("%s query ibc channel end [port-id] [channel-id]", version.ClientName), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) portID := args[0] channelID := args[1] prove := viper.GetBool(flags.FlagProve) - channelRes, err := utils.QueryChannel(cliCtx, portID, channelID, prove) + channelRes, err := utils.QueryChannel(clientCtx, portID, channelID, prove) if err != nil { return err } - cliCtx = cliCtx.WithHeight(int64(channelRes.ProofHeight)) - return cliCtx.PrintOutput(channelRes) + clientCtx = clientCtx.WithHeight(int64(channelRes.ProofHeight)) + return clientCtx.PrintOutput(channelRes) }, } cmd.Flags().Bool(flags.FlagProve, true, "show proofs for the query results") diff --git a/x/ibc/04-channel/client/cli/tx.go b/x/ibc/04-channel/client/cli/tx.go index b255c2e29610..336f53f35080 100644 --- a/x/ibc/04-channel/client/cli/tx.go +++ b/x/ibc/04-channel/client/cli/tx.go @@ -8,7 +8,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" @@ -32,7 +32,7 @@ func GetMsgChannelOpenInitCmd(storeKey string, cdc *codec.Codec) *cobra.Command RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) portID := args[0] channelID := args[1] @@ -44,13 +44,13 @@ func GetMsgChannelOpenInitCmd(storeKey string, cdc *codec.Codec) *cobra.Command msg := types.NewMsgChannelOpenInit( portID, channelID, version, order, hops, - counterpartyPortID, counterpartyChannelID, cliCtx.GetFromAddress(), + counterpartyPortID, counterpartyChannelID, clientCtx.GetFromAddress(), ) if err := msg.ValidateBasic(); err != nil { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } @@ -69,7 +69,7 @@ func GetMsgChannelOpenTryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) portID := args[0] channelID := args[1] @@ -79,7 +79,7 @@ func GetMsgChannelOpenTryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { order := channelOrder() version := viper.GetString(FlagIBCVersion) // TODO: diferenciate between channel and counterparty versions - proofInit, err := connectionutils.ParseProof(cliCtx.Codec, args[5]) + proofInit, err := connectionutils.ParseProof(clientCtx.Codec, args[5]) if err != nil { return err } @@ -92,13 +92,13 @@ func GetMsgChannelOpenTryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { msg := types.NewMsgChannelOpenTry( portID, channelID, version, order, hops, counterpartyPortID, counterpartyChannelID, version, - proofInit, uint64(proofHeight), cliCtx.GetFromAddress(), + proofInit, uint64(proofHeight), clientCtx.GetFromAddress(), ) if err := msg.ValidateBasic(); err != nil { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } cmd.Flags().Bool(FlagOrdered, true, "Pass flag for opening ordered channels") @@ -116,13 +116,13 @@ func GetMsgChannelOpenAckCmd(storeKey string, cdc *codec.Codec) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) portID := args[0] channelID := args[1] version := viper.GetString(FlagIBCVersion) // TODO: diferenciate between channel and counterparty versions - proofTry, err := connectionutils.ParseProof(cliCtx.Codec, args[5]) + proofTry, err := connectionutils.ParseProof(clientCtx.Codec, args[5]) if err != nil { return err } @@ -133,13 +133,13 @@ func GetMsgChannelOpenAckCmd(storeKey string, cdc *codec.Codec) *cobra.Command { } msg := types.NewMsgChannelOpenAck( - portID, channelID, version, proofTry, uint64(proofHeight), cliCtx.GetFromAddress(), + portID, channelID, version, proofTry, uint64(proofHeight), clientCtx.GetFromAddress(), ) if err := msg.ValidateBasic(); err != nil { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } cmd.Flags().String(FlagIBCVersion, "1.0.0", "supported IBC version") @@ -155,12 +155,12 @@ func GetMsgChannelOpenConfirmCmd(storeKey string, cdc *codec.Codec) *cobra.Comma RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) portID := args[0] channelID := args[1] - proofAck, err := connectionutils.ParseProof(cliCtx.Codec, args[5]) + proofAck, err := connectionutils.ParseProof(clientCtx.Codec, args[5]) if err != nil { return err } @@ -171,13 +171,13 @@ func GetMsgChannelOpenConfirmCmd(storeKey string, cdc *codec.Codec) *cobra.Comma } msg := types.NewMsgChannelOpenConfirm( - portID, channelID, proofAck, uint64(proofHeight), cliCtx.GetFromAddress(), + portID, channelID, proofAck, uint64(proofHeight), clientCtx.GetFromAddress(), ) if err := msg.ValidateBasic(); err != nil { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } } @@ -191,17 +191,17 @@ func GetMsgChannelCloseInitCmd(storeKey string, cdc *codec.Codec) *cobra.Command RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) portID := args[0] channelID := args[1] - msg := types.NewMsgChannelCloseInit(portID, channelID, cliCtx.GetFromAddress()) + msg := types.NewMsgChannelCloseInit(portID, channelID, clientCtx.GetFromAddress()) if err := msg.ValidateBasic(); err != nil { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } } @@ -215,12 +215,12 @@ func GetMsgChannelCloseConfirmCmd(storeKey string, cdc *codec.Codec) *cobra.Comm RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) portID := args[0] channelID := args[1] - proofInit, err := connectionutils.ParseProof(cliCtx.Codec, args[5]) + proofInit, err := connectionutils.ParseProof(clientCtx.Codec, args[5]) if err != nil { return err } @@ -231,13 +231,13 @@ func GetMsgChannelCloseConfirmCmd(storeKey string, cdc *codec.Codec) *cobra.Comm } msg := types.NewMsgChannelCloseConfirm( - portID, channelID, proofInit, uint64(proofHeight), cliCtx.GetFromAddress(), + portID, channelID, proofInit, uint64(proofHeight), clientCtx.GetFromAddress(), ) if err := msg.ValidateBasic(); err != nil { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } } diff --git a/x/ibc/04-channel/client/rest/query.go b/x/ibc/04-channel/client/rest/query.go index 30a833f92c49..fa22d7c7f467 100644 --- a/x/ibc/04-channel/client/rest/query.go +++ b/x/ibc/04-channel/client/rest/query.go @@ -6,14 +6,14 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/client/utils" ) -func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, queryRoute string) { - r.HandleFunc(fmt.Sprintf("/ibc/ports/{%s}/channels/{%s}", RestPortID, RestChannelID), queryChannelHandlerFn(cliCtx, queryRoute)).Methods("GET") +func registerQueryRoutes(clientCtx client.Context, r *mux.Router, queryRoute string) { + r.HandleFunc(fmt.Sprintf("/ibc/ports/{%s}/channels/{%s}", RestPortID, RestChannelID), queryChannelHandlerFn(clientCtx, queryRoute)).Methods("GET") } // queryChannelHandlerFn implements a channel querying route @@ -28,25 +28,25 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, queryRoute st // @Failure 400 {object} rest.ErrorResponse "Invalid port id or channel id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/ports/{port-id}/channels/{channel-id} [get] -func queryChannelHandlerFn(cliCtx context.CLIContext, _ string) http.HandlerFunc { +func queryChannelHandlerFn(clientCtx client.Context, _ string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) portID := vars[RestPortID] channelID := vars[RestChannelID] prove := rest.ParseQueryParamBool(r, flags.FlagProve) - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - channelRes, err := utils.QueryChannel(cliCtx, portID, channelID, prove) + channelRes, err := utils.QueryChannel(clientCtx, portID, channelID, prove) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - cliCtx = cliCtx.WithHeight(int64(channelRes.ProofHeight)) - rest.PostProcessResponse(w, cliCtx, channelRes) + clientCtx = clientCtx.WithHeight(int64(channelRes.ProofHeight)) + rest.PostProcessResponse(w, clientCtx, channelRes) } } diff --git a/x/ibc/04-channel/client/rest/rest.go b/x/ibc/04-channel/client/rest/rest.go index d91eae7023cc..807dcbd4e01e 100644 --- a/x/ibc/04-channel/client/rest/rest.go +++ b/x/ibc/04-channel/client/rest/rest.go @@ -3,7 +3,7 @@ package rest import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/types" commitmenttypes "github.com/cosmos/cosmos-sdk/x/ibc/23-commitment/types" @@ -15,9 +15,9 @@ const ( ) // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, queryRoute string) { - registerQueryRoutes(cliCtx, r, queryRoute) - registerTxRoutes(cliCtx, r) +func RegisterRoutes(clientCtx client.Context, r *mux.Router, queryRoute string) { + registerQueryRoutes(clientCtx, r, queryRoute) + registerTxRoutes(clientCtx, r) } // ChannelOpenInitReq defines the properties of a channel open init request's body. diff --git a/x/ibc/04-channel/client/rest/tx.go b/x/ibc/04-channel/client/rest/tx.go index 4dd533932779..39439283d867 100644 --- a/x/ibc/04-channel/client/rest/tx.go +++ b/x/ibc/04-channel/client/rest/tx.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" @@ -14,14 +14,14 @@ import ( ) // RegisterRoutes - Central function to define routes that get registered by the main application -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/ibc/channels/open-init", channelOpenInitHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc("/ibc/channels/open-try", channelOpenTryHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/ibc/ports/{%s}/channels/{%s}/open-ack", RestPortID, RestChannelID), channelOpenAckHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/ibc/ports/{%s}/channels/{%s}/open-confirm", RestPortID, RestChannelID), channelOpenConfirmHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/ibc/ports/{%s}/channels/{%s}/close-init", RestPortID, RestChannelID), channelCloseInitHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/ibc/ports/{%s}/channels/{%s}/close-confirm", RestPortID, RestChannelID), channelCloseConfirmHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc("/ibc/packets/receive", recvPacketHandlerFn(cliCtx)).Methods("POST") +func registerTxRoutes(clientCtx client.Context, r *mux.Router) { + r.HandleFunc("/ibc/channels/open-init", channelOpenInitHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc("/ibc/channels/open-try", channelOpenTryHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/ibc/ports/{%s}/channels/{%s}/open-ack", RestPortID, RestChannelID), channelOpenAckHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/ibc/ports/{%s}/channels/{%s}/open-confirm", RestPortID, RestChannelID), channelOpenConfirmHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/ibc/ports/{%s}/channels/{%s}/close-init", RestPortID, RestChannelID), channelCloseInitHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/ibc/ports/{%s}/channels/{%s}/close-confirm", RestPortID, RestChannelID), channelCloseConfirmHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc("/ibc/packets/receive", recvPacketHandlerFn(clientCtx)).Methods("POST") } // channelOpenInitHandlerFn implements a channel open init handler @@ -34,10 +34,10 @@ func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { // @Success 200 {object} PostChannelOpenInit "OK" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/channels/open-init [post] -func channelOpenInitHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func channelOpenInitHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req ChannelOpenInitReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -69,7 +69,7 @@ func channelOpenInitHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } @@ -83,10 +83,10 @@ func channelOpenInitHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Success 200 {object} PostChannelOpenTry "OK" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/channels/open-try [post] -func channelOpenTryHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func channelOpenTryHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req ChannelOpenTryReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -121,7 +121,7 @@ func channelOpenTryHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } @@ -138,14 +138,14 @@ func channelOpenTryHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Failure 400 {object} rest.ErrorResponse "Invalid port id or channel id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/ports/{port-id}/channels/{channel-id}/open-ack [post] -func channelOpenAckHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func channelOpenAckHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) portID := vars[RestPortID] channelID := vars[RestChannelID] var req ChannelOpenAckReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -175,7 +175,7 @@ func channelOpenAckHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } @@ -192,14 +192,14 @@ func channelOpenAckHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Failure 400 {object} rest.ErrorResponse "Invalid port id or channel id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/ports/{port-id}/channels/{channel-id}/open-confirm [post] -func channelOpenConfirmHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func channelOpenConfirmHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) portID := vars[RestPortID] channelID := vars[RestChannelID] var req ChannelOpenConfirmReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -228,7 +228,7 @@ func channelOpenConfirmHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } @@ -245,14 +245,14 @@ func channelOpenConfirmHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Failure 400 {object} rest.ErrorResponse "Invalid port id or channel id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/ports/{port-id}/channels/{channel-id}/close-init [post] -func channelCloseInitHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func channelCloseInitHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) portID := vars[RestPortID] channelID := vars[RestChannelID] var req ChannelCloseInitReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -279,7 +279,7 @@ func channelCloseInitHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } @@ -296,14 +296,14 @@ func channelCloseInitHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Failure 400 {object} rest.ErrorResponse "Invalid port id or channel id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/ports/{port-id}/channels/{channel-id}/close-confirm [post] -func channelCloseConfirmHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func channelCloseConfirmHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) portID := vars[RestPortID] channelID := vars[RestChannelID] var req ChannelCloseConfirmReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -332,7 +332,7 @@ func channelCloseConfirmHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } @@ -346,10 +346,10 @@ func channelCloseConfirmHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Success 200 {object} PostRecvPacket "OK" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/packets/receive [post] -func recvPacketHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func recvPacketHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req RecvPacketReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -377,6 +377,6 @@ func recvPacketHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/ibc/04-channel/client/utils/utils.go b/x/ibc/04-channel/client/utils/utils.go index 9f5302e76bfb..e670b3b4909f 100644 --- a/x/ibc/04-channel/client/utils/utils.go +++ b/x/ibc/04-channel/client/utils/utils.go @@ -3,14 +3,14 @@ package utils import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/types" host "github.com/cosmos/cosmos-sdk/x/ibc/24-host" ) // QueryPacket returns a packet from the store func QueryPacket( - ctx context.CLIContext, portID, channelID string, + ctx client.Context, portID, channelID string, sequence, timeoutHeight, timeoutTimestamp uint64, prove bool, ) (types.PacketResponse, error) { req := abci.RequestQuery{ @@ -49,7 +49,7 @@ func QueryPacket( // QueryChannel queries the store to get a channel and a merkle proof. func QueryChannel( - ctx context.CLIContext, portID, channelID string, prove bool, + ctx client.Context, portID, channelID string, prove bool, ) (types.ChannelResponse, error) { req := abci.RequestQuery{ Path: "store/ibc/key", diff --git a/x/ibc/04-channel/module.go b/x/ibc/04-channel/module.go index 7fb21535e948..c88df5c2a545 100644 --- a/x/ibc/04-channel/module.go +++ b/x/ibc/04-channel/module.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/mux" "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/client/cli" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/client/rest" @@ -18,8 +18,8 @@ func Name() string { } // RegisterRESTRoutes registers the REST routes for the IBC channel -func RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, queryRoute string) { - rest.RegisterRoutes(ctx, rtr, fmt.Sprintf("%s/%s", queryRoute, SubModuleName)) +func RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router, queryRoute string) { + rest.RegisterRoutes(clientCtx, rtr, fmt.Sprintf("%s/%s", queryRoute, SubModuleName)) } // GetTxCmd returns the root tx command for the IBC connections. diff --git a/x/ibc/07-tendermint/client/cli/tx.go b/x/ibc/07-tendermint/client/cli/tx.go index ed20ffaeb62b..ff261ee616a5 100644 --- a/x/ibc/07-tendermint/client/cli/tx.go +++ b/x/ibc/07-tendermint/client/cli/tx.go @@ -16,7 +16,7 @@ import ( tmmath "github.com/tendermint/tendermint/libs/math" lite "github.com/tendermint/tendermint/lite2" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -43,7 +43,7 @@ func GetCmdCreateClient(cdc *codec.Codec) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc).WithBroadcastMode(flags.BroadcastBlock) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc).WithBroadcastMode(flags.BroadcastBlock) clientID := args[0] @@ -91,14 +91,14 @@ func GetCmdCreateClient(cdc *codec.Codec) *cobra.Command { } msg := ibctmtypes.NewMsgCreateClient( - clientID, header, trustLevel, trustingPeriod, ubdPeriod, maxClockDrift, cliCtx.GetFromAddress(), + clientID, header, trustLevel, trustingPeriod, ubdPeriod, maxClockDrift, clientCtx.GetFromAddress(), ) if err := msg.ValidateBasic(); err != nil { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } cmd.Flags().String(flagTrustLevel, "default", "light client trust level fraction for header updates") @@ -120,7 +120,7 @@ func GetCmdUpdateClient(cdc *codec.Codec) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) clientID := args[0] @@ -136,12 +136,12 @@ func GetCmdUpdateClient(cdc *codec.Codec) *cobra.Command { } } - msg := ibctmtypes.NewMsgUpdateClient(clientID, header, cliCtx.GetFromAddress()) + msg := ibctmtypes.NewMsgUpdateClient(clientID, header, clientCtx.GetFromAddress()) if err := msg.ValidateBasic(); err != nil { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } } @@ -162,7 +162,7 @@ func GetCmdSubmitMisbehaviour(cdc *codec.Codec) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) var ev evidenceexported.Evidence if err := cdc.UnmarshalJSON([]byte(args[0]), &ev); err != nil { @@ -176,12 +176,12 @@ func GetCmdSubmitMisbehaviour(cdc *codec.Codec) *cobra.Command { } } - msg := ibctmtypes.NewMsgSubmitClientMisbehaviour(ev, cliCtx.GetFromAddress()) + msg := ibctmtypes.NewMsgSubmitClientMisbehaviour(ev, clientCtx.GetFromAddress()) if err := msg.ValidateBasic(); err != nil { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } } diff --git a/x/ibc/07-tendermint/client/rest/rest.go b/x/ibc/07-tendermint/client/rest/rest.go index bac3487d471e..198fa8f82ec2 100644 --- a/x/ibc/07-tendermint/client/rest/rest.go +++ b/x/ibc/07-tendermint/client/rest/rest.go @@ -7,7 +7,7 @@ import ( tmmath "github.com/tendermint/tendermint/libs/math" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/types/rest" evidenceexported "github.com/cosmos/cosmos-sdk/x/evidence/exported" ibctmtypes "github.com/cosmos/cosmos-sdk/x/ibc/07-tendermint/types" @@ -20,8 +20,8 @@ const ( ) // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, queryRoute string) { - registerTxRoutes(cliCtx, r) +func RegisterRoutes(clientCtx client.Context, r *mux.Router, queryRoute string) { + registerTxRoutes(clientCtx, r) } // CreateClientReq defines the properties of a create client request's body. diff --git a/x/ibc/07-tendermint/client/rest/tx.go b/x/ibc/07-tendermint/client/rest/tx.go index b0646a887d5c..a6298b79c7ab 100644 --- a/x/ibc/07-tendermint/client/rest/tx.go +++ b/x/ibc/07-tendermint/client/rest/tx.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" @@ -14,10 +14,10 @@ import ( ) // RegisterRoutes - Central function to define routes that get registered by the main application -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/ibc/clients/tendermint", createClientHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/ibc/clients/{%s}/update", RestClientID), updateClientHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/ibc/clients/{%s}/misbehaviour", RestClientID), submitMisbehaviourHandlerFn(cliCtx)).Methods("POST") +func registerTxRoutes(clientCtx client.Context, r *mux.Router) { + r.HandleFunc("/ibc/clients/tendermint", createClientHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/ibc/clients/{%s}/update", RestClientID), updateClientHandlerFn(clientCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/ibc/clients/{%s}/misbehaviour", RestClientID), submitMisbehaviourHandlerFn(clientCtx)).Methods("POST") } // createClientHandlerFn implements a create client handler @@ -30,10 +30,10 @@ func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { // @Success 200 {object} PostCreateClient "OK" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/clients/tendermint [post] -func createClientHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func createClientHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req CreateClientReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -60,7 +60,7 @@ func createClientHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } @@ -76,13 +76,13 @@ func createClientHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Failure 400 {object} rest.ErrorResponse "Invalid client id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/clients/{client-id}/update [post] -func updateClientHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func updateClientHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) clientID := vars[RestClientID] var req UpdateClientReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -109,7 +109,7 @@ func updateClientHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } @@ -124,10 +124,10 @@ func updateClientHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // @Failure 400 {object} rest.ErrorResponse "Invalid client id" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/clients/{client-id}/misbehaviour [post] -func submitMisbehaviourHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func submitMisbehaviourHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req SubmitMisbehaviourReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -149,6 +149,6 @@ func submitMisbehaviourHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/ibc/07-tendermint/module.go b/x/ibc/07-tendermint/module.go index 4f5b32cea681..33966356eef2 100644 --- a/x/ibc/07-tendermint/module.go +++ b/x/ibc/07-tendermint/module.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/mux" "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/ibc/07-tendermint/client/cli" "github.com/cosmos/cosmos-sdk/x/ibc/07-tendermint/client/rest" @@ -19,8 +19,8 @@ func Name() string { } // RegisterRESTRoutes registers the REST routes for the IBC client -func RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, queryRoute string) { - rest.RegisterRoutes(ctx, rtr, fmt.Sprintf("%s/%s", queryRoute, types.SubModuleName)) +func RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router, queryRoute string) { + rest.RegisterRoutes(clientCtx, rtr, fmt.Sprintf("%s/%s", queryRoute, types.SubModuleName)) } // GetTxCmd returns the root tx command for the IBC client diff --git a/x/ibc/09-localhost/client/cli/tx.go b/x/ibc/09-localhost/client/cli/tx.go index 68bc633f119d..31c65784628c 100644 --- a/x/ibc/09-localhost/client/cli/tx.go +++ b/x/ibc/09-localhost/client/cli/tx.go @@ -7,7 +7,7 @@ import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -32,14 +32,14 @@ $ %s tx ibc client localhost create --from node0 --home ../node0/cli --chai RunE: func(cmd *cobra.Command, args []string) error { inBuf := bufio.NewReader(cmd.InOrStdin()) txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc).WithBroadcastMode(flags.BroadcastBlock) + clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc).WithBroadcastMode(flags.BroadcastBlock) - msg := types.NewMsgCreateClient(cliCtx.GetFromAddress()) + msg := types.NewMsgCreateClient(clientCtx.GetFromAddress()) if err := msg.ValidateBasic(); err != nil { return err } - return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg}) }, } return cmd diff --git a/x/ibc/09-localhost/client/rest/rest.go b/x/ibc/09-localhost/client/rest/rest.go index 4c598895bb6d..95c429974ef9 100644 --- a/x/ibc/09-localhost/client/rest/rest.go +++ b/x/ibc/09-localhost/client/rest/rest.go @@ -3,13 +3,13 @@ package rest import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/types/rest" ) // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, queryRoute string) { - registerTxRoutes(cliCtx, r) +func RegisterRoutes(clientCtx client.Context, r *mux.Router, queryRoute string) { + registerTxRoutes(clientCtx, r) } // CreateClientReq defines the properties of a create client request's body. diff --git a/x/ibc/09-localhost/client/rest/tx.go b/x/ibc/09-localhost/client/rest/tx.go index a0d616cb0178..6ae5d7db0fd1 100644 --- a/x/ibc/09-localhost/client/rest/tx.go +++ b/x/ibc/09-localhost/client/rest/tx.go @@ -5,7 +5,7 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" @@ -13,8 +13,8 @@ import ( ) // RegisterRoutes - Central function to define routes that get registered by the main application -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/ibc/clients/localhost", createClientHandlerFn(cliCtx)).Methods("POST") +func registerTxRoutes(clientCtx client.Context, r *mux.Router) { + r.HandleFunc("/ibc/clients/localhost", createClientHandlerFn(clientCtx)).Methods("POST") } // createClientHandlerFn implements a create client handler @@ -27,10 +27,10 @@ func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { // @Success 200 {object} PostCreateClient "OK" // @Failure 500 {object} rest.ErrorResponse "Internal Server Error" // @Router /ibc/clients/localhost [post] -func createClientHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func createClientHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req CreateClientReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -51,6 +51,6 @@ func createClientHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/ibc/09-localhost/module.go b/x/ibc/09-localhost/module.go index c9a9d14171c1..13d499390d7e 100644 --- a/x/ibc/09-localhost/module.go +++ b/x/ibc/09-localhost/module.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/mux" "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/ibc/09-localhost/client/cli" "github.com/cosmos/cosmos-sdk/x/ibc/09-localhost/client/rest" @@ -19,8 +19,8 @@ func Name() string { } // RegisterRESTRoutes registers the REST routes for the IBC localhost client -func RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, queryRoute string) { - rest.RegisterRoutes(ctx, rtr, fmt.Sprintf("%s/%s", queryRoute, types.SubModuleName)) +func RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router, queryRoute string) { + rest.RegisterRoutes(clientCtx, rtr, fmt.Sprintf("%s/%s", queryRoute, types.SubModuleName)) } // GetTxCmd returns the root tx command for the IBC localhost client diff --git a/x/ibc/client/rest/rest.go b/x/ibc/client/rest/rest.go index 6f470ee05da5..7fd8a89ebdbb 100644 --- a/x/ibc/client/rest/rest.go +++ b/x/ibc/client/rest/rest.go @@ -3,8 +3,8 @@ package rest import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" - client "github.com/cosmos/cosmos-sdk/x/ibc/02-client" + "github.com/cosmos/cosmos-sdk/client" + client2 "github.com/cosmos/cosmos-sdk/x/ibc/02-client" connection "github.com/cosmos/cosmos-sdk/x/ibc/03-connection" channel "github.com/cosmos/cosmos-sdk/x/ibc/04-channel" tendermint "github.com/cosmos/cosmos-sdk/x/ibc/07-tendermint" @@ -12,10 +12,10 @@ import ( ) // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, queryRoute string) { - client.RegisterRESTRoutes(cliCtx, r, queryRoute) - tendermint.RegisterRESTRoutes(cliCtx, r, queryRoute) - localhost.RegisterRESTRoutes(cliCtx, r, queryRoute) - connection.RegisterRESTRoutes(cliCtx, r, queryRoute) - channel.RegisterRESTRoutes(cliCtx, r, queryRoute) +func RegisterRoutes(clientCtx client.Context, r *mux.Router, queryRoute string) { + client2.RegisterRESTRoutes(clientCtx, r, queryRoute) + tendermint.RegisterRESTRoutes(clientCtx, r, queryRoute) + localhost.RegisterRESTRoutes(clientCtx, r, queryRoute) + connection.RegisterRESTRoutes(clientCtx, r, queryRoute) + channel.RegisterRESTRoutes(clientCtx, r, queryRoute) } diff --git a/x/ibc/module.go b/x/ibc/module.go index bac0447cae63..f0e1eff8107d 100644 --- a/x/ibc/module.go +++ b/x/ibc/module.go @@ -10,13 +10,13 @@ import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - client "github.com/cosmos/cosmos-sdk/x/ibc/02-client" + client2 "github.com/cosmos/cosmos-sdk/x/ibc/02-client" host "github.com/cosmos/cosmos-sdk/x/ibc/24-host" "github.com/cosmos/cosmos-sdk/x/ibc/client/cli" "github.com/cosmos/cosmos-sdk/x/ibc/client/rest" @@ -61,13 +61,13 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessag } // RegisterRESTRoutes registers the REST routes for the ibc module. -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { - rest.RegisterRoutes(ctx, rtr, StoreKey) +func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { + rest.RegisterRoutes(clientCtx, rtr, StoreKey) } // GetTxCmd returns the root tx command for the ibc module. -func (AppModuleBasic) GetTxCmd(ctx context.CLIContext) *cobra.Command { - return cli.GetTxCmd(StoreKey, ctx.Codec) +func (AppModuleBasic) GetTxCmd(clientCtx client.Context) *cobra.Command { + return cli.GetTxCmd(StoreKey, clientCtx.Codec) } // GetQueryCmd returns no root query command for the ibc module. @@ -146,7 +146,7 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json // BeginBlock returns the begin blocker for the ibc module. func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { - client.BeginBlocker(ctx, am.keeper.ClientKeeper) + client2.BeginBlocker(ctx, am.keeper.ClientKeeper) } // EndBlock returns the end blocker for the ibc module. It returns no validator diff --git a/x/mint/client/cli/query.go b/x/mint/client/cli/query.go index c11f7394abf5..9815868e8de5 100644 --- a/x/mint/client/cli/query.go +++ b/x/mint/client/cli/query.go @@ -6,7 +6,6 @@ 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" @@ -42,10 +41,10 @@ func GetCmdQueryParams(cdc *codec.Codec) *cobra.Command { Short: "Query the current minting parameters", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParameters) - res, _, err := cliCtx.QueryWithData(route, nil) + res, _, err := clientCtx.QueryWithData(route, nil) if err != nil { return err } @@ -55,7 +54,7 @@ func GetCmdQueryParams(cdc *codec.Codec) *cobra.Command { return err } - return cliCtx.PrintOutput(params) + return clientCtx.PrintOutput(params) }, } } @@ -68,10 +67,10 @@ func GetCmdQueryInflation(cdc *codec.Codec) *cobra.Command { Short: "Query the current minting inflation value", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryInflation) - res, _, err := cliCtx.QueryWithData(route, nil) + res, _, err := clientCtx.QueryWithData(route, nil) if err != nil { return err } @@ -81,7 +80,7 @@ func GetCmdQueryInflation(cdc *codec.Codec) *cobra.Command { return err } - return cliCtx.PrintOutput(inflation) + return clientCtx.PrintOutput(inflation) }, } } @@ -94,10 +93,10 @@ func GetCmdQueryAnnualProvisions(cdc *codec.Codec) *cobra.Command { Short: "Query the current minting annual provisions value", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAnnualProvisions) - res, _, err := cliCtx.QueryWithData(route, nil) + res, _, err := clientCtx.QueryWithData(route, nil) if err != nil { return err } @@ -107,7 +106,7 @@ func GetCmdQueryAnnualProvisions(cdc *codec.Codec) *cobra.Command { return err } - return cliCtx.PrintOutput(inflation) + return clientCtx.PrintOutput(inflation) }, } } diff --git a/x/mint/client/rest/query.go b/x/mint/client/rest/query.go index 7cfb69775fc5..1dccd194c1ad 100644 --- a/x/mint/client/rest/query.go +++ b/x/mint/client/rest/query.go @@ -6,81 +6,81 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/mint/types" ) -func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) { +func registerQueryRoutes(clientCtx client.Context, r *mux.Router) { r.HandleFunc( "/minting/parameters", - queryParamsHandlerFn(cliCtx), + queryParamsHandlerFn(clientCtx), ).Methods("GET") r.HandleFunc( "/minting/inflation", - queryInflationHandlerFn(cliCtx), + queryInflationHandlerFn(clientCtx), ).Methods("GET") r.HandleFunc( "/minting/annual-provisions", - queryAnnualProvisionsHandlerFn(cliCtx), + queryAnnualProvisionsHandlerFn(clientCtx), ).Methods("GET") } -func queryParamsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryParamsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParameters) - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - res, height, err := cliCtx.QueryWithData(route, nil) + res, height, err := clientCtx.QueryWithData(route, nil) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } -func queryInflationHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryInflationHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryInflation) - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - res, height, err := cliCtx.QueryWithData(route, nil) + res, height, err := clientCtx.QueryWithData(route, nil) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } -func queryAnnualProvisionsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryAnnualProvisionsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAnnualProvisions) - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - res, height, err := cliCtx.QueryWithData(route, nil) + res, height, err := clientCtx.QueryWithData(route, nil) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } diff --git a/x/mint/client/rest/rest.go b/x/mint/client/rest/rest.go index 556e14685bac..a159739a0b59 100644 --- a/x/mint/client/rest/rest.go +++ b/x/mint/client/rest/rest.go @@ -3,10 +3,10 @@ package rest import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" ) // RegisterRoutes registers minting module REST handlers on the provided router. -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { - registerQueryRoutes(cliCtx, r) +func RegisterRoutes(clientCtx client.Context, r *mux.Router) { + registerQueryRoutes(clientCtx, r) } diff --git a/x/mint/module.go b/x/mint/module.go index 1c8f1765b74d..1a97a1be6efa 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -9,7 +9,7 @@ import ( "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -58,12 +58,12 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessag } // RegisterRESTRoutes registers the REST routes for the mint module. -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { - rest.RegisterRoutes(ctx, rtr) +func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { + rest.RegisterRoutes(clientCtx, rtr) } // GetTxCmd returns no root tx command for the mint module. -func (AppModuleBasic) GetTxCmd(_ context.CLIContext) *cobra.Command { return nil } +func (AppModuleBasic) GetTxCmd(_ client.Context) *cobra.Command { return nil } // GetQueryCmd returns the root query command for the mint module. func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { diff --git a/x/params/client/cli/query.go b/x/params/client/cli/query.go index 2db58147287f..ce5bc77afd10 100644 --- a/x/params/client/cli/query.go +++ b/x/params/client/cli/query.go @@ -6,7 +6,6 @@ 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" "github.com/cosmos/cosmos-sdk/x/params/types" @@ -35,7 +34,7 @@ func NewQuerySubspaceParamsCmd(m codec.JSONMarshaler) *cobra.Command { Short: "Query for raw parameters by subspace and key", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithJSONMarshaler(m) + clientCtx := client.NewContext().WithJSONMarshaler(m) params := types.NewQuerySubspaceParams(args[0], args[1]) route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParams) @@ -45,7 +44,7 @@ func NewQuerySubspaceParamsCmd(m codec.JSONMarshaler) *cobra.Command { return fmt.Errorf("failed to marshal params: %w", err) } - bz, _, err = cliCtx.QueryWithData(route, bz) + bz, _, err = clientCtx.QueryWithData(route, bz) if err != nil { return err } @@ -55,7 +54,7 @@ func NewQuerySubspaceParamsCmd(m codec.JSONMarshaler) *cobra.Command { return err } - return cliCtx.PrintOutput(resp) + return clientCtx.PrintOutput(resp) }, } diff --git a/x/params/client/cli/tx.go b/x/params/client/cli/tx.go index a02ca0b3162b..7a8cc8c29487 100644 --- a/x/params/client/cli/tx.go +++ b/x/params/client/cli/tx.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" @@ -17,7 +17,7 @@ import ( // NewSubmitParamChangeProposalTxCmd returns a CLI command handler for creating // a parameter change proposal governance transaction. -func NewSubmitParamChangeProposalTxCmd(ctx context.CLIContext) *cobra.Command { +func NewSubmitParamChangeProposalTxCmd(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "param-change [proposal-file]", Args: cobra.ExactArgs(1), @@ -57,14 +57,14 @@ Where proposal.json contains: ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) - proposal, err := paramscutils.ParseParamChangeProposalJSON(ctx.JSONMarshaler, args[0]) + proposal, err := paramscutils.ParseParamChangeProposalJSON(clientCtx.JSONMarshaler, args[0]) if err != nil { return err } - from := cliCtx.GetFromAddress() + from := clientCtx.GetFromAddress() content := paramproposal.NewParameterChangeProposal( proposal.Title, proposal.Description, proposal.Changes.ToParamChanges(), ) @@ -82,7 +82,7 @@ Where proposal.json contains: return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } diff --git a/x/params/client/rest/rest.go b/x/params/client/rest/rest.go index 0893a0bbd5e5..c13545db3b3f 100644 --- a/x/params/client/rest/rest.go +++ b/x/params/client/rest/rest.go @@ -3,7 +3,7 @@ package rest import ( "net/http" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" @@ -15,17 +15,17 @@ import ( // ProposalRESTHandler returns a ProposalRESTHandler that exposes the param // change REST handler with a given sub-route. -func ProposalRESTHandler(cliCtx context.CLIContext) govrest.ProposalRESTHandler { +func ProposalRESTHandler(clientCtx client.Context) govrest.ProposalRESTHandler { return govrest.ProposalRESTHandler{ SubRoute: "param_change", - Handler: postProposalHandlerFn(cliCtx), + Handler: postProposalHandlerFn(clientCtx), } } -func postProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func postProposalHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req paramscutils.ParamChangeProposalReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -44,6 +44,6 @@ func postProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/params/module.go b/x/params/module.go index 9dab3b572fc6..c8008df03514 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -4,14 +4,13 @@ import ( "encoding/json" "math/rand" - "github.com/cosmos/cosmos-sdk/codec/types" - "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/client" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -47,10 +46,10 @@ func (AppModuleBasic) DefaultGenesis(_ codec.JSONMarshaler) json.RawMessage { re func (AppModuleBasic) ValidateGenesis(_ codec.JSONMarshaler, _ json.RawMessage) error { return nil } // RegisterRESTRoutes registers the REST routes for the params module. -func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router) {} +func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) {} // GetTxCmd returns no root tx command for the params module. -func (AppModuleBasic) GetTxCmd(_ context.CLIContext) *cobra.Command { return nil } +func (AppModuleBasic) GetTxCmd(_ client.Context) *cobra.Command { return nil } // GetQueryCmd returns no root query command for the params module. func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } diff --git a/x/slashing/client/cli/query.go b/x/slashing/client/cli/query.go index c5420e12ecec..442096885fbb 100644 --- a/x/slashing/client/cli/query.go +++ b/x/slashing/client/cli/query.go @@ -7,7 +7,6 @@ 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" @@ -48,7 +47,7 @@ $ query slashing signing-info cosmosvalconspub1zcjduepqfhvwcmt7p06fvdge `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) pk, err := sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeConsPub, args[0]) if err != nil { @@ -58,7 +57,7 @@ $ query slashing signing-info cosmosvalconspub1zcjduepqfhvwcmt7p06fvdge consAddr := sdk.ConsAddress(pk.Address()) key := types.ValidatorSigningInfoKey(consAddr) - res, _, err := cliCtx.QueryStore(key, storeName) + res, _, err := clientCtx.QueryStore(key, storeName) if err != nil { return err } @@ -73,7 +72,7 @@ $ query slashing signing-info cosmosvalconspub1zcjduepqfhvwcmt7p06fvdge return err } - return cliCtx.PrintOutput(signingInfo) + return clientCtx.PrintOutput(signingInfo) }, } } @@ -89,17 +88,17 @@ func GetCmdQueryParams(cdc *codec.Codec) *cobra.Command { $ query slashing params `), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) route := fmt.Sprintf("custom/%s/parameters", types.QuerierRoute) - res, _, err := cliCtx.QueryWithData(route, nil) + res, _, err := clientCtx.QueryWithData(route, nil) if err != nil { return err } var params types.Params cdc.MustUnmarshalJSON(res, ¶ms) - return cliCtx.PrintOutput(params) + return clientCtx.PrintOutput(params) }, } } diff --git a/x/slashing/client/cli/tx.go b/x/slashing/client/cli/tx.go index 3cae546e0907..f09f858b2d51 100644 --- a/x/slashing/client/cli/tx.go +++ b/x/slashing/client/cli/tx.go @@ -4,7 +4,6 @@ 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/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" @@ -12,7 +11,7 @@ import ( ) // NewTxCmd returns a root CLI command handler for all x/slashing transaction commands. -func NewTxCmd(ctx context.CLIContext) *cobra.Command { +func NewTxCmd(clientCtx client.Context) *cobra.Command { slashingTxCmd := &cobra.Command{ Use: types.ModuleName, Short: "Slashing transaction subcommands", @@ -21,11 +20,11 @@ func NewTxCmd(ctx context.CLIContext) *cobra.Command { RunE: client.ValidateCmd, } - slashingTxCmd.AddCommand(NewUnjailTxCmd(ctx)) + slashingTxCmd.AddCommand(NewUnjailTxCmd(clientCtx)) return slashingTxCmd } -func NewUnjailTxCmd(ctx context.CLIContext) *cobra.Command { +func NewUnjailTxCmd(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "unjail", Args: cobra.NoArgs, @@ -35,15 +34,15 @@ func NewUnjailTxCmd(ctx context.CLIContext) *cobra.Command { $ tx slashing unjail --from mykey `, RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) - valAddr := cliCtx.GetFromAddress() + valAddr := clientCtx.GetFromAddress() msg := types.NewMsgUnjail(sdk.ValAddress(valAddr)) if err := msg.ValidateBasic(); err != nil { return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } return flags.PostCommands(cmd)[0] diff --git a/x/slashing/client/rest/query.go b/x/slashing/client/rest/query.go index f82ec97afedb..edc54c14377e 100644 --- a/x/slashing/client/rest/query.go +++ b/x/slashing/client/rest/query.go @@ -6,31 +6,31 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) -func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) { +func registerQueryRoutes(clientCtx client.Context, r *mux.Router) { r.HandleFunc( "/slashing/validators/{validatorPubKey}/signing_info", - signingInfoHandlerFn(cliCtx), + signingInfoHandlerFn(clientCtx), ).Methods("GET") r.HandleFunc( "/slashing/signing_infos", - signingInfoHandlerListFn(cliCtx), + signingInfoHandlerListFn(clientCtx), ).Methods("GET") r.HandleFunc( "/slashing/parameters", - queryParamsHandlerFn(cliCtx), + queryParamsHandlerFn(clientCtx), ).Methods("GET") } // http request handler to query signing info -func signingInfoHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func signingInfoHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) pk, err := sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeConsPub, vars["validatorPubKey"]) @@ -38,74 +38,74 @@ func signingInfoHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQuerySigningInfoParams(sdk.ConsAddress(pk.Address())) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySigningInfo) - res, height, err := cliCtx.QueryWithData(route, bz) + res, height, err := clientCtx.QueryWithData(route, bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } // http request handler to query signing info -func signingInfoHandlerListFn(cliCtx context.CLIContext) http.HandlerFunc { +func signingInfoHandlerListFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { _, page, limit, err := rest.ParseHTTPArgsWithLimit(r, 0) if rest.CheckBadRequestError(w, err) { return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQuerySigningInfosParams(page, limit) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckInternalServerError(w, err) { return } route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySigningInfos) - res, height, err := cliCtx.QueryWithData(route, bz) + res, height, err := clientCtx.QueryWithData(route, bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } -func queryParamsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryParamsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } route := fmt.Sprintf("custom/%s/parameters", types.QuerierRoute) - res, height, err := cliCtx.QueryWithData(route, nil) + res, height, err := clientCtx.QueryWithData(route, nil) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } diff --git a/x/slashing/client/rest/rest.go b/x/slashing/client/rest/rest.go index 32515fbe4fbd..cd3c5793b7d8 100644 --- a/x/slashing/client/rest/rest.go +++ b/x/slashing/client/rest/rest.go @@ -3,16 +3,16 @@ package rest import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" ) -func RegisterHandlers(ctx context.CLIContext, r *mux.Router) { - registerQueryRoutes(ctx, r) - registerTxHandlers(ctx, r) +func RegisterHandlers(clientCtx client.Context, r *mux.Router) { + registerQueryRoutes(clientCtx, r) + registerTxHandlers(clientCtx, r) } // RegisterRoutes registers staking-related REST handlers to a router -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { - registerQueryRoutes(cliCtx, r) - registerTxRoutes(cliCtx, r) +func RegisterRoutes(clientCtx client.Context, r *mux.Router) { + registerQueryRoutes(clientCtx, r) + registerTxRoutes(clientCtx, r) } diff --git a/x/slashing/client/rest/tx.go b/x/slashing/client/rest/tx.go index e01536b3e39a..e92b7394e089 100644 --- a/x/slashing/client/rest/tx.go +++ b/x/slashing/client/rest/tx.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" @@ -14,8 +14,8 @@ import ( "github.com/cosmos/cosmos-sdk/x/slashing/types" ) -func registerTxHandlers(ctx context.CLIContext, r *mux.Router) { - r.HandleFunc("/slashing/validators/{validatorAddr}/unjail", NewUnjailRequestHandlerFn(ctx)).Methods("POST") +func registerTxHandlers(clientCtx client.Context, r *mux.Router) { + r.HandleFunc("/slashing/validators/{validatorAddr}/unjail", NewUnjailRequestHandlerFn(clientCtx)).Methods("POST") } // Unjail TX body @@ -25,13 +25,13 @@ type UnjailReq struct { // NewUnjailRequestHandlerFn returns an HTTP REST handler for creating a MsgUnjail // transaction. -func NewUnjailRequestHandlerFn(ctx context.CLIContext) http.HandlerFunc { +func NewUnjailRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) bech32Validator := vars["validatorAddr"] var req UnjailReq - if !rest.ReadRESTReq(w, r, ctx.JSONMarshaler, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.JSONMarshaler, &req) { return } @@ -59,7 +59,7 @@ func NewUnjailRequestHandlerFn(ctx context.CLIContext) http.HandlerFunc { if rest.CheckBadRequestError(w, msg.ValidateBasic()) { return } - tx.WriteGeneratedTxResponse(ctx, w, req.BaseReq, msg) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) } } @@ -69,21 +69,21 @@ func NewUnjailRequestHandlerFn(ctx context.CLIContext) http.HandlerFunc { // TODO: Remove once client-side Protobuf migration has been completed. // --------------------------------------------------------------------------- // ref: https://github.com/cosmos/cosmos-sdk/issues/5864 -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { +func registerTxRoutes(clientCtx client.Context, r *mux.Router) { r.HandleFunc( "/slashing/validators/{validatorAddr}/unjail", - unjailRequestHandlerFn(cliCtx), + unjailRequestHandlerFn(clientCtx), ).Methods("POST") } -func unjailRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func unjailRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) bech32validator := vars["validatorAddr"] var req UnjailReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -112,6 +112,6 @@ func unjailRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/slashing/module.go b/x/slashing/module.go index 0bc65c296c1d..1d95e24395cb 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -10,7 +10,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -62,13 +62,13 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessag } // RegisterRESTRoutes registers the REST routes for the slashing module. -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { - rest.RegisterHandlers(ctx, rtr) +func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { + rest.RegisterHandlers(clientCtx, rtr) } // GetTxCmd returns the root tx command for the slashing module. -func (AppModuleBasic) GetTxCmd(ctx context.CLIContext) *cobra.Command { - return cli.NewTxCmd(ctx) +func (AppModuleBasic) GetTxCmd(clientCtx client.Context) *cobra.Command { + return cli.NewTxCmd(clientCtx) } // GetQueryCmd returns no root query command for the slashing module. diff --git a/x/staking/client/cli/query.go b/x/staking/client/cli/query.go index c215f06b0af1..dd1819e01fe9 100644 --- a/x/staking/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -8,7 +8,6 @@ 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" @@ -60,14 +59,14 @@ $ %s query staking validator cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhff ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) addr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err } - res, _, err := cliCtx.QueryStore(types.GetValidatorKey(addr), storeName) + res, _, err := clientCtx.QueryStore(types.GetValidatorKey(addr), storeName) if err != nil { return err } @@ -81,7 +80,7 @@ $ %s query staking validator cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhff return err } - return cliCtx.PrintOutput(validator) + return clientCtx.PrintOutput(validator) }, } } @@ -102,9 +101,9 @@ $ %s query staking validators ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) - resKVs, _, err := cliCtx.QuerySubspace(types.ValidatorsKey, storeName) + resKVs, _, err := clientCtx.QuerySubspace(types.ValidatorsKey, storeName) if err != nil { return err } @@ -119,7 +118,7 @@ $ %s query staking validators validators = append(validators, validator) } - return cliCtx.PrintOutput(validators) + return clientCtx.PrintOutput(validators) }, } } @@ -140,7 +139,7 @@ $ %s query staking unbonding-delegations-from cosmosvaloper1gghjut3ccd8ay0zduzj6 ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) valAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { @@ -153,14 +152,14 @@ $ %s query staking unbonding-delegations-from cosmosvaloper1gghjut3ccd8ay0zduzj6 } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryValidatorUnbondingDelegations) - res, _, err := cliCtx.QueryWithData(route, bz) + res, _, err := clientCtx.QueryWithData(route, bz) if err != nil { return err } var ubds types.UnbondingDelegations cdc.MustUnmarshalJSON(res, &ubds) - return cliCtx.PrintOutput(ubds) + return clientCtx.PrintOutput(ubds) }, } } @@ -182,7 +181,7 @@ $ %s query staking redelegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fx ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) valSrcAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { @@ -195,7 +194,7 @@ $ %s query staking redelegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fx } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryRedelegations) - res, _, err := cliCtx.QueryWithData(route, bz) + res, _, err := clientCtx.QueryWithData(route, bz) if err != nil { return err } @@ -205,7 +204,7 @@ $ %s query staking redelegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fx return err } - return cliCtx.PrintOutput(resp) + return clientCtx.PrintOutput(resp) }, } } @@ -226,7 +225,7 @@ $ %s query staking delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosm ), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) delAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -244,7 +243,7 @@ $ %s query staking delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosm } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegation) - res, _, err := cliCtx.QueryWithData(route, bz) + res, _, err := clientCtx.QueryWithData(route, bz) if err != nil { return err } @@ -254,7 +253,7 @@ $ %s query staking delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosm return err } - return cliCtx.PrintOutput(resp) + return clientCtx.PrintOutput(resp) }, } } @@ -276,7 +275,7 @@ $ %s query staking delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) delAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -289,7 +288,7 @@ $ %s query staking delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorDelegations) - res, _, err := cliCtx.QueryWithData(route, bz) + res, _, err := clientCtx.QueryWithData(route, bz) if err != nil { return err } @@ -299,7 +298,7 @@ $ %s query staking delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p return err } - return cliCtx.PrintOutput(resp) + return clientCtx.PrintOutput(resp) }, } } @@ -321,7 +320,7 @@ $ %s query staking delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ld ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) valAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { @@ -334,7 +333,7 @@ $ %s query staking delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ld } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryValidatorDelegations) - res, _, err := cliCtx.QueryWithData(route, bz) + res, _, err := clientCtx.QueryWithData(route, bz) if err != nil { return err } @@ -344,7 +343,7 @@ $ %s query staking delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ld return err } - return cliCtx.PrintOutput(resp) + return clientCtx.PrintOutput(resp) }, } } @@ -366,7 +365,7 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7 ), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) valAddr, err := sdk.ValAddressFromBech32(args[1]) if err != nil { @@ -384,7 +383,7 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7 } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryUnbondingDelegation) - res, _, err := cliCtx.QueryWithData(route, bz) + res, _, err := clientCtx.QueryWithData(route, bz) if err != nil { return err } @@ -394,7 +393,7 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7 return err } - return cliCtx.PrintOutput(ubd) + return clientCtx.PrintOutput(ubd) }, } } @@ -416,7 +415,7 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7 ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) delegatorAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -429,7 +428,7 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7 } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorUnbondingDelegations) - res, _, err := cliCtx.QueryWithData(route, bz) + res, _, err := clientCtx.QueryWithData(route, bz) if err != nil { return err } @@ -439,7 +438,7 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7 return err } - return cliCtx.PrintOutput(ubds) + return clientCtx.PrintOutput(ubds) }, } } @@ -461,7 +460,7 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co ), Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) delAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -484,7 +483,7 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryRedelegations) - res, _, err := cliCtx.QueryWithData(route, bz) + res, _, err := clientCtx.QueryWithData(route, bz) if err != nil { return err } @@ -494,7 +493,7 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co return err } - return cliCtx.PrintOutput(resp) + return clientCtx.PrintOutput(resp) }, } } @@ -516,7 +515,7 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) delAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -529,7 +528,7 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryRedelegations) - res, _, err := cliCtx.QueryWithData(route, bz) + res, _, err := clientCtx.QueryWithData(route, bz) if err != nil { return err } @@ -539,7 +538,7 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p return err } - return cliCtx.PrintOutput(resp) + return clientCtx.PrintOutput(resp) }, } } @@ -560,7 +559,7 @@ $ %s query staking historical-info 5 ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) height, err := strconv.ParseInt(args[0], 10, 64) if err != nil || height < 0 { @@ -573,7 +572,7 @@ $ %s query staking historical-info 5 } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryHistoricalInfo) - res, _, err := cliCtx.QueryWithData(route, bz) + res, _, err := clientCtx.QueryWithData(route, bz) if err != nil { return err } @@ -583,7 +582,7 @@ $ %s query staking historical-info 5 return err } - return cliCtx.PrintOutput(resp) + return clientCtx.PrintOutput(resp) }, } } @@ -604,9 +603,9 @@ $ %s query staking pool ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) - bz, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/pool", storeName), nil) + bz, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/pool", storeName), nil) if err != nil { return err } @@ -616,7 +615,7 @@ $ %s query staking pool return err } - return cliCtx.PrintOutput(pool) + return clientCtx.PrintOutput(pool) }, } } @@ -637,17 +636,17 @@ $ %s query staking params ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) route := fmt.Sprintf("custom/%s/%s", storeName, types.QueryParameters) - bz, _, err := cliCtx.QueryWithData(route, nil) + bz, _, err := clientCtx.QueryWithData(route, nil) if err != nil { return err } var params types.Params cdc.MustUnmarshalJSON(bz, ¶ms) - return cliCtx.PrintOutput(params) + return clientCtx.PrintOutput(params) }, } } diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index c3c9c4b6e5e1..efafb272b6ce 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -15,7 +15,6 @@ import ( "github.com/tendermint/tendermint/crypto" "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/tx" sdk "github.com/cosmos/cosmos-sdk/types" @@ -35,7 +34,7 @@ var ( ) // NewTxCmd returns a root CLI command handler for all x/staking transaction commands. -func NewTxCmd(ctx context.CLIContext) *cobra.Command { +func NewTxCmd(clientCtx client.Context) *cobra.Command { stakingTxCmd := &cobra.Command{ Use: types.ModuleName, Short: "Staking transaction subcommands", @@ -45,29 +44,29 @@ func NewTxCmd(ctx context.CLIContext) *cobra.Command { } stakingTxCmd.AddCommand(flags.PostCommands( - NewCreateValidatorCmd(ctx), - NewEditValidatorCmd(ctx), - NewDelegateCmd(ctx), - NewRedelegateCmd(ctx), - NewUnbondCmd(ctx), + NewCreateValidatorCmd(clientCtx), + NewEditValidatorCmd(clientCtx), + NewDelegateCmd(clientCtx), + NewRedelegateCmd(clientCtx), + NewUnbondCmd(clientCtx), )...) return stakingTxCmd } -func NewCreateValidatorCmd(ctx context.CLIContext) *cobra.Command { +func NewCreateValidatorCmd(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "create-validator", Short: "create new validator initialized with a self-delegation to it", RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) - txf := tx.NewFactoryFromCLI(ctx.Input).WithTxGenerator(ctx.TxGenerator).WithAccountRetriever(ctx.AccountRetriever) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) + txf := tx.NewFactoryFromCLI(clientCtx.Input).WithTxGenerator(clientCtx.TxGenerator).WithAccountRetriever(clientCtx.AccountRetriever) - txf, msg, err := NewBuildCreateValidatorMsg(cliCtx, txf) + txf, msg, err := NewBuildCreateValidatorMsg(clientCtx, txf) if err != nil { return err } - return tx.GenerateOrBroadcastTxWithFactory(cliCtx, txf, msg) + return tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, msg) }, } cmd.Flags().AddFlagSet(FsPk) @@ -87,14 +86,14 @@ func NewCreateValidatorCmd(ctx context.CLIContext) *cobra.Command { return cmd } -func NewEditValidatorCmd(ctx context.CLIContext) *cobra.Command { +func NewEditValidatorCmd(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "edit-validator", Short: "edit an existing validator account", RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) - valAddr := cliCtx.GetFromAddress() + valAddr := clientCtx.GetFromAddress() description := types.NewDescription( viper.GetString(FlagMoniker), viper.GetString(FlagIdentity), @@ -133,14 +132,14 @@ func NewEditValidatorCmd(ctx context.CLIContext) *cobra.Command { } // build and sign the transaction, then broadcast to Tendermint - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } return cmd } -func NewDelegateCmd(ctx context.CLIContext) *cobra.Command { +func NewDelegateCmd(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "delegate [validator-addr] [amount]", Args: cobra.ExactArgs(2), @@ -155,14 +154,14 @@ $ %s tx staking delegate cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 10 ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) amount, err := sdk.ParseCoin(args[1]) if err != nil { return err } - delAddr := cliCtx.GetFromAddress() + delAddr := clientCtx.GetFromAddress() valAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err @@ -173,7 +172,7 @@ $ %s tx staking delegate cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 10 return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } cmd.Flags().AddFlagSet(fsDescriptionEdit) @@ -183,7 +182,7 @@ $ %s tx staking delegate cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 10 return cmd } -func NewRedelegateCmd(ctx context.CLIContext) *cobra.Command { +func NewRedelegateCmd(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "redelegate [src-validator-addr] [dst-validator-addr] [amount]", Short: "Redelegate illiquid tokens from one validator to another", @@ -198,9 +197,9 @@ $ %s tx staking redelegate cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) - delAddr := cliCtx.GetFromAddress() + delAddr := clientCtx.GetFromAddress() valSrcAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err @@ -221,14 +220,14 @@ $ %s tx staking redelegate cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } return cmd } -func NewUnbondCmd(ctx context.CLIContext) *cobra.Command { +func NewUnbondCmd(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "unbond [validator-addr] [amount]", Short: "Unbond shares from a validator", @@ -243,9 +242,9 @@ $ %s tx staking unbond cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100s ), ), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) - delAddr := cliCtx.GetFromAddress() + delAddr := clientCtx.GetFromAddress() valAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err @@ -261,20 +260,20 @@ $ %s tx staking unbond cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100s return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } return cmd } -func NewBuildCreateValidatorMsg(cliCtx context.CLIContext, txf tx.Factory) (tx.Factory, sdk.Msg, error) { +func NewBuildCreateValidatorMsg(clientCtx client.Context, txf tx.Factory) (tx.Factory, sdk.Msg, error) { amount, err := sdk.ParseCoin(viper.GetString(FlagAmount)) if err != nil { return txf, nil, err } - valAddr := cliCtx.GetFromAddress() + valAddr := clientCtx.GetFromAddress() pkStr := viper.GetString(FlagPubKey) pk, err := sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeConsPub, pkStr) @@ -408,7 +407,7 @@ func PrepareFlagsForTxCreateValidator( } // BuildCreateValidatorMsg makes a new MsgCreateValidator. -func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr auth.TxBuilder) (auth.TxBuilder, sdk.Msg, error) { +func BuildCreateValidatorMsg(clientCtx client.Context, txBldr auth.TxBuilder) (auth.TxBuilder, sdk.Msg, error) { amounstStr := viper.GetString(FlagAmount) amount, err := sdk.ParseCoin(amounstStr) @@ -416,7 +415,7 @@ func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr auth.TxBuilder) ( return txBldr, nil, err } - valAddr := cliCtx.GetFromAddress() + valAddr := clientCtx.GetFromAddress() pkStr := viper.GetString(FlagPubKey) pk, err := sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeConsPub, pkStr) diff --git a/x/staking/client/rest/query.go b/x/staking/client/rest/query.go index cfac31ad5ecf..1453d70fc90f 100644 --- a/x/staking/client/rest/query.go +++ b/x/staking/client/rest/query.go @@ -8,116 +8,116 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/staking/types" ) -func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) { +func registerQueryRoutes(clientCtx client.Context, r *mux.Router) { // Get all delegations from a delegator r.HandleFunc( "/staking/delegators/{delegatorAddr}/delegations", - delegatorDelegationsHandlerFn(cliCtx), + delegatorDelegationsHandlerFn(clientCtx), ).Methods("GET") // Get all unbonding delegations from a delegator r.HandleFunc( "/staking/delegators/{delegatorAddr}/unbonding_delegations", - delegatorUnbondingDelegationsHandlerFn(cliCtx), + delegatorUnbondingDelegationsHandlerFn(clientCtx), ).Methods("GET") // Get all staking txs (i.e msgs) from a delegator r.HandleFunc( "/staking/delegators/{delegatorAddr}/txs", - delegatorTxsHandlerFn(cliCtx), + delegatorTxsHandlerFn(clientCtx), ).Methods("GET") // Query all validators that a delegator is bonded to r.HandleFunc( "/staking/delegators/{delegatorAddr}/validators", - delegatorValidatorsHandlerFn(cliCtx), + delegatorValidatorsHandlerFn(clientCtx), ).Methods("GET") // Query a validator that a delegator is bonded to r.HandleFunc( "/staking/delegators/{delegatorAddr}/validators/{validatorAddr}", - delegatorValidatorHandlerFn(cliCtx), + delegatorValidatorHandlerFn(clientCtx), ).Methods("GET") // Query a delegation between a delegator and a validator r.HandleFunc( "/staking/delegators/{delegatorAddr}/delegations/{validatorAddr}", - delegationHandlerFn(cliCtx), + delegationHandlerFn(clientCtx), ).Methods("GET") // Query all unbonding delegations between a delegator and a validator r.HandleFunc( "/staking/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}", - unbondingDelegationHandlerFn(cliCtx), + unbondingDelegationHandlerFn(clientCtx), ).Methods("GET") // Query redelegations (filters in query params) r.HandleFunc( "/staking/redelegations", - redelegationsHandlerFn(cliCtx), + redelegationsHandlerFn(clientCtx), ).Methods("GET") // Get all validators r.HandleFunc( "/staking/validators", - validatorsHandlerFn(cliCtx), + validatorsHandlerFn(clientCtx), ).Methods("GET") // Get a single validator info r.HandleFunc( "/staking/validators/{validatorAddr}", - validatorHandlerFn(cliCtx), + validatorHandlerFn(clientCtx), ).Methods("GET") // Get all delegations to a validator r.HandleFunc( "/staking/validators/{validatorAddr}/delegations", - validatorDelegationsHandlerFn(cliCtx), + validatorDelegationsHandlerFn(clientCtx), ).Methods("GET") // Get all unbonding delegations from a validator r.HandleFunc( "/staking/validators/{validatorAddr}/unbonding_delegations", - validatorUnbondingDelegationsHandlerFn(cliCtx), + validatorUnbondingDelegationsHandlerFn(clientCtx), ).Methods("GET") // Get HistoricalInfo at a given height r.HandleFunc( "/staking/historical_info/{height}", - historicalInfoHandlerFn(cliCtx), + historicalInfoHandlerFn(clientCtx), ).Methods("GET") // Get the current state of the staking pool r.HandleFunc( "/staking/pool", - poolHandlerFn(cliCtx), + poolHandlerFn(clientCtx), ).Methods("GET") // Get the current staking parameter values r.HandleFunc( "/staking/parameters", - paramsHandlerFn(cliCtx), + paramsHandlerFn(clientCtx), ).Methods("GET") } // HTTP request handler to query a delegator delegations -func delegatorDelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return queryDelegator(cliCtx, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegatorDelegations)) +func delegatorDelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { + return queryDelegator(clientCtx, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegatorDelegations)) } // HTTP request handler to query a delegator unbonding delegations -func delegatorUnbondingDelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return queryDelegator(cliCtx, "custom/staking/delegatorUnbondingDelegations") +func delegatorUnbondingDelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { + return queryDelegator(clientCtx, "custom/staking/delegatorUnbondingDelegations") } // HTTP request handler to query all staking txs (msgs) from a delegator -func delegatorTxsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func delegatorTxsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var typesQuerySlice []string @@ -128,7 +128,7 @@ func delegatorTxsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } @@ -171,7 +171,7 @@ func delegatorTxsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } for _, action := range actions { - foundTxs, errQuery := queryTxs(cliCtx, action, delegatorAddr) + foundTxs, errQuery := queryTxs(clientCtx, action, delegatorAddr) if rest.CheckInternalServerError(w, errQuery) { return } @@ -179,26 +179,26 @@ func delegatorTxsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { txs = append(txs, foundTxs) } - res, err := cliCtx.Codec.MarshalJSON(txs) + res, err := clientCtx.Codec.MarshalJSON(txs) if rest.CheckInternalServerError(w, err) { return } - rest.PostProcessResponseBare(w, cliCtx, res) + rest.PostProcessResponseBare(w, clientCtx, res) } } // HTTP request handler to query an unbonding-delegation -func unbondingDelegationHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return queryBonds(cliCtx, "custom/staking/unbondingDelegation") +func unbondingDelegationHandlerFn(clientCtx client.Context) http.HandlerFunc { + return queryBonds(clientCtx, "custom/staking/unbondingDelegation") } // HTTP request handler to query redelegations -func redelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func redelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var params types.QueryRedelegationParams - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } @@ -234,45 +234,45 @@ func redelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { params.DstValidatorAddr = dstValidatorAddr } - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } - res, height, err := cliCtx.QueryWithData("custom/staking/redelegations", bz) + res, height, err := clientCtx.QueryWithData("custom/staking/redelegations", bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } // HTTP request handler to query a delegation -func delegationHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return queryBonds(cliCtx, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegation)) +func delegationHandlerFn(clientCtx client.Context) http.HandlerFunc { + return queryBonds(clientCtx, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegation)) } // HTTP request handler to query all delegator bonded validators -func delegatorValidatorsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return queryDelegator(cliCtx, "custom/staking/delegatorValidators") +func delegatorValidatorsHandlerFn(clientCtx client.Context) http.HandlerFunc { + return queryDelegator(clientCtx, "custom/staking/delegatorValidators") } // HTTP request handler to get information from a currently bonded validator -func delegatorValidatorHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return queryBonds(cliCtx, "custom/staking/delegatorValidator") +func delegatorValidatorHandlerFn(clientCtx client.Context) http.HandlerFunc { + return queryBonds(clientCtx, "custom/staking/delegatorValidator") } // HTTP request handler to query list of validators -func validatorsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func validatorsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { _, page, limit, err := rest.ParseHTTPArgsWithLimit(r, 0) if rest.CheckBadRequestError(w, err) { return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } @@ -284,40 +284,40 @@ func validatorsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { params := types.NewQueryValidatorsParams(page, limit, status) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryValidators) - res, height, err := cliCtx.QueryWithData(route, bz) + res, height, err := clientCtx.QueryWithData(route, bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } // HTTP request handler to query the validator information from a given validator address -func validatorHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return queryValidator(cliCtx, "custom/staking/validator") +func validatorHandlerFn(clientCtx client.Context) http.HandlerFunc { + return queryValidator(clientCtx, "custom/staking/validator") } // HTTP request handler to query all unbonding delegations from a validator -func validatorDelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return queryValidator(cliCtx, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryValidatorDelegations)) +func validatorDelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { + return queryValidator(clientCtx, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryValidatorDelegations)) } // HTTP request handler to query all unbonding delegations from a validator -func validatorUnbondingDelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return queryValidator(cliCtx, "custom/staking/validatorUnbondingDelegations") +func validatorUnbondingDelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { + return queryValidator(clientCtx, "custom/staking/validatorUnbondingDelegations") } // HTTP request handler to query historical info at a given height -func historicalInfoHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func historicalInfoHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) heightStr := vars["height"] @@ -330,53 +330,53 @@ func historicalInfoHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { params := types.NewQueryHistoricalInfoParams(height) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckInternalServerError(w, err) { return } - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryHistoricalInfo), bz) + res, height, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryHistoricalInfo), bz) if rest.CheckBadRequestError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } // HTTP request handler to query the pool information -func poolHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func poolHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - res, height, err := cliCtx.QueryWithData("custom/staking/pool", nil) + res, height, err := clientCtx.QueryWithData("custom/staking/pool", nil) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } // HTTP request handler to query the staking params values -func paramsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func paramsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } - res, height, err := cliCtx.QueryWithData("custom/staking/parameters", nil) + res, height, err := clientCtx.QueryWithData("custom/staking/parameters", nil) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } diff --git a/x/staking/client/rest/rest.go b/x/staking/client/rest/rest.go index e112341e9f84..cd3c5793b7d8 100644 --- a/x/staking/client/rest/rest.go +++ b/x/staking/client/rest/rest.go @@ -3,16 +3,16 @@ package rest import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" ) -func RegisterHandlers(cliCtx context.CLIContext, r *mux.Router) { - registerQueryRoutes(cliCtx, r) - registerTxHandlers(cliCtx, r) +func RegisterHandlers(clientCtx client.Context, r *mux.Router) { + registerQueryRoutes(clientCtx, r) + registerTxHandlers(clientCtx, r) } // RegisterRoutes registers staking-related REST handlers to a router -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { - registerQueryRoutes(cliCtx, r) - registerTxRoutes(cliCtx, r) +func RegisterRoutes(clientCtx client.Context, r *mux.Router) { + registerQueryRoutes(clientCtx, r) + registerTxRoutes(clientCtx, r) } diff --git a/x/staking/client/rest/tx.go b/x/staking/client/rest/tx.go index 965cf3da470b..7a4c9763fdd5 100644 --- a/x/staking/client/rest/tx.go +++ b/x/staking/client/rest/tx.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" @@ -14,18 +14,18 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/types" ) -func registerTxHandlers(cliCtx context.CLIContext, r *mux.Router) { +func registerTxHandlers(clientCtx client.Context, r *mux.Router) { r.HandleFunc( "/staking/delegators/{delegatorAddr}/delegations", - newPostDelegationsHandlerFn(cliCtx), + newPostDelegationsHandlerFn(clientCtx), ).Methods("POST") r.HandleFunc( "/staking/delegators/{delegatorAddr}/unbonding_delegations", - newPostUnbondingDelegationsHandlerFn(cliCtx), + newPostUnbondingDelegationsHandlerFn(clientCtx), ).Methods("POST") r.HandleFunc( "/staking/delegators/{delegatorAddr}/redelegations", - newPostRedelegationsHandlerFn(cliCtx), + newPostRedelegationsHandlerFn(clientCtx), ).Methods("POST") } @@ -56,10 +56,10 @@ type ( } ) -func newPostDelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func newPostDelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req DelegateRequest - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -83,14 +83,14 @@ func newPostDelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) } } -func newPostRedelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func newPostRedelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req RedelegateRequest - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -114,14 +114,14 @@ func newPostRedelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) } } -func newPostUnbondingDelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func newPostUnbondingDelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req UndelegateRequest - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -145,7 +145,7 @@ func newPostUnbondingDelegationsHandlerFn(cliCtx context.CLIContext) http.Handle return } - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) } } @@ -154,26 +154,26 @@ func newPostUnbondingDelegationsHandlerFn(cliCtx context.CLIContext) http.Handle // // TODO: Remove once client-side Protobuf migration has been completed. // --------------------------------------------------------------------------- -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { +func registerTxRoutes(clientCtx client.Context, r *mux.Router) { r.HandleFunc( "/staking/delegators/{delegatorAddr}/delegations", - postDelegationsHandlerFn(cliCtx), + postDelegationsHandlerFn(clientCtx), ).Methods("POST") r.HandleFunc( "/staking/delegators/{delegatorAddr}/unbonding_delegations", - postUnbondingDelegationsHandlerFn(cliCtx), + postUnbondingDelegationsHandlerFn(clientCtx), ).Methods("POST") r.HandleFunc( "/staking/delegators/{delegatorAddr}/redelegations", - postRedelegationsHandlerFn(cliCtx), + postRedelegationsHandlerFn(clientCtx), ).Methods("POST") } -func postDelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func postDelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req DelegateRequest - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -197,15 +197,15 @@ func postDelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } -func postRedelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func postRedelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req RedelegateRequest - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -229,15 +229,15 @@ func postRedelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } -func postUnbondingDelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func postUnbondingDelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req UndelegateRequest - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -261,6 +261,6 @@ func postUnbondingDelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFu return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/staking/client/rest/utils.go b/x/staking/client/rest/utils.go index 04ec27809da6..e4e3328abebe 100644 --- a/x/staking/client/rest/utils.go +++ b/x/staking/client/rest/utils.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" @@ -25,7 +25,7 @@ func contains(stringSlice []string, txType string) bool { } // queries staking txs -func queryTxs(cliCtx context.CLIContext, action string, delegatorAddr string) (*sdk.SearchTxsResult, error) { +func queryTxs(clientCtx client.Context, action string, delegatorAddr string) (*sdk.SearchTxsResult, error) { page := 1 limit := 100 events := []string{ @@ -33,10 +33,10 @@ func queryTxs(cliCtx context.CLIContext, action string, delegatorAddr string) (* fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeySender, delegatorAddr), } - return authclient.QueryTxsByEvents(cliCtx, events, page, limit, "") + return authclient.QueryTxsByEvents(clientCtx, events, page, limit, "") } -func queryBonds(cliCtx context.CLIContext, endpoint string) http.HandlerFunc { +func queryBonds(clientCtx client.Context, endpoint string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) bech32delegator := vars["delegatorAddr"] @@ -52,29 +52,29 @@ func queryBonds(cliCtx context.CLIContext, endpoint string) http.HandlerFunc { return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQueryBondsParams(delegatorAddr, validatorAddr) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } - res, height, err := cliCtx.QueryWithData(endpoint, bz) + res, height, err := clientCtx.QueryWithData(endpoint, bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } -func queryDelegator(cliCtx context.CLIContext, endpoint string) http.HandlerFunc { +func queryDelegator(clientCtx client.Context, endpoint string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) bech32delegator := vars["delegatorAddr"] @@ -84,29 +84,29 @@ func queryDelegator(cliCtx context.CLIContext, endpoint string) http.HandlerFunc return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQueryDelegatorParams(delegatorAddr) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } - res, height, err := cliCtx.QueryWithData(endpoint, bz) + res, height, err := clientCtx.QueryWithData(endpoint, bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } -func queryValidator(cliCtx context.CLIContext, endpoint string) http.HandlerFunc { +func queryValidator(clientCtx client.Context, endpoint string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) bech32validatorAddr := vars["validatorAddr"] @@ -116,24 +116,24 @@ func queryValidator(cliCtx context.CLIContext, endpoint string) http.HandlerFunc return } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return } params := types.NewQueryValidatorParams(validatorAddr) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } - res, height, err := cliCtx.QueryWithData(endpoint, bz) + res, height, err := clientCtx.QueryWithData(endpoint, bz) if rest.CheckInternalServerError(w, err) { return } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) + clientCtx = clientCtx.WithHeight(height) + rest.PostProcessResponse(w, clientCtx, res) } } diff --git a/x/staking/module.go b/x/staking/module.go index 4d6c9fc6f81f..432096f59107 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -13,7 +13,7 @@ import ( cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -65,13 +65,13 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessag } // RegisterRESTRoutes registers the REST routes for the staking module. -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { - rest.RegisterHandlers(ctx, rtr) +func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { + rest.RegisterHandlers(clientCtx, rtr) } // GetTxCmd returns the root tx command for the staking module. -func (AppModuleBasic) GetTxCmd(ctx context.CLIContext) *cobra.Command { - return cli.NewTxCmd(ctx) +func (AppModuleBasic) GetTxCmd(clientCtx client.Context) *cobra.Command { + return cli.NewTxCmd(clientCtx) } // GetQueryCmd returns no root query command for the staking module. @@ -95,9 +95,9 @@ func (AppModuleBasic) PrepareFlagsForTxCreateValidator(config *cfg.Config, nodeI } // BuildCreateValidatorMsg - used for gen-tx -func (AppModuleBasic) BuildCreateValidatorMsg(cliCtx context.CLIContext, +func (AppModuleBasic) BuildCreateValidatorMsg(clientCtx client.Context, txBldr authtypes.TxBuilder) (authtypes.TxBuilder, sdk.Msg, error) { - return cli.BuildCreateValidatorMsg(cliCtx, txBldr) + return cli.BuildCreateValidatorMsg(clientCtx, txBldr) } //____________________________________________________________________________ diff --git a/x/upgrade/client/cli/query.go b/x/upgrade/client/cli/query.go index 390ed9e5de68..7392e4e1ce03 100644 --- a/x/upgrade/client/cli/query.go +++ b/x/upgrade/client/cli/query.go @@ -8,7 +8,7 @@ import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" ) @@ -20,10 +20,10 @@ func GetPlanCmd(storeName string, cdc *codec.Codec) *cobra.Command { Long: "Gets the currently scheduled upgrade plan, if one exists", Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) // ignore height for now - res, _, err := cliCtx.Query(fmt.Sprintf("custom/%s/%s", types.QuerierKey, types.QueryCurrent)) + res, _, err := clientCtx.Query(fmt.Sprintf("custom/%s/%s", types.QuerierKey, types.QueryCurrent)) if err != nil { return err } @@ -37,7 +37,7 @@ func GetPlanCmd(storeName string, cdc *codec.Codec) *cobra.Command { if err != nil { return err } - return cliCtx.PrintOutput(plan) + return clientCtx.PrintOutput(plan) }, } } @@ -51,16 +51,16 @@ func GetAppliedHeightCmd(storeName string, cdc *codec.Codec) *cobra.Command { "This helps a client determine which binary was valid over a given range of blocks, as well as more context to understand past migrations.", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.NewContext().WithCodec(cdc) name := args[0] params := types.NewQueryAppliedParams(name) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if err != nil { return err } - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierKey, types.QueryApplied), bz) + res, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierKey, types.QueryApplied), bz) if err != nil { return err } @@ -74,7 +74,7 @@ func GetAppliedHeightCmd(storeName string, cdc *codec.Codec) *cobra.Command { applied := int64(binary.BigEndian.Uint64(res)) // we got the height, now let's return the headers - node, err := cliCtx.GetNode() + node, err := clientCtx.GetNode() if err != nil { return err } diff --git a/x/upgrade/client/cli/tx.go b/x/upgrade/client/cli/tx.go index 218399ce8bdc..cc77d5e5e44c 100644 --- a/x/upgrade/client/cli/tx.go +++ b/x/upgrade/client/cli/tx.go @@ -11,7 +11,7 @@ import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/upgrade/types" ) @@ -26,7 +26,7 @@ const ( ) // NewCmdSubmitUpgradeProposal implements a command handler for submitting a software upgrade proposal transaction. -func NewCmdSubmitUpgradeProposal(ctx context.CLIContext) *cobra.Command { +func NewCmdSubmitUpgradeProposal(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "software-upgrade [name] (--upgrade-height [height] | --upgrade-time [time]) (--upgrade-info [info]) [flags]", @@ -42,8 +42,8 @@ func NewCmdSubmitUpgradeProposal(ctx context.CLIContext) *cobra.Command { return err } - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) - from := cliCtx.GetFromAddress() + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) + from := clientCtx.GetFromAddress() depositStr, err := cmd.Flags().GetString(cli.FlagDeposit) if err != nil { @@ -63,7 +63,7 @@ func NewCmdSubmitUpgradeProposal(ctx context.CLIContext) *cobra.Command { return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } @@ -78,15 +78,15 @@ func NewCmdSubmitUpgradeProposal(ctx context.CLIContext) *cobra.Command { } // NewCmdSubmitCancelUpgradeProposal implements a command handler for submitting a software upgrade cancel proposal transaction. -func NewCmdSubmitCancelUpgradeProposal(ctx context.CLIContext) *cobra.Command { +func NewCmdSubmitCancelUpgradeProposal(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "cancel-software-upgrade [flags]", Args: cobra.ExactArgs(0), Short: "Submit a software upgrade proposal", Long: "Cancel a software upgrade along with an initial deposit.", RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := ctx.InitWithInput(cmd.InOrStdin()) - from := cliCtx.GetFromAddress() + clientCtx := clientCtx.InitWithInput(cmd.InOrStdin()) + from := clientCtx.GetFromAddress() depositStr, err := cmd.Flags().GetString(cli.FlagDeposit) if err != nil { @@ -119,7 +119,7 @@ func NewCmdSubmitCancelUpgradeProposal(ctx context.CLIContext) *cobra.Command { return err } - return tx.GenerateOrBroadcastTx(cliCtx, msg) + return tx.GenerateOrBroadcastTx(clientCtx, msg) }, } diff --git a/x/upgrade/client/rest/query.go b/x/upgrade/client/rest/query.go index 101235419b2c..a3d597d377a0 100644 --- a/x/upgrade/client/rest/query.go +++ b/x/upgrade/client/rest/query.go @@ -7,22 +7,22 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/upgrade/types" ) // RegisterRoutes registers REST routes for the upgrade module under the path specified by routeName. -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/upgrade/current", getCurrentPlanHandler(cliCtx)).Methods("GET") - r.HandleFunc("/upgrade/applied/{name}", getDonePlanHandler(cliCtx)).Methods("GET") - registerTxRoutes(cliCtx, r) +func RegisterRoutes(clientCtx client.Context, r *mux.Router) { + r.HandleFunc("/upgrade/current", getCurrentPlanHandler(clientCtx)).Methods("GET") + r.HandleFunc("/upgrade/applied/{name}", getDonePlanHandler(clientCtx)).Methods("GET") + registerTxRoutes(clientCtx, r) } -func getCurrentPlanHandler(cliCtx context.CLIContext) func(http.ResponseWriter, *http.Request) { +func getCurrentPlanHandler(clientCtx client.Context) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, request *http.Request) { // ignore height for now - res, _, err := cliCtx.Query(fmt.Sprintf("custom/%s/%s", types.QuerierKey, types.QueryCurrent)) + res, _, err := clientCtx.Query(fmt.Sprintf("custom/%s/%s", types.QuerierKey, types.QueryCurrent)) if rest.CheckInternalServerError(w, err) { return } @@ -32,26 +32,26 @@ func getCurrentPlanHandler(cliCtx context.CLIContext) func(http.ResponseWriter, } var plan types.Plan - err = cliCtx.Codec.UnmarshalBinaryBare(res, &plan) + err = clientCtx.Codec.UnmarshalBinaryBare(res, &plan) if rest.CheckInternalServerError(w, err) { return } - rest.PostProcessResponse(w, cliCtx, plan) + rest.PostProcessResponse(w, clientCtx, plan) } } -func getDonePlanHandler(cliCtx context.CLIContext) func(http.ResponseWriter, *http.Request) { +func getDonePlanHandler(clientCtx client.Context) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { name := mux.Vars(r)["name"] params := types.NewQueryAppliedParams(name) - bz, err := cliCtx.Codec.MarshalJSON(params) + bz, err := clientCtx.Codec.MarshalJSON(params) if rest.CheckBadRequestError(w, err) { return } - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierKey, types.QueryApplied), bz) + res, _, err := clientCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierKey, types.QueryApplied), bz) if rest.CheckBadRequestError(w, err) { return } @@ -66,6 +66,6 @@ func getDonePlanHandler(cliCtx context.CLIContext) func(http.ResponseWriter, *ht applied := int64(binary.BigEndian.Uint64(res)) fmt.Println(applied) - rest.PostProcessResponse(w, cliCtx, applied) + rest.PostProcessResponse(w, clientCtx, applied) } } diff --git a/x/upgrade/client/rest/tx.go b/x/upgrade/client/rest/tx.go index 656f492d86fe..bc4b0795fe4f 100644 --- a/x/upgrade/client/rest/tx.go +++ b/x/upgrade/client/rest/tx.go @@ -11,7 +11,7 @@ import ( authclient "github.com/cosmos/cosmos-sdk/x/auth/client" govrest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" gov "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -20,17 +20,17 @@ import ( // nolint func newRegisterTxRoutes( - cliCtx context.CLIContext, - txg context.TxGenerator, + clientCtx client.Context, + txg client.TxGenerator, newMsgFn func() gov.MsgSubmitProposalI, r *mux.Router) { - r.HandleFunc("/upgrade/plan", newPostPlanHandler(cliCtx, txg, newMsgFn)).Methods("POST") - r.HandleFunc("/upgrade/cancel", newCancelPlanHandler(cliCtx, txg, newMsgFn)).Methods("POST") + r.HandleFunc("/upgrade/plan", newPostPlanHandler(clientCtx, txg, newMsgFn)).Methods("POST") + r.HandleFunc("/upgrade/cancel", newCancelPlanHandler(clientCtx, txg, newMsgFn)).Methods("POST") } -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/upgrade/plan", postPlanHandler(cliCtx)).Methods("POST") - r.HandleFunc("/upgrade/cancel", cancelPlanHandler(cliCtx)).Methods("POST") +func registerTxRoutes(clientCtx client.Context, r *mux.Router) { + r.HandleFunc("/upgrade/plan", postPlanHandler(clientCtx)).Methods("POST") + r.HandleFunc("/upgrade/cancel", cancelPlanHandler(clientCtx)).Methods("POST") } // PlanRequest defines a proposal for a new upgrade plan. @@ -53,19 +53,19 @@ type CancelRequest struct { Deposit sdk.Coins `json:"deposit" yaml:"deposit"` } -func ProposalRESTHandler(cliCtx context.CLIContext) govrest.ProposalRESTHandler { +func ProposalRESTHandler(clientCtx client.Context) govrest.ProposalRESTHandler { return govrest.ProposalRESTHandler{ SubRoute: "upgrade", - Handler: postPlanHandler(cliCtx), + Handler: postPlanHandler(clientCtx), } } // nolint -func newPostPlanHandler(cliCtx context.CLIContext, txg context.TxGenerator, newMsgFn func() gov.MsgSubmitProposalI) http.HandlerFunc { +func newPostPlanHandler(clientCtx client.Context, txg client.TxGenerator, newMsgFn func() gov.MsgSubmitProposalI) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req PlanRequest - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -101,16 +101,16 @@ func newPostPlanHandler(cliCtx context.CLIContext, txg context.TxGenerator, newM return } - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) } } // nolint -func newCancelPlanHandler(cliCtx context.CLIContext, txg context.TxGenerator, newMsgFn func() gov.MsgSubmitProposalI) http.HandlerFunc { +func newCancelPlanHandler(clientCtx client.Context, txg client.TxGenerator, newMsgFn func() gov.MsgSubmitProposalI) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req CancelRequest - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -137,15 +137,15 @@ func newCancelPlanHandler(cliCtx context.CLIContext, txg context.TxGenerator, ne return } - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) + tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) } } -func postPlanHandler(cliCtx context.CLIContext) http.HandlerFunc { +func postPlanHandler(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req PlanRequest - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -177,15 +177,15 @@ func postPlanHandler(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } -func cancelPlanHandler(cliCtx context.CLIContext) http.HandlerFunc { +func cancelPlanHandler(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req CancelRequest - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) { return } @@ -208,6 +208,6 @@ func cancelPlanHandler(cliCtx context.CLIContext) http.HandlerFunc { return } - authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + authclient.WriteGenerateStdTxResponse(w, clientCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/upgrade/module.go b/x/upgrade/module.go index d0a8ee51975c..f87025c2ece7 100644 --- a/x/upgrade/module.go +++ b/x/upgrade/module.go @@ -8,7 +8,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -46,8 +46,8 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { } // RegisterRESTRoutes registers all REST query handlers -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, r *mux.Router) { - rest.RegisterRoutes(ctx, r) +func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, r *mux.Router) { + rest.RegisterRoutes(clientCtx, r) } // GetQueryCmd returns the cli query commands for this module @@ -65,7 +65,7 @@ func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { } // GetTxCmd returns the transaction commands for this module -func (AppModuleBasic) GetTxCmd(_ context.CLIContext) *cobra.Command { +func (AppModuleBasic) GetTxCmd(_ client.Context) *cobra.Command { txCmd := &cobra.Command{ Use: "upgrade", Short: "Upgrade transaction subcommands",