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

Add a EmitTypeEvent function that doesn't add double quotes to string attributes #5

Merged
merged 2 commits into from
Aug 21, 2024
Merged
Changes from all 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
62 changes: 62 additions & 0 deletions utils/uevent/events.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package uevent

import (
"encoding/json"
"fmt"
"slices"

abci "github.com/cometbft/cometbft/abci/types"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/gogoproto/proto"
"golang.org/x/exp/maps"
)

// EmitTypedEvent takes a typed event and emits it.
// The original EmitTypedEvent from cosmos-sdk adds double quotes around the string attributes,
// which makes it difficult, if not impossible to query/subscribe to those events.
// See https://github.com/cosmos/cosmos-sdk/issues/12592 and
// https://github.com/dymensionxyz/sdk-utils/pull/5#discussion_r1724688379
func EmitTypedEvent(ctx sdk.Context, tev proto.Message) error {
event, err := TypedEventToEvent(tev)
if err != nil {
return err
}
ctx.EventManager().EmitEvent(event)
return nil
zale144 marked this conversation as resolved.
Show resolved Hide resolved
}

// TypedEventToEvent takes typed event and converts to Event object
func TypedEventToEvent(tev proto.Message) (ev sdk.Event, err error) {
evtType := proto.MessageName(tev)

var evtJSON []byte
evtJSON, err = codec.ProtoMarshalJSON(tev, nil)
if err != nil {
return
}

var attrMap map[string]any
if err = json.Unmarshal(evtJSON, &attrMap); err != nil {
return
}

// sort the keys to ensure the order is always the same
keys := maps.Keys(attrMap)
slices.Sort(keys)
danwt marked this conversation as resolved.
Show resolved Hide resolved

attrs := make([]abci.EventAttribute, 0, len(attrMap))
for _, k := range keys {
v := attrMap[k]
attrs = append(attrs, abci.EventAttribute{
Key: k,
Value: fmt.Sprintf("%v", v),
})
}

ev = sdk.Event{
Type: evtType,
Attributes: attrs,
}
return
}