Skip to main content

moonproof_node_client/
error.rs

1//! Error taxonomy for the Midnight node client.
2//!
3//! Mirrors the TS tagged-error union in
4//! `midnight-wallet/packages/node-client/src/effect/NodeClientError.ts`.
5//! Each variant captures enough context (failing tx bytes, desired stage,
6//! underlying cause) that a caller can log or react meaningfully.
7
8use crate::event::SubmissionStage;
9
10/// Errors produced by the node-client. All terminal transaction statuses
11/// (`Usurped`/`Dropped`/`Invalid`) surface as errors — they end the
12/// submission stream without emitting a terminal event.
13#[derive(Debug, thiserror::Error)]
14pub enum NodeClientError {
15    /// The initial submission RPC call failed before the tx entered the pool.
16    /// Typical cause: the node rejected the extrinsic as not well-formed.
17    #[error("transaction submission failed: {message}")]
18    Submission {
19        message: String,
20        tx_data: Vec<u8>,
21        #[source]
22        source: Option<Box<dyn std::error::Error + Send + Sync>>,
23    },
24
25    /// Could not connect to the node (transport-level failure — WebSocket
26    /// unreachable, handshake timed out, etc.).
27    #[error("connection error: {message}")]
28    Connection {
29        message: String,
30        #[source]
31        source: Option<Box<dyn std::error::Error + Send + Sync>>,
32    },
33
34    /// The submission stream closed before reaching the requested stage and
35    /// no other error was reported — the stream ended cleanly but the caller
36    /// wanted a terminal event it never saw.
37    #[error(
38        "transaction did not reach desired stage '{desired_stage}' and no other error was reported"
39    )]
40    TransactionProgress {
41        message: String,
42        tx_data: Vec<u8>,
43        desired_stage: SubmissionStage,
44    },
45
46    /// Failed to decode a status or block payload returned by the node.
47    /// Indicates a wire-format mismatch (usually a runtime upgrade the
48    /// client hasn't caught up with).
49    #[error("failed to parse node response: {message}")]
50    Parse {
51        message: String,
52        #[source]
53        source: Option<Box<dyn std::error::Error + Send + Sync>>,
54    },
55
56    /// The transaction was usurped — replaced in the pool by another tx with
57    /// matching discriminators (same sender+nonce). The node dropped this
58    /// submission's watcher; the replacement tx may still succeed.
59    #[error("transaction usurped (replaced in pool by another matching tx)")]
60    TransactionUsurped { tx_data: Vec<u8> },
61
62    /// The mempool dropped the transaction — commonly because the pool is
63    /// full and the network is congested.
64    #[error("transaction dropped from mempool (pool likely full / congested)")]
65    TransactionDropped { tx_data: Vec<u8> },
66
67    /// The node validated the extrinsic and rejected it as invalid (bad
68    /// signature / fails `ValidateUnsigned` / ledger well-formedness check).
69    #[error("transaction rejected as invalid by node")]
70    TransactionInvalid {
71        tx_data: Vec<u8>,
72        #[source]
73        source: Option<Box<dyn std::error::Error + Send + Sync>>,
74    },
75}
76
77impl NodeClientError {
78    /// Byte payload of the transaction that produced this error, if any.
79    /// `ConnectionError` and `ParseError` do not carry a tx — they are
80    /// transport-level and can occur before any submission.
81    #[must_use]
82    pub fn tx_data(&self) -> Option<&[u8]> {
83        match self {
84            Self::Submission { tx_data, .. }
85            | Self::TransactionProgress { tx_data, .. }
86            | Self::TransactionUsurped { tx_data }
87            | Self::TransactionDropped { tx_data }
88            | Self::TransactionInvalid { tx_data, .. } => Some(tx_data),
89            Self::Connection { .. } | Self::Parse { .. } => None,
90        }
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn error_variants_display_is_informative() {
100        let err = NodeClientError::TransactionProgress {
101            message: "stream ended".into(),
102            tx_data: vec![1, 2, 3],
103            desired_stage: SubmissionStage::Finalized,
104        };
105        let rendered = format!("{err}");
106        assert!(
107            rendered.contains("Finalized"),
108            "progress error should name the desired stage: {rendered}"
109        );
110    }
111
112    #[test]
113    fn tx_data_accessor_returns_bytes_for_tx_scoped_variants() {
114        let tx = vec![0xaa; 32];
115        let err = NodeClientError::TransactionInvalid {
116            tx_data: tx.clone(),
117            source: None,
118        };
119        assert_eq!(err.tx_data(), Some(tx.as_slice()));
120    }
121
122    #[test]
123    fn tx_data_accessor_returns_none_for_transport_variants() {
124        let err = NodeClientError::Connection {
125            message: "ws down".into(),
126            source: None,
127        };
128        assert_eq!(err.tx_data(), None);
129
130        let err = NodeClientError::Parse {
131            message: "bad u64".into(),
132            source: None,
133        };
134        assert_eq!(err.tx_data(), None);
135    }
136
137    #[test]
138    fn node_client_error_is_send_sync() {
139        fn assert_send_sync<T: Send + Sync>() {}
140        assert_send_sync::<NodeClientError>();
141    }
142}