Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: automate EventTypeMessage inclusion in every message execution #13532

Merged
merged 23 commits into from
Oct 16, 2022
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions UPGRADING.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,21 @@ the correct code.

### Modules

#### `**all**`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

<3

julienrbrt marked this conversation as resolved.
Show resolved Hide resolved

`EventTypeMessage` events, with `sdk.AttributeKeyModule` and `sdk.AttributeKeySender` are now emitted directly at message excecution (in `baseapp`).
This means that you can remove the following boilerplate from all your custom modules:

```go
ctx.EventManager().EmitEvent(
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(sdk.AttributeKeySender, `signer/sender`),
),
)
```

#### `x/gov`

##### Minimum Proposal Deposit At Time of Submission
Expand Down
41 changes: 25 additions & 16 deletions baseapp/baseapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -669,7 +669,6 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte) (gInfo sdk.GasInfo, re
// and we're in DeliverTx. Note, runMsgs will never return a reference to a
// Result if any single message fails or does not have a registered Handler.
result, err = app.runMsgs(runMsgCtx, msgs, mode)

if err == nil {

// Run optional postHandlers.
Expand Down Expand Up @@ -717,28 +716,19 @@ func (app *BaseApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg, mode runTxMode) (*s
break
}

var (
msgResult *sdk.Result
eventMsgName string // name to use as value in event `message.action`
err error
)

if handler := app.msgServiceRouter.Handler(msg); handler != nil {
// ADR 031 request type routing
msgResult, err = handler(ctx, msg)
eventMsgName = sdk.MsgTypeURL(msg)
} else {
handler := app.msgServiceRouter.Handler(msg)
if handler == nil {
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "can't route message %+v", msg)
}

// ADR 031 request type routing
msgResult, err := handler(ctx, msg)
if err != nil {
return nil, sdkerrors.Wrapf(err, "failed to execute message; message index: %d", i)
}

msgEvents := sdk.Events{
sdk.NewEvent(sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyAction, eventMsgName)),
}
msgEvents = msgEvents.AppendEvents(msgResult.GetEvents())
// create message events
msgEvents := createEvents(msg).AppendEvents(msgResult.GetEvents())

// append message events, data and logs
//
Expand Down Expand Up @@ -779,3 +769,22 @@ func (app *BaseApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg, mode runTxMode) (*s
func makeABCIData(msgResponses []*codectypes.Any) ([]byte, error) {
return proto.Marshal(&sdk.TxMsgData{MsgResponses: msgResponses})
}

func createEvents(msg sdk.Msg) sdk.Events {
julienrbrt marked this conversation as resolved.
Show resolved Hide resolved
eventMsgName := sdk.MsgTypeURL(msg)
msgEvent := sdk.NewEvent(sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyAction, eventMsgName))

// we set the signer attribute as the sender
if len(msg.GetSigners()) > 0 && !msg.GetSigners()[0].Empty() {
msgEvent = msgEvent.AppendAttributes(sdk.NewAttribute(sdk.AttributeKeySender, msg.GetSigners()[0].String()))
}

// here we assume that routes module name is the second element of the route
// e.g. "cosmos.bank.v1beta1.MsgSend" => "bank"
moduleName := strings.Split(eventMsgName, ".")
if len(moduleName) > 1 {
msgEvent = msgEvent.AppendAttributes(sdk.NewAttribute(sdk.AttributeKeyModule, moduleName[1]))
}

return sdk.Events{msgEvent}
}
4 changes: 4 additions & 0 deletions baseapp/testutil/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ func (msg *MsgCounter2) ValidateBasic() error {
var _ sdk.Msg = &MsgKeyValue{}

func (msg *MsgKeyValue) GetSigners() []sdk.AccAddress {
if len(msg.Signer) == 0 {
return []sdk.AccAddress{}
}

return []sdk.AccAddress{sdk.MustAccAddressFromBech32(msg.Signer)}
}

Expand Down
7 changes: 0 additions & 7 deletions docs/docs/core/02-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,6 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.46.0/types/context.go#L17-L42
`Events` by defining various `Types` and `Attributes` or use the common definitions found in `types/`. Clients can subscribe or query for these `Events`. These `Events` are collected throughout `DeliverTx`, `BeginBlock`, and `EndBlock` and are returned to Tendermint for indexing. For example:
* **Priority:** The transaction priority, only relevant in `CheckTx`.

```go
ctx.EventManager().EmitEvent(sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory)),
)
```

## Go Context Package

A basic `Context` is defined in the [Golang Context Package](https://pkg.go.dev/context). A `Context`
Expand Down
34 changes: 24 additions & 10 deletions docs/docs/core/08-events.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ sidebar_position: 1

:::

## Typed Events
## Events

Events are implemented in the Cosmos SDK as an alias of the ABCI `Event` type and
take the form of: `{eventType}.{attributeKey}={attributeValue}`.
Expand All @@ -35,11 +35,12 @@ To parse the attribute values as strings, make sure to add `'` (single quotes) a
:::

_Typed Events_ are Protobuf-defined [messages](../architecture/adr-032-typed-events.md) used by the Cosmos SDK
for emitting and querying Events. They are defined in a `event.proto` file, on a **per-module basis**.
for emitting and querying Events. They are defined in a `event.proto` file, on a **per-module basis** and are read as `proto.Message`.
_Legacy Events_ are defined on a **per-module basis** in the module's `/types/events.go` file.
They are triggered from the module's Protobuf [`Msg` service](../building-modules/03-msg-services.md)
by using the [`EventManager`](#eventmanager), where they are read as `proto.Message`.
by using the [`EventManager`](#eventmanager).

In addition, each module documents its Events under `spec/xx_events.md`.
In addition, each module documents its events under in the `Events` sections of its specs (x/{moduleName}/`README.md`).

Lastly, Events are returned to the underlying consensus engine in the response of the following ABCI messages:

Expand Down Expand Up @@ -71,21 +72,32 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.46.0/types/events.go#L17-L25
```

The `EventManager` comes with a set of useful methods to manage Events. The method
that is used most by module and application developers is `EmitTypedEvent` that tracks
that is used most by module and application developers is `EmitTypedEvent` or `EmitEvent` that tracks
an Event in the `EventManager`.

```go reference
https://github.com/cosmos/cosmos-sdk/blob/v0.46.0/types/events.go#L50-L59
```

Module developers should handle Event emission via the `EventManager#EmitTypedEvent` in each message
Module developers should handle Event emission via the `EventManager#EmitTypedEvent` or `EventManager#EmitEvent` in each message
`Handler` and in each `BeginBlock`/`EndBlock` handler. The `EventManager` is accessed via
the [`Context`](./02-context.md), where Event should be already registered, and emitted like this:


**Typed events:**

```go reference
https://github.com/cosmos/cosmos-sdk/blob/v0.46.0/x/group/keeper/msg_server.go#L89-L92
```

**Legacy events:**

```go
ctx.EventManager().EmitEvent(
sdk.NewEvent(eventType, sdk.NewAttribute(attributeKey, attributeValue)),
)
```

Module's `handler` function should also set a new `EventManager` to the `context` to isolate emitted Events per `message`:

```go
Expand Down Expand Up @@ -139,10 +151,12 @@ Subscribing to this Event would be done like so:

where `ownerAddress` is an address following the [`AccAddress`](../basics/03-accounts.md#addresses) format.

## Events
The same way can be used to subscribe to [legacy events](https://github.com/cosmos/cosmos-sdk/blob/v0.46.0/x/bank/types/events.go).

Previously, the Cosmos SDK supported emitting Events that were defined in `types/events.go`. It is the responsibility of the module developer to define Event types and Event attributes. Except in the `spec/XX_events.md` file, these Event types and attributes are unfortunately not easily discoverable,
## Default Events

This is why this methods as been deprecated, and replaced by [Typed Events](#typed-events).
There is a few events that are automatically emitted for all messages, directly from `baseapp`.
julienrbrt marked this conversation as resolved.
Show resolved Hide resolved
julienrbrt marked this conversation as resolved.
Show resolved Hide resolved

To learn more about the previous way of defining events, please refer to the [previous SDK documentation](https://docs.cosmos.network/v0.45/core/events.html#events-2).
* `message.action`: The name of the message type.
* `message.sender`: The address of the message signer.
* `message.module`: The name of the module that emitted the message.
12 changes: 6 additions & 6 deletions tests/e2e/tx/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,13 +221,13 @@ func (s IntegrationTestSuite) TestSimulateTx_GRPC() {
s.Require().NoError(err)
// Check the result and gas used are correct.
//
// The 13 events are:
// The 12 events are:
// - Sending Fee to the pool: coin_spent, coin_received, transfer and message.sender=<val1>
// - tx.* events: tx.fee, tx.acc_seq, tx.signature
// - Sending Amount to recipient: coin_spent, coin_received, transfer and message.sender=<val1>
// - Msg events: message.module=bank and message.action=/cosmos.bank.v1beta1.MsgSend
s.Require().Equal(len(res.GetResult().GetEvents()), 13) // 1 coin recv 1 coin spent, 1 transfer, 3 messages.
s.Require().True(res.GetGasInfo().GetGasUsed() > 0) // Gas used sometimes change, just check it's not empty.
// - Msg events: message.module=bank and message.action=/cosmos.bank.v1beta1.MsgSend (in one message)
s.Require().Equal(12, len(res.GetResult().GetEvents()))
s.Require().True(res.GetGasInfo().GetGasUsed() > 0) // Gas used sometimes change, just check it's not empty.
}
})
}
Expand Down Expand Up @@ -268,8 +268,8 @@ func (s IntegrationTestSuite) TestSimulateTx_GRPCGateway() {
s.Require().NoError(err)
// Check the result and gas used are correct.
s.Require().Len(result.GetResult().MsgResponses, 1)
s.Require().Equal(len(result.GetResult().GetEvents()), 13) // See TestSimulateTx_GRPC for the 13 events.
s.Require().True(result.GetGasInfo().GetGasUsed() > 0) // Gas used sometimes change, jus
s.Require().Equal(12, len(result.GetResult().GetEvents())) // See TestSimulateTx_GRPC for the 12 events.
s.Require().True(result.GetGasInfo().GetGasUsed() > 0) // Gas used sometimes change, just check it's not empty.
}
})
}
Expand Down
20 changes: 0 additions & 20 deletions x/auth/vesting/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,6 @@ func (s msgServer) CreateVestingAccount(goCtx context.Context, msg *types.MsgCre
return nil, err
}

ctx.EventManager().EmitEvent(
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
),
)

return &types.MsgCreateVestingAccountResponse{}, nil
}

Expand Down Expand Up @@ -145,13 +138,6 @@ func (s msgServer) CreatePermanentLockedAccount(goCtx context.Context, msg *type
return nil, err
}

ctx.EventManager().EmitEvent(
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
),
)

return &types.MsgCreatePermanentLockedAccountResponse{}, nil
}

Expand Down Expand Up @@ -205,11 +191,5 @@ func (s msgServer) CreatePeriodicVestingAccount(goCtx context.Context, msg *type
return nil, err
}

ctx.EventManager().EmitEvent(
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
),
)
return &types.MsgCreatePeriodicVestingAccountResponse{}, nil
}
3 changes: 0 additions & 3 deletions x/auth/vesting/types/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ const (
// ModuleName defines the module's name.
ModuleName = "vesting"

// AttributeValueCategory is an alias for the message event value.
AttributeValueCategory = ModuleName

// RouterKey defines the module's message routing key
RouterKey = ModuleName
)
30 changes: 0 additions & 30 deletions x/bank/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,6 @@ func (k msgServer) Send(goCtx context.Context, msg *types.MsgSend) (*types.MsgSe
}
}()

ctx.EventManager().EmitEvent(
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
),
)

return &types.MsgSendResponse{}, nil
}

Expand All @@ -94,13 +87,6 @@ func (k msgServer) MultiSend(goCtx context.Context, msg *types.MsgMultiSend) (*t
return nil, err
}

ctx.EventManager().EmitEvent(
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
),
)

return &types.MsgMultiSendResponse{}, nil
}

Expand All @@ -114,14 +100,6 @@ func (k msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParam
return nil, err
}

ctx.EventManager().EmitEvent(
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(sdk.AttributeKeySender, req.Authority),
),
)

return &types.MsgUpdateParamsResponse{}, nil
}

Expand All @@ -138,13 +116,5 @@ func (k msgServer) SetSendEnabled(goCtx context.Context, msg *types.MsgSetSendEn
k.DeleteSendEnabled(ctx, msg.UseDefaultFor...)
}

ctx.EventManager().EmitEvent(
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(sdk.AttributeKeySender, msg.Authority),
),
)

return &types.MsgSetSendEnabledResponse{}, nil
}
2 changes: 0 additions & 2 deletions x/bank/types/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ const (
AttributeKeyRecipient = "recipient"
AttributeKeySender = sdk.AttributeKeySender

AttributeValueCategory = ModuleName

// supply and balance tracking events name and attributes
EventTypeCoinSpent = "coin_spent"
EventTypeCoinReceived = "coin_received"
Expand Down
8 changes: 0 additions & 8 deletions x/consensus/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,5 @@ func (k msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParam

k.Set(ctx, &consensusParams)

ctx.EventManager().EmitEvent(
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(sdk.AttributeKeySender, req.Authority),
),
)

return &types.MsgUpdateParamsResponse{}, nil
}
2 changes: 0 additions & 2 deletions x/consensus/types/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ var (

// Events
const (
AttributeValueCategory = ModuleName

EventTypeUpdateParam = "update_param"

AttributeKeyParamUpdater = "param_updater"
Expand Down
5 changes: 0 additions & 5 deletions x/crisis/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,6 @@ func (k *Keeper) VerifyInvariant(goCtx context.Context, msg *types.MsgVerifyInva
types.EventTypeInvariant,
sdk.NewAttribute(types.AttributeKeyRoute, msg.InvariantRoute),
),
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCrisis),
sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender),
),
})

return &types.MsgVerifyInvariantResponse{}, nil
Expand Down
3 changes: 1 addition & 2 deletions x/crisis/types/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,5 @@ package types
const (
EventTypeInvariant = "invariant"

AttributeValueCrisis = ModuleName
AttributeKeyRoute = "route"
AttributeKeyRoute = "route"
)
Loading