Unleashing the Power of Typed Events in Cosmos SDK
Are you ready to streamline event handling and unlock a new level of application responsiveness? Look no further than typed events, a…
Unleashing the Power of Typed Events in Cosmos SDK
Are you ready to streamline event handling and unlock a new level of application responsiveness? Look no further than typed events, a revolutionary addition to the Cosmos SDK. This blog post dives deep into how typed events empower you to build dynamic, event-driven applications within the Cosmos ecosystem.
The Challenge: String Matching
Traditionally, Cosmos SDK applications relied on strings to define events within message handlers. This approach, while functional, presents significant drawbacks:
- Tedious String Matching: Consuming events necessitates cumbersome raw string matching and parsing, hindering developer productivity.
- Limited Type Safety: The lack of type safety introduces potential errors and complicates code maintenance.
- Restricted Expressiveness: String-based events offer limited flexibility for representing complex event data.
The Solution: Embracing Typed Events
The Cosmos SDK’s typed events proposal introduces a paradigm shift. By leveraging Protobuf message types, it enables developers to define events with a clear structure and well-defined data types. This approach offers a multitude of benefits:
- Enhanced Developer Experience: Type safety and clear event definitions streamline development, reduce errors, and improve code readability.
- Simplified Event Consumption: Consume events with ease by directly working with strongly typed message objects, eliminating the need for string parsing gymnastics.
- Richer Event Data: Represent complex event details using Protobuf message structures, enabling more expressive and informative event definitions.
A Glimpse into Implementation
The typed events functionality is implemented through two key functions:
- EmitTypedEvent: This function takes a typed event message and converts it into a standard Cosmos SDK event for emission.
- ParseTypedEvent: This function takes a standard Cosmos SDK event and parses it back into its original typed event message format.
Practical Example: Submitting a Governance Proposal
Let’s consider the MsgSubmitProposal message from the Cosmos SDK’s governance module. With typed events, we can define a corresponding event type like EventSubmitProposal:
Protocol Buffers:
message EventSubmitProposal {
string from_address = 1;
uint64 proposal_id = 2;
TextProposal proposal = 3;
}
When a proposal is submitted, the application can then emit a typed EventSubmitProposal event containing details like the submitter’s address, proposal ID, and proposal data.
Under the Hood: Key Functions
The typed events functionality relies on two crucial functions:
- EmitTypedEvent: This function takes a typed event message and converts it into a standard Cosmos SDK event for emission.
- ParseTypedEvent: This function takes a standard Cosmos SDK event and parses it back into its original typed event message format.
Code Snippet 1: EmitTypedEvent Function
// EmitTypedEvent takes a typed event and emits converting it into sdk.Event
func (em *EventManager) EmitTypedEvent(event proto.Message) error {
evtType := proto.MessageName(event)
evtJSON, err := codec.ProtoMarshalJSON(event)
if err != nil {
return err
}
var attrMap map[string]json.RawMessage
err = json.Unmarshal(evtJSON, &attrMap)
if err != nil {
return err
}
var attrs []abci.EventAttribute
for k, v := range attrMap {
attrs = append(attrs, abci.EventAttribute{
Key: []byte(k),
Value: v,
})
}
em.EmitEvent(Event{
Type: evtType,
Attributes: attrs,
})
return nil
}
Explanation:
- The function takes a proto.Message as input, representing the typed event.
- It retrieves the event type name using proto.MessageName.
- The function converts the typed event to JSON format using codec.ProtoMarshalJSON.
- The JSON-encoded event is then unmarshaled into a map of strings to JSON raw messages using json.Unmarshal.
- This map is iterated over, and each key-value pair is converted into an abci.EventAttribute.
- Finally, a new Event struct is created with the event type and attributes, and em.EmitEvent is called to emit the event.
Code Snippet 2: ParseTypedEvent Function
// ParseTypedEvent converts abci.Event back to typed event
func ParseTypedEvent(event abci.Event) (proto.Message, error) {
concreteGoType := proto.MessageType(event.Type)
if concreteGoType == nil {
return nil, fmt.Errorf(“failed to retrieve the message of type %q”, event.Type)
}
var value reflect.Value
if concreteGoType.Kind() == reflect.Ptr {
value = reflect.New(concreteGoType.Elem())
} else {
value = reflect.Zero(concreteGoType)
}
protoMsg, ok := value.Interface().(proto.Message)
if !ok {
return nil, fmt.Errorf(“%q does not implement proto.Message”, event.Type)
}
attrMap := make(map[string]json.RawMessage)
for _, attr := range event.Attributes {
attrMap[string(attr.Key)] = attr
Building Event-Driven Applications
Typed events empower you to construct applications that react to on-chain events in real-time. Here’s a breakdown of the workflow:
- Define Event Handlers: Implement functions that handle specific typed event messages.
- Subscribe to Events: Register your event handlers with the Cosmos SDK’s event emitter.
- React to Events: Upon receiving a relevant event, the corresponding event handler is triggered, allowing you to execute custom logic.
A Brighter Future for Cosmos Development
Typed events represent a significant leap forward for Cosmos SDK application development. By streamlining event handling and fostering a more robust event-driven architecture, they pave the way for a new generation of dynamic and responsive Cosmos applications.
Have you explored typed events in your Cosmos SDK projects? Share your experiences, questions, and potential use cases in the comments below. Let’s leverage the power of typed events to build a more robust and developer-friendly Cosmos ecosystem!
메타데이터
- post_id
- 0e8a9c7cb8fe
- slug
- unleashing-the-power-of-typed-events-in-cosmos-sdk-0e8a9c7cb8fe
- url
- https://medium.com/@fahimcsekuet/unleashing-the-power-of-typed-events-in-cosmos-sdk-0e8a9c7cb8fe
- canonical_url
- https://medium.com/@fahimcsekuet/unleashing-the-power-of-typed-events-in-cosmos-sdk-0e8a9c7cb8fe
- author_url
- https://medium.com/@fahimcsekuet
- status
- ok
- fetched_at
- 2026-07-07 22:13:32