diff --git a/CHANGELOG.md b/CHANGELOG.md index 940c70f6376f..1f0356a5b70d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * [#12634](https://github.com/cosmos/cosmos-sdk/pull/12634) Move `sdk.Dec` to math package. * [#12596](https://github.com/cosmos/cosmos-sdk/pull/12596) Remove all imports of the non-existent gogo/protobuf v1.3.3 to ease downstream use and go workspaces. * [#12187](https://github.com/cosmos/cosmos-sdk/pull/12187) Add batch operation for x/nft module. +* [#12693](https://github.com/cosmos/cosmos-sdk/pull/12693) Make sure the order of each node is consistent when emitting proto events. ### State Machine Breaking diff --git a/types/events.go b/types/events.go index dbff89ce2d02..2d295bebc09a 100644 --- a/types/events.go +++ b/types/events.go @@ -3,6 +3,8 @@ package types import ( "encoding/json" "fmt" + "golang.org/x/exp/maps" + "golang.org/x/exp/slices" "reflect" "sort" "strings" @@ -87,8 +89,13 @@ func TypedEventToEvent(tev proto.Message) (Event, error) { return Event{}, err } + // 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, v := range attrMap { + for _, k := range keys { + v := attrMap[k] attrs = append(attrs, abci.EventAttribute{ Key: k, Value: string(v), diff --git a/types/events_test.go b/types/events_test.go index a395f8c73838..a9aad208398c 100644 --- a/types/events_test.go +++ b/types/events_test.go @@ -67,6 +67,21 @@ func (s *eventsTestSuite) TestEventManager() { s.Require().Equal(em.Events(), events.AppendEvent(event)) } +func (s *eventsTestSuite) TestEmitTypedEvent() { + s.Run("deterministic key-value order", func() { + for i := 0; i < 10; i++ { + em := sdk.NewEventManager() + coin := sdk.NewCoin("fakedenom", sdk.NewInt(1999999)) + s.Require().NoError(em.EmitTypedEvent(&coin)) + s.Require().Len(em.Events(), 1) + attrs := em.Events()[0].Attributes + s.Require().Len(attrs, 2) + s.Require().Equal(attrs[0].Key, "amount") + s.Require().Equal(attrs[1].Key, "denom") + } + }) +} + func (s *eventsTestSuite) TestEventManagerTypedEvents() { em := sdk.NewEventManager()