Skip to content

Commit

Permalink
Add a EmitTypeEvent function that doesn't add double quotes to string…
Browse files Browse the repository at this point in the history
… attributes (#5)
  • Loading branch information
zale144 authored Aug 21, 2024
1 parent e29089e commit a6f8c61
Showing 1 changed file with 62 additions and 0 deletions.
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
}

// 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)

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
}

0 comments on commit a6f8c61

Please sign in to comment.