Skip to content

Commit

Permalink
proto: add extension trait for easier parsing of domain types (#4886)
Browse files Browse the repository at this point in the history
## 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.
  • Loading branch information
cronokirby authored Oct 7, 2024
1 parent 4f0d1f7 commit 7694c38
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion crates/proto/src/event.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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
<Self as DomainType>::Proto: ProtoEvent,
anyhow::Error: From<<Self as TryFrom<<Self as DomainType>::Proto>>::Error>,
{
fn try_from_event(event: &abci::Event) -> anyhow::Result<Self> {
Ok(<Self as DomainType>::Proto::from_event(event)?.try_into()?)
}
}

impl<T: DomainType> EventDomainType for T
where
<T as DomainType>::Proto: ProtoEvent,
anyhow::Error: From<<Self as TryFrom<<Self as DomainType>::Proto>>::Error>,
{
}

0 comments on commit 7694c38

Please sign in to comment.