Skip to main content

moonproof_node_client/
status.rs

1//! Pure translation from Substrate tx-pool statuses to wallet-level events
2//! and errors.
3//!
4//! The Substrate transaction pool reports ten discrete statuses (see
5//! `polkadot-sdk/.../transaction-pool/api/src/lib.rs`). The TS node-client's
6//! `#handleSubmissionResult` (`PolkadotNodeClient.ts:178-277`) collapses
7//! those into three streamable events (`Submitted`/`InBlock`/`Finalized`)
8//! and four terminal errors (`Usurped`/`Dropped`/`Invalid`/`FinalityTimeout`).
9//!
10//! This module encodes that collapse as a pure function so it can be tested
11//! without a live node — the adapter layer only has to translate subxt's
12//! native status type into [`TxStatus`] and call [`SubmissionOutcome::from_status`].
13
14use crate::error::NodeClientError;
15use crate::event::SubmissionEvent;
16
17/// Runtime-agnostic mirror of a Substrate transaction-pool status.
18///
19/// Subxt (and Polkadot.js before it) exposes these as a tagged enum; we
20/// accept them as simple Rust variants so the translation can be tested
21/// without any Substrate dep.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum TxStatus {
24    /// The tx was validated and is sitting in the ready queue.
25    Ready,
26    /// The tx is awaiting a gap in its signer's nonce before it becomes ready.
27    Future,
28    /// The tx was broadcast to peers.
29    Broadcast,
30    /// The tx was previously included in a block that later got reverted;
31    /// it's back in the pool waiting to be re-included.
32    Retracted,
33    /// The tx was included in a (non-final) block.
34    InBlock {
35        block_hash: String,
36        block_height: u64,
37    },
38    /// The tx's including block reached finality.
39    Finalized {
40        block_hash: String,
41        block_height: u64,
42    },
43    /// The tx did not finalize within the node's configured window.
44    FinalityTimeout,
45    /// The tx was replaced in the pool by another tx with matching
46    /// discriminators (same sender+nonce).
47    Usurped,
48    /// The tx was evicted from the pool (pool full, congested network).
49    Dropped,
50    /// The node rejected the tx as invalid (bad signature, `ValidateUnsigned`
51    /// returned `Err`, etc.).
52    Invalid,
53}
54
55/// Result of translating a single [`TxStatus`] against a running submission.
56///
57/// - [`SubmissionOutcome::Emit`] produces a [`SubmissionEvent`] and the
58///   stream should keep going (for `Ready`/`Future`/`Broadcast`/`Retracted`
59///   and `InBlock`).
60/// - [`SubmissionOutcome::EmitAndFinish`] emits a final event and the
61///   stream should end (for `Finalized`).
62/// - [`SubmissionOutcome::Fail`] produces a terminal error and the stream
63///   ends (for `FinalityTimeout`/`Usurped`/`Dropped`/`Invalid`).
64#[derive(Debug)]
65pub enum SubmissionOutcome {
66    Emit(SubmissionEvent),
67    EmitAndFinish(SubmissionEvent),
68    Fail(NodeClientError),
69}
70
71impl SubmissionOutcome {
72    /// Translate a single Substrate status into either an event or a
73    /// terminal error. Takes ownership of the status and copies of the tx
74    /// bytes and tx hash so the resulting event can live past the status.
75    ///
76    /// # Behavior
77    ///
78    /// Mirrors `PolkadotNodeClient.ts:#handleSubmissionResult`. In particular:
79    ///
80    /// - `Retracted` emits `Submitted` (not an error) — the tx is back in
81    ///   the pool and can still land. The TS code does the same.
82    /// - `Finalized` emits `Finalized` *and* ends the stream
83    ///   (`EmitAndFinish`) — subsequent statuses from the same subscription
84    ///   are not delivered.
85    pub fn from_status(status: TxStatus, tx: &[u8], tx_hash: &str) -> Self {
86        match status {
87            TxStatus::Ready | TxStatus::Future | TxStatus::Broadcast | TxStatus::Retracted => {
88                Self::Emit(SubmissionEvent::Submitted {
89                    tx: tx.to_vec(),
90                    tx_hash: tx_hash.to_owned(),
91                })
92            }
93            TxStatus::InBlock {
94                block_hash,
95                block_height,
96            } => Self::Emit(SubmissionEvent::InBlock {
97                tx: tx.to_vec(),
98                block_hash,
99                block_height,
100                tx_hash: tx_hash.to_owned(),
101            }),
102            TxStatus::Finalized {
103                block_hash,
104                block_height,
105            } => Self::EmitAndFinish(SubmissionEvent::Finalized {
106                tx: tx.to_vec(),
107                block_hash,
108                block_height,
109                tx_hash: tx_hash.to_owned(),
110            }),
111            TxStatus::FinalityTimeout => Self::Fail(NodeClientError::TransactionProgress {
112                message: "transaction did not finalize within the expected window".to_owned(),
113                tx_data: tx.to_vec(),
114                desired_stage: crate::event::SubmissionStage::Finalized,
115            }),
116            TxStatus::Usurped => Self::Fail(NodeClientError::TransactionUsurped {
117                tx_data: tx.to_vec(),
118            }),
119            TxStatus::Dropped => Self::Fail(NodeClientError::TransactionDropped {
120                tx_data: tx.to_vec(),
121            }),
122            TxStatus::Invalid => Self::Fail(NodeClientError::TransactionInvalid {
123                tx_data: tx.to_vec(),
124                source: None,
125            }),
126        }
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133    use crate::event::SubmissionStage;
134
135    fn tx() -> Vec<u8> {
136        vec![1, 2, 3, 4, 5]
137    }
138
139    fn assert_is_submitted(outcome: SubmissionOutcome) {
140        match outcome {
141            SubmissionOutcome::Emit(SubmissionEvent::Submitted { tx: e_tx, tx_hash }) => {
142                assert_eq!(e_tx, tx());
143                assert_eq!(tx_hash, "0xhash");
144            }
145            other => panic!("expected Emit(Submitted), got {other:?}"),
146        }
147    }
148
149    #[test]
150    fn ready_maps_to_submitted() {
151        assert_is_submitted(SubmissionOutcome::from_status(
152            TxStatus::Ready,
153            &tx(),
154            "0xhash",
155        ));
156    }
157
158    #[test]
159    fn future_maps_to_submitted() {
160        assert_is_submitted(SubmissionOutcome::from_status(
161            TxStatus::Future,
162            &tx(),
163            "0xhash",
164        ));
165    }
166
167    #[test]
168    fn broadcast_maps_to_submitted() {
169        assert_is_submitted(SubmissionOutcome::from_status(
170            TxStatus::Broadcast,
171            &tx(),
172            "0xhash",
173        ));
174    }
175
176    #[test]
177    fn retracted_maps_to_submitted_not_error() {
178        // Load-bearing: a retracted tx can still be re-included; the TS
179        // reference treats this as "Submitted" (back in flight), not as a
180        // failure.
181        assert_is_submitted(SubmissionOutcome::from_status(
182            TxStatus::Retracted,
183            &tx(),
184            "0xhash",
185        ));
186    }
187
188    #[test]
189    fn in_block_carries_block_hash_and_height() {
190        let outcome = SubmissionOutcome::from_status(
191            TxStatus::InBlock {
192                block_hash: "0xblk".into(),
193                block_height: 99,
194            },
195            &tx(),
196            "0xhash",
197        );
198        match outcome {
199            SubmissionOutcome::Emit(SubmissionEvent::InBlock {
200                block_hash,
201                block_height,
202                tx_hash,
203                ..
204            }) => {
205                assert_eq!(block_hash, "0xblk");
206                assert_eq!(block_height, 99);
207                assert_eq!(tx_hash, "0xhash");
208            }
209            other => panic!("expected Emit(InBlock), got {other:?}"),
210        }
211    }
212
213    #[test]
214    fn finalized_emits_and_finishes_the_stream() {
215        let outcome = SubmissionOutcome::from_status(
216            TxStatus::Finalized {
217                block_hash: "0xfin".into(),
218                block_height: 100,
219            },
220            &tx(),
221            "0xhash",
222        );
223        match outcome {
224            SubmissionOutcome::EmitAndFinish(SubmissionEvent::Finalized {
225                block_hash,
226                block_height,
227                ..
228            }) => {
229                assert_eq!(block_hash, "0xfin");
230                assert_eq!(block_height, 100);
231            }
232            other => panic!("expected EmitAndFinish(Finalized), got {other:?}"),
233        }
234    }
235
236    #[test]
237    fn finality_timeout_fails_with_progress_error_at_finalized_stage() {
238        let outcome = SubmissionOutcome::from_status(TxStatus::FinalityTimeout, &tx(), "0xhash");
239        match outcome {
240            SubmissionOutcome::Fail(NodeClientError::TransactionProgress {
241                desired_stage,
242                tx_data,
243                ..
244            }) => {
245                assert_eq!(desired_stage, SubmissionStage::Finalized);
246                assert_eq!(tx_data, tx());
247            }
248            other => panic!("expected Fail(TransactionProgress), got {other:?}"),
249        }
250    }
251
252    #[test]
253    fn usurped_fails_with_usurped_error() {
254        let outcome = SubmissionOutcome::from_status(TxStatus::Usurped, &tx(), "0xhash");
255        match outcome {
256            SubmissionOutcome::Fail(NodeClientError::TransactionUsurped { tx_data }) => {
257                assert_eq!(tx_data, tx());
258            }
259            other => panic!("expected Fail(TransactionUsurped), got {other:?}"),
260        }
261    }
262
263    #[test]
264    fn dropped_fails_with_dropped_error() {
265        let outcome = SubmissionOutcome::from_status(TxStatus::Dropped, &tx(), "0xhash");
266        assert!(matches!(
267            outcome,
268            SubmissionOutcome::Fail(NodeClientError::TransactionDropped { .. })
269        ));
270    }
271
272    #[test]
273    fn invalid_fails_with_invalid_error() {
274        let outcome = SubmissionOutcome::from_status(TxStatus::Invalid, &tx(), "0xhash");
275        assert!(matches!(
276            outcome,
277            SubmissionOutcome::Fail(NodeClientError::TransactionInvalid { .. })
278        ));
279    }
280}