moonproof-node-client 0.2.2

Rust client for the Midnight node's Substrate submission RPC
Documentation
//! Error taxonomy for the Midnight node client.
//!
//! Mirrors the TS tagged-error union in
//! `midnight-wallet/packages/node-client/src/effect/NodeClientError.ts`.
//! Each variant captures enough context (failing tx bytes, desired stage,
//! underlying cause) that a caller can log or react meaningfully.

use crate::event::SubmissionStage;

/// Errors produced by the node-client. All terminal transaction statuses
/// (`Usurped`/`Dropped`/`Invalid`) surface as errors — they end the
/// submission stream without emitting a terminal event.
#[derive(Debug, thiserror::Error)]
pub enum NodeClientError {
    /// The initial submission RPC call failed before the tx entered the pool.
    /// Typical cause: the node rejected the extrinsic as not well-formed.
    #[error("transaction submission failed: {message}")]
    Submission {
        message: String,
        tx_data: Vec<u8>,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Could not connect to the node (transport-level failure — WebSocket
    /// unreachable, handshake timed out, etc.).
    #[error("connection error: {message}")]
    Connection {
        message: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// The submission stream closed before reaching the requested stage and
    /// no other error was reported — the stream ended cleanly but the caller
    /// wanted a terminal event it never saw.
    #[error(
        "transaction did not reach desired stage '{desired_stage}' and no other error was reported"
    )]
    TransactionProgress {
        message: String,
        tx_data: Vec<u8>,
        desired_stage: SubmissionStage,
    },

    /// Failed to decode a status or block payload returned by the node.
    /// Indicates a wire-format mismatch (usually a runtime upgrade the
    /// client hasn't caught up with).
    #[error("failed to parse node response: {message}")]
    Parse {
        message: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// The transaction was usurped — replaced in the pool by another tx with
    /// matching discriminators (same sender+nonce). The node dropped this
    /// submission's watcher; the replacement tx may still succeed.
    #[error("transaction usurped (replaced in pool by another matching tx)")]
    TransactionUsurped { tx_data: Vec<u8> },

    /// The mempool dropped the transaction — commonly because the pool is
    /// full and the network is congested.
    #[error("transaction dropped from mempool (pool likely full / congested)")]
    TransactionDropped { tx_data: Vec<u8> },

    /// The node validated the extrinsic and rejected it as invalid (bad
    /// signature / fails `ValidateUnsigned` / ledger well-formedness check).
    #[error("transaction rejected as invalid by node")]
    TransactionInvalid {
        tx_data: Vec<u8>,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
}

impl NodeClientError {
    /// Byte payload of the transaction that produced this error, if any.
    /// `ConnectionError` and `ParseError` do not carry a tx — they are
    /// transport-level and can occur before any submission.
    #[must_use]
    pub fn tx_data(&self) -> Option<&[u8]> {
        match self {
            Self::Submission { tx_data, .. }
            | Self::TransactionProgress { tx_data, .. }
            | Self::TransactionUsurped { tx_data }
            | Self::TransactionDropped { tx_data }
            | Self::TransactionInvalid { tx_data, .. } => Some(tx_data),
            Self::Connection { .. } | Self::Parse { .. } => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn error_variants_display_is_informative() {
        let err = NodeClientError::TransactionProgress {
            message: "stream ended".into(),
            tx_data: vec![1, 2, 3],
            desired_stage: SubmissionStage::Finalized,
        };
        let rendered = format!("{err}");
        assert!(
            rendered.contains("Finalized"),
            "progress error should name the desired stage: {rendered}"
        );
    }

    #[test]
    fn tx_data_accessor_returns_bytes_for_tx_scoped_variants() {
        let tx = vec![0xaa; 32];
        let err = NodeClientError::TransactionInvalid {
            tx_data: tx.clone(),
            source: None,
        };
        assert_eq!(err.tx_data(), Some(tx.as_slice()));
    }

    #[test]
    fn tx_data_accessor_returns_none_for_transport_variants() {
        let err = NodeClientError::Connection {
            message: "ws down".into(),
            source: None,
        };
        assert_eq!(err.tx_data(), None);

        let err = NodeClientError::Parse {
            message: "bad u64".into(),
            source: None,
        };
        assert_eq!(err.tx_data(), None);
    }

    #[test]
    fn node_client_error_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<NodeClientError>();
    }
}