# Module Interfaces

This document details how to build CLI and REST interfaces for a module. Examples from various SDK modules are included.

# Prerequisite Readings

# CLI

One of the main interfaces for an application is the command-line interface. This entrypoint adds commands from the application's modules enabling end-users to create messages wrapped in transactions and queries. The CLI files are typically found in the module's ./client/cli folder.

# Transaction Commands

In order to create messages that trigger state changes, end-users must create transactions that wrap and deliver the messages. A transaction command creates a transaction that includes one or more messages.

Transaction commands typically have their own tx.go file that lives within the module's ./client/cli folder. The commands are specified in getter functions and the name of the function should include the name of the command.

Here is an example from the x/bank module:

Copy // NewSendTxCmd returns a CLI command handler for creating a MsgSend transaction. func NewSendTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "send [from_key_or_address] [to_address] [amount]", Short: `Send funds from one account to another. Note, the'--from' flag is ignored as it is implied from [from_key_or_address].`, Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { cmd.Flags().Set(flags.FlagFrom, args[0]) clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err } toAddr, err := sdk.AccAddressFromBech32(args[1]) if err != nil { return err } coins, err := sdk.ParseCoinsNormalized(args[2]) if err != nil { return err } msg := types.NewMsgSend(clientCtx.GetFromAddress(), toAddr, coins) return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } flags.AddTxFlagsToCmd(cmd) return cmd }

In the example, NewSendTxCmd() creates and returns the transaction command for a transaction that wraps and delivers MsgSend. MsgSend is the message used to send tokens from one account to another.

In general, the getter function does the following:

  • Constructs the command: Read the Cobra Documentation (opens new window) for more detailed information on how to create commands.
    • Use: Specifies the format of the user input required to invoke the command. In the example above, send is the name of the transaction command and [from_key_or_address], [to_address], and [amount] are the arguments.
    • Args: The number of arguments the user provides. In this case, there are exactly three: [from_key_or_address], [to_address], and [amount].
    • Short and Long: Descriptions for the command. A Short description is expected. A Long description can be used to provide additional information that is displayed when a user adds the --help flag.
    • RunE: Defines a function that can return an error. This is the function that is called when the command is executed. This function encapsulates all of the logic to create a new transaction.
      • The function typically starts by getting the clientCtx, which can be done with client.GetClientTxContext(cmd). The clientCtx contains information relevant to transaction handling, including information about the user. In this example, the clientCtx is used to retrieve the address of the sender by calling clientCtx.GetFromAddress().
      • If applicable, the command's arguments are parsed. In this example, the arguments [to_address] and [amount] are both parsed.
      • A message is created using the parsed arguments and information from the clientCtx. The constructor function of the message type is called directly. In this case, types.NewMsgSend(fromAddr, toAddr, amount). Its good practice to call msg.ValidateBasic() after creating the message, which runs a sanity check on the provided arguments.
      • Depending on what the user wants, the transaction is either generated offline or signed and broadcasted to the preconfigured node using tx.GenerateOrBroadcastTxCLI(clientCtx, flags, msg).
  • Adds transaction flags: All transaction commands must add a set of transaction flags. The transaction flags are used to collect additional information from the user (e.g. the amount of fees the user is willing to pay). The transaction flags are added to the constructed command using AddTxFlagsToCmd(cmd).
  • Returns the command: Finally, the transaction command is returned.

Each module must implement NewTxCmd(), which aggregates all of the transaction commands of the module. Here is an example from the x/bank module:

Copy // NewTxCmd returns a root CLI command handler for all x/bank transaction commands. func NewTxCmd() *cobra.Command { txCmd := &cobra.Command{ Use: types.ModuleName, Short: "Bank transaction subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } txCmd.AddCommand(NewSendTxCmd()) return txCmd }

Each module must also implement the GetTxCmd() method for AppModuleBasic that simply returns NewTxCmd(). This allows the root command to easily aggregate all of the transaction commands for each module. Here is an example:

Copy // GetTxCmd returns the root tx command for the bank module. func (AppModuleBasic) GetTxCmd() *cobra.Command { return cli.NewTxCmd() }

# Query Commands

Queries allow users to gather information about the application or network state; they are routed by the application and processed by the module in which they are defined. Query commands typically have their own query.go file in the module's ./client/cli folder. Like transaction commands, they are specified in getter functions. Here is an example of a query command from the x/auth module:

Copy // GetAccountCmd returns a query account that will display the state of the // account at a given address. func GetAccountCmd() *cobra.Command { cmd := &cobra.Command{ Use: "account [address]", Short: "Query for account by address", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientQueryContext(cmd) if err != nil { return err } key, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return err } queryClient := types.NewQueryClient(clientCtx) res, err := queryClient.Account(cmd.Context(), &types.QueryAccountRequest{Address: key.String()}) if err != nil { return err } return clientCtx.PrintProto(res.Account) }, } flags.AddQueryFlagsToCmd(cmd) return cmd }

In the example, GetAccountCmd() creates and returns a query command that returns the state of an account based on the provided account address.

In general, the getter function does the following:

  • Constructs the command: Read the Cobra Documentation (opens new window) for more detailed information on how to create commands.
    • Use: Specifies the format of the user input required to invoke the command. In the example above, account is the name of the query command and [address] is the argument.
    • Args: The number of arguments the user provides. In this case, there is exactly one: [address].
    • Short and Long: Descriptions for the command. A Short description is expected. A Long description can be used to provide additional information that is displayed when a user adds the --help flag.
    • RunE: Defines a function that can return an error. This is the function that is called when the command is executed. This function encapsulates all of the logic to create a new query.
      • The function typically starts by getting the clientCtx, which can be done with client.GetClientQueryContext(cmd). The clientCtx contains information relevant to query handling.
      • If applicable, the command's arguments are parsed. In this example, the argument [address] is parsed.
      • A new queryClient is initialized using NewQueryClient(clientCtx). The queryClient is then used to call the appropriate query.
      • The clientCtx.PrintProto method is used to format the proto.Message object so that the results can be printed back to the user.
  • Adds query flags: All query commands must add a set of query flags. The query flags are added to the constructed command using AddQueryFlagsToCmd(cmd).
  • Returns the command: Finally, the query command is returned.

Each module must implement GetQueryCmd(), which aggregates all of the query commands of the module. Here is an example from the x/auth module:

Copy // GetQueryCmd returns the transaction commands for this module func GetQueryCmd() *cobra.Command { cmd := &cobra.Command{ Use: types.ModuleName, Short: "Querying commands for the auth module", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } cmd.AddCommand( GetAccountCmd(), GetAccountsCmd(), QueryParamsCmd(), ) return cmd }

Each module must also implement the GetQueryCmd() method for AppModuleBasic that returns the GetQueryCmd() function. This allows for the root command to easily aggregate all of the query commands for each module. Here is an example:

Copy // GetQueryCmd returns the root query command for the auth module. func (AppModuleBasic) GetQueryCmd() *cobra.Command { return cli.GetQueryCmd() }

# Flags

Flags allow users to customize commands. --fees and --gas-prices are examples of flags that allow users to set the fees and gas prices for their transactions.

Flags that are specific to a module are typically created in a flags.go file in the module's ./client/cli folder. When creating a flag, developers set the value type, the name of the flag, the default value, and a description about the flag. Developers also have the option to mark flags as required so that an error is thrown if the user does not include a value for the flag.

Here is an example that adds the --from flag to a command:

Copy cmd.Flags().String(FlagFrom, "", "Name or address of private key with which to sign")

In this example, the value of the flag is a String, the name of the flag is from (the value of the FlagFrom constant), the default value of the flag is "", and there is a description that will be displayed when a user adds --help to the command.

Here is an example that marks the --from flag as required:

Copy cmd.MarkFlagRequired(FlagFrom)

For more detailed information on creating flags, visit the Cobra Documentation (opens new window).

As mentioned in transaction commands, there is a set of flags that all transaction commands must add. This is done with the AddTxFlagsToCmd method defined in the SDK's ./client/flags package.

Copy // AddTxFlagsToCmd adds common flags to a module tx command. func AddTxFlagsToCmd(cmd *cobra.Command) { cmd.Flags().String(FlagKeyringDir, "", "The client Keyring directory; if omitted, the default 'home' directory will be used") cmd.Flags().String(FlagFrom, "", "Name or address of private key with which to sign") cmd.Flags().Uint64P(FlagAccountNumber, "a", 0, "The account number of the signing account (offline mode only)") cmd.Flags().Uint64P(FlagSequence, "s", 0, "The sequence number of the signing account (offline mode only)") cmd.Flags().String(FlagNote, "", "Note to add a description to the transaction (previously `--memo`)") cmd.Flags().String(FlagFees, "", "Fees to pay along with transaction; eg: 10uatom") cmd.Flags().String(FlagGasPrices, "", "Gas prices in decimal format to determine the transaction fee (e.g. 0.1uatom)") cmd.Flags().String(FlagNode, "tcp://localhost:26657", "<host>:<port> to tendermint rpc interface for this chain") cmd.Flags().Bool(FlagUseLedger, false, "Use a connected Ledger device") cmd.Flags().Float64(FlagGasAdjustment, DefaultGasAdjustment, "adjustment factor to be multiplied against the estimate returned by the tx simulation; if the gas limit is set manually this flag is ignored ") cmd.Flags().StringP(FlagBroadcastMode, "b", BroadcastSync, "Transaction broadcasting mode (sync|async|block)") cmd.Flags().Bool(FlagDryRun, false, "ignore the --gas flag and perform a simulation of a transaction, but don't broadcast it") cmd.Flags().Bool(FlagGenerateOnly, false, "Build an unsigned transaction and write it to STDOUT (when enabled, the local Keybase is not accessible)") cmd.Flags().Bool(FlagOffline, false, "Offline mode (does not allow any online functionality") cmd.Flags().BoolP(FlagSkipConfirmation, "y", false, "Skip tx broadcasting prompt confirmation") cmd.Flags().String(FlagKeyringBackend, DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test|memory)") cmd.Flags().String(FlagSignMode, "", "Choose sign mode (direct|amino-json), this is an advanced feature") cmd.Flags().Uint64(FlagTimeoutHeight, 0, "Set a block timeout height to prevent the tx from being committed past a certain height") cmd.Flags().String(FlagFeeAccount, "", "Fee account pays fees for the transaction instead of deducting from the signer") // --gas can accept integers and "auto" cmd.Flags().String(FlagGas, "", fmt.Sprintf("gas limit to set per-transaction; set to %q to calculate sufficient gas automatically (default %d)", GasFlagAuto, DefaultGasLimit)) cmd.MarkFlagRequired(FlagChainID) }

Since AddTxFlagsToCmd(cmd *cobra.Command) includes all of the basic flags required for a transaction command, module developers may choose not to add any of their own (specifying arguments instead may often be more appropriate).

Similarly, there is a AddQueryFlagsToCmd(cmd *cobra.Command) to add common flags to a module query command.

Copy // AddQueryFlagsToCmd adds common flags to a module query command. func AddQueryFlagsToCmd(cmd *cobra.Command) { cmd.Flags().String(FlagNode, "tcp://localhost:26657", "<host>:<port> to Tendermint RPC interface for this chain") cmd.Flags().Int64(FlagHeight, 0, "Use a specific height to query state at (this can error if the node is pruning state)") cmd.Flags().StringP(tmcli.OutputFlag, "o", "text", "Output format (text|json)") cmd.MarkFlagRequired(FlagChainID) }

# gRPC

gRPC (opens new window) is a Remote Procedure Call (RPC) framework. RPC is the preferred way for external clients like wallets and exchanges to interact with a blockchain.

In addition to providing an ABCI query pathway, the Cosmos SDK provides a gRPC proxy server that routes gRPC query requests to ABCI query requests.

In order to do that, modules must implement RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) on AppModuleBasic to wire the client gRPC requests to the correct handler inside the module.

Here's an example from the x/auth module:

Copy // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the auth module. func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { panic(err) } }

# gRPC-gateway REST

Applications need to support web services that use HTTP requests (e.g. a web wallet like Keplr (opens new window)). grpc-gateway (opens new window) translates REST calls into gRPC calls, which might be useful for clients that do not use gRPC.

Modules that want to expose REST queries should add google.api.http annotations to their rpc methods, such as in the example below from the x/auth module:

Copy // Query defines the gRPC querier service. service Query { // Accounts returns all the existing accounts rpc Accounts(QueryAccountsRequest) returns (QueryAccountsResponse) { option (google.api.http).get = "/cosmos/auth/v1beta1/accounts"; } // Account returns account details based on address. rpc Account(QueryAccountRequest) returns (QueryAccountResponse) { option (google.api.http).get = "/cosmos/auth/v1beta1/accounts/{address}"; } // Params queries all parameters. rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { option (google.api.http).get = "/cosmos/auth/v1beta1/params"; } }

gRPC gateway is started in-process along with the application and Tendermint. It can be enabled or disabled by setting gRPC Configuration enable in app.toml.

The SDK provides a command for generating Swagger (opens new window) documentation (protoc-gen-swagger). Setting swagger in app.toml defines if swagger documentation should be automatically registered.

# Next

Read about the recommended module structure