From 7694c38f9f869bbfaac9bacbbee6bae6f724e46f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=BAc=C3=A1s=20Meier?= Date: Mon, 7 Oct 2024 14:00:02 -0700 Subject: [PATCH] proto: add extension trait for easier parsing of domain types (#4886) ## Describe your changes This allows creating domain types for each of the events, e.g. `EventBatchSwap`, and then doing `EventBatchSwap::try_from_event(&event)`, which makes the pindexer app views much more ergonomic, especially because we can avoid having to duplicate event parsing logic across views. In subsequent PRs, we should create domain types for each component. We can probably do this as needed, when we write app views touching particular components. ## Checklist before requesting a review - [x] If this code contains consensus-breaking changes, I have added the "consensus-breaking" label. Otherwise, I declare my belief that there are not consensus-breaking changes, for the following reason: > Just an internal refactor to events code, so doubly non breaking. --- crates/proto/src/event.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/proto/src/event.rs b/crates/proto/src/event.rs index 0c24a6ce48..e7e69fefa4 100644 --- a/crates/proto/src/event.rs +++ b/crates/proto/src/event.rs @@ -1,4 +1,4 @@ -use crate::{Message, Name}; +use crate::{DomainType, Message, Name}; use anyhow::{self, Context}; use serde::{de::DeserializeOwned, Serialize}; use std::collections::HashMap; @@ -121,3 +121,25 @@ mod tests { assert_eq!(proto_output, proto_output2); } } + +/// An extension trait allowing for easy conversion from events into domain types. +/// +/// This makes the task of writing code that processes events much more easy, +/// since you can just attempt to parse the event directly into the specific domain +/// type. +pub trait EventDomainType: DomainType +where + ::Proto: ProtoEvent, + anyhow::Error: From<::Proto>>::Error>, +{ + fn try_from_event(event: &abci::Event) -> anyhow::Result { + Ok(::Proto::from_event(event)?.try_into()?) + } +} + +impl EventDomainType for T +where + ::Proto: ProtoEvent, + anyhow::Error: From<::Proto>>::Error>, +{ +}