# App and Modules Migration

The following document describes the changes to update your app and modules from Cosmos SDK v0.39 to v0.40, a.k.a. Stargate release.

# Update Tooling

Make sure to have the following dependencies before updating your app to v0.40:

  • Go 1.15+
  • Docker
  • Node.js v12.0+ (optional, for generating Swagger docs)

In Cosmos-SDK we manage the project using Makefile. Your own app can use a similar Makefile to the Cosmos SDK's one (opens new window). More specifically, below are some make commands that might be useful for your own app, related to the introduction of Protocol Buffers:

  • proto-update-deps - To download/update the required thirdparty proto definitions.
  • proto-gen - To auto generate proto code.
  • proto-check-breaking - To check proto breaking changes.
  • proto-format - To format proto files.

# Updating Modules

This section outlines how to upgrade your module to v0.40. There is also a whole section about building modules from scratch, it might serve as a useful guide.

# Protocol Buffers

As outlined in our encoding guide, one of the most significant improvements introduced in Cosmos SDK v0.40 is Protobuf.

The rule of thumb is that any object that needs to be serialized (into binary or JSON) must implement proto.Message and must be serializable into Protobuf format. The easiest way to do it is to use Protobuf type definition and protoc compiler to generate the structures and functions for you. In practice, the three following categories of types must be converted to Protobuf messages:

  • client-facing types: Msgs, query requests and responses. This is because client will send these types over the wire to your app.
  • objects that are stored in state. This is because the SDK stores the binary representation of these types in state.
  • genesis types. These are used when importing and exporting state snapshots during chain upgrades.

Let's have a look at x/auth's BaseAccount objects, which are stored in a state. The migration looks like:

Copy // We were definining `MsgSend` as a Go struct in v0.39. - // https://github.com/cosmos/cosmos-sdk/blob/v0.39.2/x/bank/internal/types/msgs.go#L12-L16 - type BaseAccount struct { - Address sdk.AccAddress `json:"address" yaml:"address"` - Coins sdk.Coins `json:"coins" yaml:"coins"` - PubKey crypto.PubKey `json:"public_key" yaml:"public_key"` - AccountNumber uint64 `json:"account_number" yaml:"account_number"` - Sequence uint64 `json:"sequence" yaml:"sequence"` - } // And it should be converted to a Protobuf message in v0.40. + // https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/proto/cosmos/auth/v1beta1/auth.proto#L13-L25 + message BaseAccount { + string address = 1; + google.protobuf.Any pub_key = 2 + [(gogoproto.jsontag) = "public_key,omitempty", (gogoproto.moretags) = "yaml:\"public_key\""]; + uint64 account_number = 3 [(gogoproto.moretags) = "yaml:\"account_number\""]; + uint64 sequence = 4; + } }

In general, we recommend to put all the Protobuf definitions in your module's subdirectory under a root proto/ folder, as described in ADR-023. This ADR also contains other useful information on naming conventions.

You might have noticed that the PubKey interface in v0.39's BaseAccount has been transformed into an Any. For storing interfaces, we use Protobuf's Any message, which is a struct that can hold arbitrary content. Please refer to the encoding FAQ to learn how to handle interfaces and Anys.

Once all your Protobuf messages are defined, use the make proto-gen command defined in the tooling section to generate Go structs. These structs will be generated into *.pb.go files. As a quick example, here is the generated Go struct for the Protobuf BaseAccount we defined above:

Copy // BaseAccount defines a base account type. It contains all the necessary fields // for basic account functionality. Any custom account type should extend this // type for additional functionality (e.g. vesting). type BaseAccount struct { Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` PubKey *types.Any `protobuf:"bytes,2,opt,name=pub_key,json=pubKey,proto3" json:"public_key,omitempty" yaml:"public_key"` AccountNumber uint64 `protobuf:"varint,3,opt,name=account_number,json=accountNumber,proto3" json:"account_number,omitempty" yaml:"account_number"` Sequence uint64 `protobuf:"varint,4,opt,name=sequence,proto3" json:"sequence,omitempty"` }

There might be some back and forth removing old Go structs/interfaces and defining new Protobuf messages before your Go app compiles and your tests pass.

# Create Msg and Query Services

Cosmos SDK v0.40 uses Protobuf services to define state transitions (Msgs) and state queries, please read the building modules guide on those services for an overview.

# Msg Service

For migrating Msgs, the handler pattern (inside the handler.go file) is deprecated. You may still keep it if you wish to support Msgs defined in older versions of the SDK. However, it is strongly recommended to add a Msg service to your Protobuf files, and each old Msg should be converted into a service method. Taking x/bank's MsgSend as an example, we have a corresponding cosmos.bank.v1beta1.Msg/Send service method:

Copy // Msg defines the bank Msg service. service Msg { // Send defines a method for sending coins from one account to another account. rpc Send(MsgSend) returns (MsgSendResponse); // MultiSend defines a method for sending coins from some accounts to other accounts. rpc MultiSend(MsgMultiSend) returns (MsgMultiSendResponse); } // MsgSend represents a message to send coins from one account to another. message MsgSend { option (gogoproto.equal) = false; option (gogoproto.goproto_getters) = false; string from_address = 1 [(gogoproto.moretags) = "yaml:\"from_address\""]; string to_address = 2 [(gogoproto.moretags) = "yaml:\"to_address\""]; repeated cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; } // MsgSendResponse defines the Msg/Send response type. message MsgSendResponse {}

A state transition is therefore modelized as a Protobuf service method, with a method request, and an (optionally empty) method response.

After defining your Msg service, run the make proto-gen script again to generate Msg server interfaces. The name of this interface is simply MsgServer. The implementation of this interface should follow exactly the implementation of the old Msg handlers, which, in most cases, defers the actual state transition logic to the keeper. You may implement a MsgServer directly on the keeper, or you can do it using a new struct (e.g. called msgServer) that references the module's keeper.

For more information, please check our Msg service guide.

# Query Service

For migrating state queries, the querier pattern (inside the querier.go file) is deprecated. You may still keep this file to support legacy queries, but it is strongly recommended to use a Protobuf Query service to handle state queries.

Each query endpoint is now defined as a separate service method in the Query service. Still taking x/bank as an example, here are the queries to fetch an account's balances:

Copy // Query defines the gRPC querier service. service Query { // Balance queries the balance of a single coin for a single account. rpc Balance(QueryBalanceRequest) returns (QueryBalanceResponse) { option (google.api.http).get = "/cosmos/bank/v1beta1/balances/{address}/{denom}"; } // AllBalances queries the balance of all coins for a single account. rpc AllBalances(QueryAllBalancesRequest) returns (QueryAllBalancesResponse) { option (google.api.http).get = "/cosmos/bank/v1beta1/balances/{address}"; }

Each query has its own Request and Response types. Please also note the google.api.http option (coming from grpc-gateway (opens new window)) on each service method. grpc-gateway is a tool that exposes Query service methods as REST endpoints. Adding this annotation will expose these endpoints not only as gRPC endpoints, but also as REST endpoints. An overview of gRPC versus REST can be found here.

After defining the Query Protobuf service, run the make proto-gen command to generate corresponding interfaces. The interface that needs to be implemented by your module is QueryServer. This interface can be implemented on the keeper directly, or on a struct (e.g. called queryServer) that references the module's keeper. The logic of the implementation, namely the logic that fetches data from the module's store and performs unmarshalling, can be deferred to the keeper.

Cosmos SDK v0.40 also comes with an efficient pagination, it now uses Prefix stores to make queries. There are 2 helpers for pagination, Paginate (opens new window), FilteredPaginate (opens new window).

For more information, please check our Query service guide.

# Wiring up Msg and Query Services

We added a new RegisterServices method that registers a module's Msg service and a Query service. It should be implemented by all modules, using a Configurator object:

Copy // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) types.RegisterQueryServer(cfg.QueryServer(), am.keeper) }

If you wish to expose your Query endpoints as REST endpoints (as proposed in the Query Services paragraph), make sure to also implement the RegisterGRPCGatewayRoutes method:

Copy // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the bank module. func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) }

# Codec

If you still use Amino (which is deprecated since Stargate), you must register related types using the RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) method (previously it was called RegisterCodec(cdc *codec.Codec)).

Moreover, a new RegisterInterfaces method has been added to the AppModule interface that all modules must implement. This method must register the interfaces that Protobuf messages implement, as well as the service Msgs used in the module. An example from x/bank is given below:

Copy func RegisterInterfaces(registry types.InterfaceRegistry) { registry.RegisterImplementations((*sdk.Msg)(nil), &MsgSend{}, &MsgMultiSend{}, ) registry.RegisterInterface( "cosmos.bank.v1beta1.SupplyI", (*exported.SupplyI)(nil), &Supply{}, ) msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) }

# Keeper

The Keeper constructor now takes a codec.Marshaler instead of a concrete Amino codec. This codec.Marshaler is used to encode types as binary and save the bytes into the state. With an interface, you can define codec.Marshaler to be Amino or Protobuf on an app level, and keepers will use that encoding library to encode state. Please note that Amino is deprecated in v0.40, and we strongly recommend to use Protobuf. Internally, the SDK still uses Amino in a couple of places (legacy REST API, x/params, keyring...), but Amino is planned to be removed in a future release.

Keeping Amino for now can be useful if you wish to update to SDK v0.40 without doing a chain upgrade with a genesis migration. This will not require updating the stores, so you can migrate to Cosmos SDK v0.40 with less effort. However, as Amino will be removed in a future release, the chain migration with genesis export/import will need to be performed then.

Related to the keepers, each module's AppModuleBasic now also includes this codec.Marshaler:

Copy // AppModuleBasic defines the basic application module used by the bank module. type AppModuleBasic struct { cdc codec.Marshaler }


Each modules may optionally expose CLI commands, and some changes are needed in these commands.

First, context.CLIContext is renamed to client.Context and moved to github.com/cosmos/cosmos-sdk/client.

Second, the global viper usage is removed from client and is replaced with Cobra' cmd.Flags(). There are two helpers to read common flags for CLI txs and queries:

Copy clientCtx, err := client.GetClientQueryContext(cmd) clientCtx, err := client.GetClientTxContext(cmd)

Some other flags helper functions are transformed: flags.PostCommands(cmds ...*cobra.Command) []*cobra.Command and flags.GetCommands(...) usage is now replaced by flags.AddTxFlagsToCmd(cmd *cobra.Command) and flags.AddQueryFlagsToCmd(cmd *cobra.Command) respectively.

Moreover, new CLI commands don't take any codec as input anymore. Instead, the clientCtx can be retrieved from the cmd itself using the GetClient{Query,Tx}Context function above, and the codec as clientCtx.JSONMarshaler.

Copy // v0.39 - func SendTxCmd(cdc *codec.Codec) *cobra.Command { - cdc.MarshalJSON(...) - } // v0.40 + func NewSendTxCmd() *cobra.Command { + clientCtx, err := client.GetClientTxContext(cmd) + clientCtx.JSONMarshaler.MarshalJSON(...) +}

Finally, once your Query services are wired up, the CLI commands should preferably use gRPC to communicate with the node. The gist is to create a Query or Msg client using the command's clientCtx, and perform the request using Protobuf's generated code. An example for querying x/bank balances is given here:

Copy queryClient := types.NewQueryClient(clientCtx) addr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return err } pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { return err } if denom == "" { params := types.NewQueryAllBalancesRequest(addr, pageReq) res, err := queryClient.AllBalances(context.Background(), params) if err != nil { return err } return clientCtx.PrintProto(res) } params := types.NewQueryBalanceRequest(addr, denom) res, err := queryClient.Balance(context.Background(), params) if err != nil { return err } return clientCtx.PrintProto(res.Balance)

# Miscelleanous

A number of other smaller breaking changes are also noteworthy.

Before After Comment
alias.go file Removed alias usage is removed, please see #6311 (opens new window) for details.
codec.New() codec.NewLegacyAmino() Simple rename.
DefaultGenesis() DefaultGenesis(cdc codec.JSONMarshaler) DefaultGenesis takes a codec argument now
ValidateGenesis() ValidateGenesis(cdc codec.JSONMarshaler, config client.TxEncodingConfig, bz json.RawMessage) ValidateGenesis now requires Marshaler, TxEncodingConfig, json.RawMessage as input.
Route() string Route() sdk.Route For legacy handlers, return type of Route() method is changed from string to "github.com/cosmos/cosmos-sdk/types".Route. It should return a NewRoute() which includes RouterKey and NewHandler as params.
QuerierHandler LegacyQuerierHandler Simple rename.
InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate InitGenesis now takes a codec input.
ExportGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate ExportGenesis now takes a codec input.

# Updating Your App

For a reference implementation used for demo purposes, you can refer to the SDK's SimApp (opens new window) for your app's migration. The most important changes are described in this section.

# Creating Codecs

With the introduction of Protobuf, each app needs to define the encoding library (Amino or Protobuf) to be used throughout the app. There is a central struct, EncodingConfig (opens new window), which defines all information necessary for codecs. In your app, an example EncodingConfig with Protobuf as default codec might look like:

Copy // MakeEncodingConfig creates an EncodingConfig func MakeEncodingConfig() params.EncodingConfig { amino := codec.NewLegacyAmino() interfaceRegistry := types.NewInterfaceRegistry() marshaler := codec.NewProtoCodec(interfaceRegistry) txCfg := tx.NewTxConfig(marshaler, tx.DefaultSignModes) encodingConfig := params.EncodingConfig{ InterfaceRegistry: interfaceRegistry, Marshaler: marshaler, TxConfig: txCfg, Amino: amino, } std.RegisterLegacyAminoCodec(encodingConfig.Amino) std.RegisterInterfaces(encodingConfig.InterfaceRegistry) ModuleBasics.RegisterLegacyAminoCodec(encodingConfig.Amino) ModuleBasics.RegisterInterfaces(encodingConfig.InterfaceRegistry) return encodingConfig }

These codecs are used to populate the following fields on your app (again, we are using SimApp for demo purposes):

Copy // SimApp extends an ABCI application, but with most of its parameters exported. // They are exported for convenience in creating helper functions, as object // capabilities aren't needed for testing. type SimApp struct { *baseapp.BaseApp legacyAmino *codec.LegacyAmino appCodec codec.Marshaler interfaceRegistry types.InterfaceRegistry

As explained in the modules migration section, some functions and structs in modules require an additional codec.Marshaler argument. You should pass app.appCodec in these cases, and this will be the default codec used throughout the app.

# Registering Non-Module Protobuf Services

We described in the modules migration section Query and Msg services defined in each module. The SDK also exposes two more module-agnostic services:

These services are optional, if you wish to use them, or if you wish to add more module-agnostic Protobuf services into your app, then you need to add them inside app.go:

Copy // RegisterTxService implements the Application.RegisterTxService method. func (app *SimApp) RegisterTxService(clientCtx client.Context) { authtx.RegisterTxService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.BaseApp.Simulate, app.interfaceRegistry) } // RegisterTendermintService implements the Application.RegisterTendermintService method. func (app *SimApp) RegisterTendermintService(clientCtx client.Context) { tmservice.RegisterTendermintService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.interfaceRegistry) }

# Registering grpc-gateway Routes

The exising RegisterAPIRoutes method on the app only registers Legacy API routes. If you are using grpc-gateway REST endpoints as described above, then these endpoints need to be wired up to a HTTP server:

Copy // RegisterAPIRoutes registers all application module routes with the provided // API server. func (app *SimApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) { clientCtx := apiSvr.ClientCtx rpc.RegisterRoutes(clientCtx, apiSvr.Router) // Register legacy tx routes. authrest.RegisterTxRoutes(clientCtx, apiSvr.Router) // Register new tx routes from grpc-gateway. authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) // Register new tendermint queries routes from grpc-gateway. tmservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) // Register legacy and grpc-gateway routes for all modules. ModuleBasics.RegisterRESTRoutes(clientCtx, apiSvr.Router) ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) // register swagger API from root so that other applications can override easily if apiConfig.Swagger { RegisterSwaggerAPI(clientCtx, apiSvr.Router) } }

# Next

Learn how to perform a chain upgrade to 0.40.