# Msg Services

A Msg Service processes messages. Msg Services are specific to the module in which they are defined, and only process messages defined within the said module. They are called from BaseApp during DeliverTx.

# Pre-requisite Readings

# Implementation of a module Msg service

All Msg processing is done by a Msg protobuf service. Each module should define a Msg service, which will be responsible for request and response serialization.

As further described in ADR 031, this approach has the advantage of clearly specifying return types and generating server and client code.

Based on the definition of the Msg service, Protobuf generates a MsgServer interface. It is the role of the module developer to implement this interface, by implementing the state transition logic that should happen upon receival of each Msg. As an example, here is the generated MsgServer interface for x/bank, which exposes two Msgs:

Copy // MsgServer is the server API for Msg service. type MsgServer interface { // Send defines a method for sending coins from one account to another account. Send(context.Context, *MsgSend) (*MsgSendResponse, error) // MultiSend defines a method for sending coins from some accounts to other accounts. MultiSend(context.Context, *MsgMultiSend) (*MsgMultiSendResponse, error) }

When possible, the existing module's Keeper should implement MsgServer, otherwise a msgServer struct that embeds the Keeper can be created, typically in ./keeper/msg_server.go:

Copy type msgServer struct { Keeper }

msgServer methods can retrieve the sdk.Context from the context.Context parameter method using the sdk.UnwrapSDKContext:

Copy ctx := sdk.UnwrapSDKContext(goCtx)

Msg processing usually follows these 2 steps:

  • First, they perform stateful checks to make sure the message is valid. At this stage, the message's ValidateBasic() method has already been called, meaning stateless checks on the message (like making sure parameters are correctly formatted) have already been performed. Checks performed in the msgServer method can be more expensive and require access to the state. For example, a msgServer method for a transfer message might check that the sending account has enough funds to actually perform the transfer. To access the state, the msgServer method needs to call the keeper's getter functions.
  • Then, if the checks are successful, the msgServer method calls the keeper's setter functions to actually perform the state transition.

Before returning, msgServer methods generally emit one or more events via the EventManager held in the ctx:

Copy ctx.EventManager().EmitEvent( sdk.NewEvent( eventType, // e.g. sdk.EventTypeMessage for a message, types.CustomEventType for a custom event defined in the module sdk.NewAttribute(attributeKey, attributeValue), ), )

These events are relayed back to the underlying consensus engine and can be used by service providers to implement services around the application. Click here to learn more about events.

The invoked msgServer method returns a proto.Message response and an error. These return values are then wrapped into an *sdk.Result or an error using sdk.WrapServiceResult(ctx sdk.Context, res proto.Message, err error):

Copy return sdk.WrapServiceResult(ctx, resMsg, err)

This method takes care of marshaling the res parameter to protobuf and attaching any events on the ctx.EventManager() to the sdk.Result.

Copy // Result is the union of ResponseFormat and ResponseCheckTx. message Result { option (gogoproto.goproto_getters) = false; // Data is any data returned from message or handler execution. It MUST be // length prefixed in order to separate data from multiple message executions. bytes data = 1; // Log contains the log information from message or handler execution. string log = 2; // Events contains a slice of Event objects that were emitted during message // or handler execution. repeated tendermint.abci.Event events = 3 [(gogoproto.nullable) = false]; }

# Legacy Amino Msgs

# handler type

The handler type defined in the Cosmos SDK will be deprecated in favor of Msg Services.

Here is the typical structure of a handler function:

Copy type Handler func(ctx Context, msg Msg) (*Result, error)

Let us break it down:

  • The Msg is the actual object being processed.
  • The Context contains all the necessary information needed to process the msg, as well as a branch of the latest state. If the msg is successfully processed, the branched version of the state contained in the ctx will be written to the main state (branch).
  • The [*Result] returned to BaseApp contains (among other things) information on the execution of the handler and events.

Module handlers are typically implemented in a ./handler.go file inside the module's folder. The module manager is used to add the module's handlers to the application's router via the Route() method. Typically, the manager's Route() method simply constructs a Route that calls a NewHandler() method defined in handler.go.

Copy // Route returns the message routing key for the gov module. func (am AppModule) Route() sdk.Route { return sdk.NewRoute(types.RouterKey, NewHandler(am.keeper)) }

# Implementation

NewHandler function dispatches a Msg to appropriate handler function, usually by using a switch statement:

Copy // NewHandler returns a handler for "bank" type messages. func NewHandler(k keeper.Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { ctx = ctx.WithEventManager(sdk.NewEventManager()) switch msg := msg.(type) { case *types.MsgSend: return handleMsgSend(ctx, k, msg) case *types.MsgMultiSend: return handleMsgMultiSend(ctx, k, msg) default: return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized bank message type: %T", msg) } } }

First, NewHandler function sets a new EventManager to the context to isolate events per msg. Then, a simple switch calls the appropriate handler based on the Msg type.

In this regard, handlers functions need to be implemented for each module Msg. This will also involve manual handler registration of Msg types. handlers functions should return a *Result and an error.

# Telemetry

New telemetry metrics can be created from msgServer methods when handling messages.

This is an example from the x/auth/vesting module:

Copy defer func() { telemetry.IncrCounter(1, "new", "account") for _, a := range msg.Amount { if a.Amount.IsInt64() { telemetry.SetGaugeWithLabels( []string{"tx", "msg", "create_vesting_account"}, float32(a.Amount.Int64()), []metrics.Label{telemetry.NewLabel("denom", a.Denom)}, ) } } }()

# Next

Learn about query services