Skip to main content

sui_rpc/light_client/events/
envelope.rs

1//! SDK-side envelope for authenticated events received from the v2
2//! `LedgerService.ListEvents` RPC filtered by `EventStreamHeadFilter`.
3
4use sui_sdk_types::Digest;
5use sui_sdk_types::Event;
6
7use crate::field::FieldMask;
8use crate::field::FieldMaskUtil;
9use crate::proto::TryFromProtoError;
10use crate::proto::sui::rpc::v2::Event as ProtoEvent;
11
12/// A single authenticated event paired with the positional metadata a
13/// verifier needs to reconstruct its `EventCommitment` leaf.
14///
15/// The tuple `(checkpoint, transaction_index, event_index)` identifies
16/// the event's position in the ledger; combined with the per-event
17/// digest derived from `event`, those four pieces form the BCS-encoded
18/// merkle leaf the framework folds into the stream's MMR — see
19/// `sui_sdk_types::framework::EventCommitment`.
20///
21/// `transaction_digest` is carried for caller convenience (e.g.,
22/// correlating with an explorer URL or another transaction-keyed
23/// lookup) but is not an input to the cryptographic verification.
24///
25/// The envelope deliberately omits any `stream_id`: every event in a
26/// `ListEvents` stream filtered by `EventStreamHeadFilter` belongs to
27/// the same stream by construction, and the caller already knows which
28/// stream they asked for.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct AuthenticatedEvent {
31    /// The checkpoint containing the transaction that emitted this event.
32    pub checkpoint: u64,
33    /// 0-based index of the emitting transaction within its containing
34    /// checkpoint.
35    pub transaction_index: u64,
36    /// 0-based index of this event within its transaction's event list.
37    pub event_index: u32,
38    /// The digest of the emitting transaction.
39    pub transaction_digest: Digest,
40    /// The event payload itself.
41    pub event: Event,
42}
43
44impl AuthenticatedEvent {
45    /// Read mask selecting every proto `Event` field the
46    /// [`TryFrom<&ProtoEvent>`] conversion requires: the ledger position,
47    /// the emitting transaction's digest, and the event payload.
48    pub(super) fn read_mask() -> FieldMask {
49        FieldMask::from_paths([
50            ProtoEvent::CHECKPOINT_FIELD.name,
51            ProtoEvent::TRANSACTION_INDEX_FIELD.name,
52            ProtoEvent::EVENT_INDEX_FIELD.name,
53            ProtoEvent::TRANSACTION_DIGEST_FIELD.name,
54            ProtoEvent::PACKAGE_ID_FIELD.name,
55            ProtoEvent::MODULE_FIELD.name,
56            ProtoEvent::SENDER_FIELD.name,
57            ProtoEvent::EVENT_TYPE_FIELD.name,
58            ProtoEvent::CONTENTS_FIELD.name,
59        ])
60    }
61}
62
63impl TryFrom<&ProtoEvent> for AuthenticatedEvent {
64    type Error = TryFromProtoError;
65
66    fn try_from(value: &ProtoEvent) -> Result<Self, Self::Error> {
67        let checkpoint = value
68            .checkpoint
69            .ok_or_else(|| TryFromProtoError::missing(ProtoEvent::CHECKPOINT_FIELD.name))?;
70        let transaction_index = value
71            .transaction_index
72            .ok_or_else(|| TryFromProtoError::missing(ProtoEvent::TRANSACTION_INDEX_FIELD.name))?;
73        let event_index = value
74            .event_index
75            .ok_or_else(|| TryFromProtoError::missing(ProtoEvent::EVENT_INDEX_FIELD.name))?;
76        let transaction_digest = value
77            .transaction_digest
78            .as_ref()
79            .ok_or_else(|| TryFromProtoError::missing(ProtoEvent::TRANSACTION_DIGEST_FIELD.name))?
80            .parse()
81            .map_err(|e| TryFromProtoError::invalid(ProtoEvent::TRANSACTION_DIGEST_FIELD, e))?;
82        let event = Event::try_from(value)?;
83
84        Ok(Self {
85            checkpoint,
86            transaction_index,
87            event_index,
88            transaction_digest,
89            event,
90        })
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97    use crate::field::FieldMaskTree;
98    use crate::merge::Merge;
99    use sui_sdk_types::Address;
100    use sui_sdk_types::Identifier;
101    use sui_sdk_types::StructTag;
102
103    fn sample_authenticated_event() -> AuthenticatedEvent {
104        AuthenticatedEvent {
105            checkpoint: 42,
106            transaction_index: 3,
107            event_index: 7,
108            transaction_digest: Digest::new([0xaa; 32]),
109            event: Event {
110                package_id: Address::TWO,
111                module: Identifier::from_static("clock"),
112                sender: Address::TWO,
113                type_: StructTag::new(
114                    Address::TWO,
115                    Identifier::from_static("clock"),
116                    Identifier::from_static("Tick"),
117                    vec![],
118                ),
119                contents: vec![0xde, 0xad, 0xbe, 0xef],
120            },
121        }
122    }
123
124    /// The proto `Event` a server returns for `value` under
125    /// [`AuthenticatedEvent::read_mask`].
126    fn to_proto(value: &AuthenticatedEvent) -> ProtoEvent {
127        ProtoEvent::from(value.event.clone())
128            .with_checkpoint(value.checkpoint)
129            .with_transaction_digest(value.transaction_digest.to_string())
130            .with_transaction_index(value.transaction_index)
131            .with_event_index(value.event_index)
132    }
133
134    #[test]
135    fn round_trip_through_proto_preserves_envelope() {
136        let original = sample_authenticated_event();
137        let back = AuthenticatedEvent::try_from(&to_proto(&original)).unwrap();
138        assert_eq!(back, original);
139    }
140
141    /// Every field the conversion reads is selected by the read mask,
142    /// so a server honoring the mask returns a convertible event.
143    #[test]
144    fn read_mask_selects_every_converted_field() {
145        let mask = FieldMaskTree::from(AuthenticatedEvent::read_mask());
146        let masked = ProtoEvent::merge_from(&to_proto(&sample_authenticated_event()), &mask);
147        assert_eq!(
148            AuthenticatedEvent::try_from(&masked).unwrap(),
149            sample_authenticated_event()
150        );
151    }
152
153    #[test]
154    fn missing_checkpoint_is_rejected() {
155        let mut proto = to_proto(&sample_authenticated_event());
156        proto.checkpoint = None;
157        let err = AuthenticatedEvent::try_from(&proto).unwrap_err();
158        assert_eq!(err.field_violation().field, "checkpoint");
159    }
160
161    #[test]
162    fn missing_transaction_index_is_rejected() {
163        let mut proto = to_proto(&sample_authenticated_event());
164        proto.transaction_index = None;
165        let err = AuthenticatedEvent::try_from(&proto).unwrap_err();
166        assert_eq!(err.field_violation().field, "transaction_index");
167    }
168
169    #[test]
170    fn missing_event_index_is_rejected() {
171        let mut proto = to_proto(&sample_authenticated_event());
172        proto.event_index = None;
173        let err = AuthenticatedEvent::try_from(&proto).unwrap_err();
174        assert_eq!(err.field_violation().field, "event_index");
175    }
176
177    #[test]
178    fn missing_transaction_digest_is_rejected() {
179        let mut proto = to_proto(&sample_authenticated_event());
180        proto.transaction_digest = None;
181        let err = AuthenticatedEvent::try_from(&proto).unwrap_err();
182        assert_eq!(err.field_violation().field, "transaction_digest");
183    }
184
185    #[test]
186    fn missing_payload_field_is_rejected() {
187        let mut proto = to_proto(&sample_authenticated_event());
188        proto.package_id = None;
189        let err = AuthenticatedEvent::try_from(&proto).unwrap_err();
190        assert_eq!(err.field_violation().field, "package_id");
191    }
192
193    /// A malformed `transaction_digest` (base58-undecodable) reports the
194    /// `transaction_digest` field with a parse-error source.
195    #[test]
196    fn malformed_transaction_digest_is_rejected() {
197        let mut proto = to_proto(&sample_authenticated_event());
198        proto.transaction_digest = Some("not-a-real-digest!".into());
199        let err = AuthenticatedEvent::try_from(&proto).unwrap_err();
200        assert_eq!(err.field_violation().field, "transaction_digest");
201    }
202}