Skip to main content

moonproof_node_client/
event.rs

1//! Submission events emitted while a transaction progresses through the node.
2//!
3//! The TS reference (`SubmissionEvent.ts`) collapses the Substrate tx-pool
4//! status stream into three observable events: [`SubmissionEvent::Submitted`]
5//! (for `Ready`/`Future`/`Broadcast`/`Retracted`), [`SubmissionEvent::InBlock`],
6//! and [`SubmissionEvent::Finalized`]. Terminal-error statuses
7//! (`FinalityTimeout`/`Usurped`/`Dropped`/`Invalid`) do not appear here — they
8//! are surfaced as [`crate::NodeClientError`] variants instead.
9
10/// Hex string with `0x` prefix, matching the TS `HexString` alias. Used for
11/// transaction and block hashes on the wire and in event payloads.
12pub type HexString = String;
13
14/// Event stream item emitted while a submitted transaction progresses through
15/// the node's tx pool.
16///
17/// Each variant carries the original transaction bytes for correlation —
18/// matches the TS `SubmissionEvent` which attaches `tx` to every case.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum SubmissionEvent {
21    /// Node accepted the extrinsic into its pool. Covers Substrate's
22    /// `Ready`, `Future`, `Broadcast`, and `Retracted` statuses — from the
23    /// wallet's point of view, the transaction is in flight but not yet
24    /// included in a block. A `Retracted` can reappear as a later `InBlock`
25    /// once the replacement block is imported.
26    Submitted { tx: Vec<u8>, tx_hash: HexString },
27
28    /// The transaction was included in a block. Not yet finalized — the chain
29    /// could still re-org. Wallets that need strong finality should wait for
30    /// [`SubmissionEvent::Finalized`].
31    InBlock {
32        tx: Vec<u8>,
33        block_hash: HexString,
34        block_height: u64,
35        tx_hash: HexString,
36    },
37
38    /// The transaction's including block reached GRANDPA finality. Terminal
39    /// success — stream completes after this.
40    Finalized {
41        tx: Vec<u8>,
42        block_hash: HexString,
43        block_height: u64,
44        tx_hash: HexString,
45    },
46}
47
48impl SubmissionEvent {
49    /// Identify which [`SubmissionStage`] this event corresponds to. Useful
50    /// for the `send_and_wait_for` pattern where callers pick the stage they
51    /// want to block on.
52    #[must_use]
53    pub fn stage(&self) -> SubmissionStage {
54        match self {
55            Self::Submitted { .. } => SubmissionStage::Submitted,
56            Self::InBlock { .. } => SubmissionStage::InBlock,
57            Self::Finalized { .. } => SubmissionStage::Finalized,
58        }
59    }
60
61    /// Shared transaction hash. Present on every variant.
62    #[must_use]
63    pub fn tx_hash(&self) -> &str {
64        match self {
65            Self::Submitted { tx_hash, .. }
66            | Self::InBlock { tx_hash, .. }
67            | Self::Finalized { tx_hash, .. } => tx_hash,
68        }
69    }
70
71    /// Underlying transaction bytes. Present on every variant.
72    #[must_use]
73    pub fn tx_bytes(&self) -> &[u8] {
74        match self {
75            Self::Submitted { tx, .. } | Self::InBlock { tx, .. } | Self::Finalized { tx, .. } => {
76                tx
77            }
78        }
79    }
80
81    /// Block hash and height — `Some` only for [`SubmissionEvent::InBlock`]
82    /// and [`SubmissionEvent::Finalized`]. `None` for [`SubmissionEvent::Submitted`].
83    #[must_use]
84    pub fn block(&self) -> Option<(&str, u64)> {
85        match self {
86            Self::Submitted { .. } => None,
87            Self::InBlock {
88                block_hash,
89                block_height,
90                ..
91            }
92            | Self::Finalized {
93                block_hash,
94                block_height,
95                ..
96            } => Some((block_hash, *block_height)),
97        }
98    }
99}
100
101/// Coarse-grained stage label — ordered (`Submitted < InBlock < Finalized`)
102/// so callers can say "wait for at least `InBlock`" semantically.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
104pub enum SubmissionStage {
105    Submitted,
106    InBlock,
107    Finalized,
108}
109
110impl SubmissionStage {
111    /// Stable short name matching the TS `_tag` field: `"Submitted"`,
112    /// `"InBlock"`, `"Finalized"`. Used in error messages so logs read the
113    /// same across runtimes.
114    #[must_use]
115    pub fn as_tag(&self) -> &'static str {
116        match self {
117            Self::Submitted => "Submitted",
118            Self::InBlock => "InBlock",
119            Self::Finalized => "Finalized",
120        }
121    }
122}
123
124impl std::fmt::Display for SubmissionStage {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        f.write_str(self.as_tag())
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    fn sample_tx() -> Vec<u8> {
135        vec![0xde, 0xad, 0xbe, 0xef]
136    }
137
138    #[test]
139    fn submitted_event_exposes_tag_hash_and_bytes() {
140        let event = SubmissionEvent::Submitted {
141            tx: sample_tx(),
142            tx_hash: "0xabc".into(),
143        };
144        assert_eq!(event.stage(), SubmissionStage::Submitted);
145        assert_eq!(event.tx_hash(), "0xabc");
146        assert_eq!(event.tx_bytes(), sample_tx().as_slice());
147        assert_eq!(event.block(), None);
148    }
149
150    #[test]
151    fn in_block_event_exposes_block_height_and_hash() {
152        let event = SubmissionEvent::InBlock {
153            tx: sample_tx(),
154            block_hash: "0xblk".into(),
155            block_height: 7,
156            tx_hash: "0xabc".into(),
157        };
158        assert_eq!(event.stage(), SubmissionStage::InBlock);
159        assert_eq!(event.block(), Some(("0xblk", 7)));
160    }
161
162    #[test]
163    fn finalized_event_exposes_block_height_and_hash() {
164        let event = SubmissionEvent::Finalized {
165            tx: sample_tx(),
166            block_hash: "0xfin".into(),
167            block_height: 8,
168            tx_hash: "0xabc".into(),
169        };
170        assert_eq!(event.stage(), SubmissionStage::Finalized);
171        assert_eq!(event.block(), Some(("0xfin", 8)));
172    }
173
174    #[test]
175    fn submission_stage_ordering_matches_tx_lifecycle() {
176        assert!(SubmissionStage::Submitted < SubmissionStage::InBlock);
177        assert!(SubmissionStage::InBlock < SubmissionStage::Finalized);
178    }
179
180    #[test]
181    fn submission_stage_tags_are_stable_strings() {
182        assert_eq!(SubmissionStage::Submitted.as_tag(), "Submitted");
183        assert_eq!(SubmissionStage::InBlock.as_tag(), "InBlock");
184        assert_eq!(SubmissionStage::Finalized.as_tag(), "Finalized");
185        assert_eq!(format!("{}", SubmissionStage::Finalized), "Finalized");
186    }
187}