moonproof-node-client 0.2.1

Rust client for the Midnight node's Substrate submission RPC
Documentation
//! Pure translation from Substrate tx-pool statuses to wallet-level events
//! and errors.
//!
//! The Substrate transaction pool reports ten discrete statuses (see
//! `polkadot-sdk/.../transaction-pool/api/src/lib.rs`). The TS node-client's
//! `#handleSubmissionResult` (`PolkadotNodeClient.ts:178-277`) collapses
//! those into three streamable events (`Submitted`/`InBlock`/`Finalized`)
//! and four terminal errors (`Usurped`/`Dropped`/`Invalid`/`FinalityTimeout`).
//!
//! This module encodes that collapse as a pure function so it can be tested
//! without a live node — the adapter layer only has to translate subxt's
//! native status type into [`TxStatus`] and call [`SubmissionOutcome::from_status`].

use crate::error::NodeClientError;
use crate::event::SubmissionEvent;

/// Runtime-agnostic mirror of a Substrate transaction-pool status.
///
/// Subxt (and Polkadot.js before it) exposes these as a tagged enum; we
/// accept them as simple Rust variants so the translation can be tested
/// without any Substrate dep.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TxStatus {
    /// The tx was validated and is sitting in the ready queue.
    Ready,
    /// The tx is awaiting a gap in its signer's nonce before it becomes ready.
    Future,
    /// The tx was broadcast to peers.
    Broadcast,
    /// The tx was previously included in a block that later got reverted;
    /// it's back in the pool waiting to be re-included.
    Retracted,
    /// The tx was included in a (non-final) block.
    InBlock {
        block_hash: String,
        block_height: u64,
    },
    /// The tx's including block reached finality.
    Finalized {
        block_hash: String,
        block_height: u64,
    },
    /// The tx did not finalize within the node's configured window.
    FinalityTimeout,
    /// The tx was replaced in the pool by another tx with matching
    /// discriminators (same sender+nonce).
    Usurped,
    /// The tx was evicted from the pool (pool full, congested network).
    Dropped,
    /// The node rejected the tx as invalid (bad signature, `ValidateUnsigned`
    /// returned `Err`, etc.).
    Invalid,
}

/// Result of translating a single [`TxStatus`] against a running submission.
///
/// - [`SubmissionOutcome::Emit`] produces a [`SubmissionEvent`] and the
///   stream should keep going (for `Ready`/`Future`/`Broadcast`/`Retracted`
///   and `InBlock`).
/// - [`SubmissionOutcome::EmitAndFinish`] emits a final event and the
///   stream should end (for `Finalized`).
/// - [`SubmissionOutcome::Fail`] produces a terminal error and the stream
///   ends (for `FinalityTimeout`/`Usurped`/`Dropped`/`Invalid`).
#[derive(Debug)]
pub enum SubmissionOutcome {
    Emit(SubmissionEvent),
    EmitAndFinish(SubmissionEvent),
    Fail(NodeClientError),
}

impl SubmissionOutcome {
    /// Translate a single Substrate status into either an event or a
    /// terminal error. Takes ownership of the status and copies of the tx
    /// bytes and tx hash so the resulting event can live past the status.
    ///
    /// # Behavior
    ///
    /// Mirrors `PolkadotNodeClient.ts:#handleSubmissionResult`. In particular:
    ///
    /// - `Retracted` emits `Submitted` (not an error) — the tx is back in
    ///   the pool and can still land. The TS code does the same.
    /// - `Finalized` emits `Finalized` *and* ends the stream
    ///   (`EmitAndFinish`) — subsequent statuses from the same subscription
    ///   are not delivered.
    pub fn from_status(status: TxStatus, tx: &[u8], tx_hash: &str) -> Self {
        match status {
            TxStatus::Ready | TxStatus::Future | TxStatus::Broadcast | TxStatus::Retracted => {
                Self::Emit(SubmissionEvent::Submitted {
                    tx: tx.to_vec(),
                    tx_hash: tx_hash.to_owned(),
                })
            }
            TxStatus::InBlock {
                block_hash,
                block_height,
            } => Self::Emit(SubmissionEvent::InBlock {
                tx: tx.to_vec(),
                block_hash,
                block_height,
                tx_hash: tx_hash.to_owned(),
            }),
            TxStatus::Finalized {
                block_hash,
                block_height,
            } => Self::EmitAndFinish(SubmissionEvent::Finalized {
                tx: tx.to_vec(),
                block_hash,
                block_height,
                tx_hash: tx_hash.to_owned(),
            }),
            TxStatus::FinalityTimeout => Self::Fail(NodeClientError::TransactionProgress {
                message: "transaction did not finalize within the expected window".to_owned(),
                tx_data: tx.to_vec(),
                desired_stage: crate::event::SubmissionStage::Finalized,
            }),
            TxStatus::Usurped => Self::Fail(NodeClientError::TransactionUsurped {
                tx_data: tx.to_vec(),
            }),
            TxStatus::Dropped => Self::Fail(NodeClientError::TransactionDropped {
                tx_data: tx.to_vec(),
            }),
            TxStatus::Invalid => Self::Fail(NodeClientError::TransactionInvalid {
                tx_data: tx.to_vec(),
                source: None,
            }),
        }
    }
}

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

    fn tx() -> Vec<u8> {
        vec![1, 2, 3, 4, 5]
    }

    fn assert_is_submitted(outcome: SubmissionOutcome) {
        match outcome {
            SubmissionOutcome::Emit(SubmissionEvent::Submitted { tx: e_tx, tx_hash }) => {
                assert_eq!(e_tx, tx());
                assert_eq!(tx_hash, "0xhash");
            }
            other => panic!("expected Emit(Submitted), got {other:?}"),
        }
    }

    #[test]
    fn ready_maps_to_submitted() {
        assert_is_submitted(SubmissionOutcome::from_status(
            TxStatus::Ready,
            &tx(),
            "0xhash",
        ));
    }

    #[test]
    fn future_maps_to_submitted() {
        assert_is_submitted(SubmissionOutcome::from_status(
            TxStatus::Future,
            &tx(),
            "0xhash",
        ));
    }

    #[test]
    fn broadcast_maps_to_submitted() {
        assert_is_submitted(SubmissionOutcome::from_status(
            TxStatus::Broadcast,
            &tx(),
            "0xhash",
        ));
    }

    #[test]
    fn retracted_maps_to_submitted_not_error() {
        // Load-bearing: a retracted tx can still be re-included; the TS
        // reference treats this as "Submitted" (back in flight), not as a
        // failure.
        assert_is_submitted(SubmissionOutcome::from_status(
            TxStatus::Retracted,
            &tx(),
            "0xhash",
        ));
    }

    #[test]
    fn in_block_carries_block_hash_and_height() {
        let outcome = SubmissionOutcome::from_status(
            TxStatus::InBlock {
                block_hash: "0xblk".into(),
                block_height: 99,
            },
            &tx(),
            "0xhash",
        );
        match outcome {
            SubmissionOutcome::Emit(SubmissionEvent::InBlock {
                block_hash,
                block_height,
                tx_hash,
                ..
            }) => {
                assert_eq!(block_hash, "0xblk");
                assert_eq!(block_height, 99);
                assert_eq!(tx_hash, "0xhash");
            }
            other => panic!("expected Emit(InBlock), got {other:?}"),
        }
    }

    #[test]
    fn finalized_emits_and_finishes_the_stream() {
        let outcome = SubmissionOutcome::from_status(
            TxStatus::Finalized {
                block_hash: "0xfin".into(),
                block_height: 100,
            },
            &tx(),
            "0xhash",
        );
        match outcome {
            SubmissionOutcome::EmitAndFinish(SubmissionEvent::Finalized {
                block_hash,
                block_height,
                ..
            }) => {
                assert_eq!(block_hash, "0xfin");
                assert_eq!(block_height, 100);
            }
            other => panic!("expected EmitAndFinish(Finalized), got {other:?}"),
        }
    }

    #[test]
    fn finality_timeout_fails_with_progress_error_at_finalized_stage() {
        let outcome = SubmissionOutcome::from_status(TxStatus::FinalityTimeout, &tx(), "0xhash");
        match outcome {
            SubmissionOutcome::Fail(NodeClientError::TransactionProgress {
                desired_stage,
                tx_data,
                ..
            }) => {
                assert_eq!(desired_stage, SubmissionStage::Finalized);
                assert_eq!(tx_data, tx());
            }
            other => panic!("expected Fail(TransactionProgress), got {other:?}"),
        }
    }

    #[test]
    fn usurped_fails_with_usurped_error() {
        let outcome = SubmissionOutcome::from_status(TxStatus::Usurped, &tx(), "0xhash");
        match outcome {
            SubmissionOutcome::Fail(NodeClientError::TransactionUsurped { tx_data }) => {
                assert_eq!(tx_data, tx());
            }
            other => panic!("expected Fail(TransactionUsurped), got {other:?}"),
        }
    }

    #[test]
    fn dropped_fails_with_dropped_error() {
        let outcome = SubmissionOutcome::from_status(TxStatus::Dropped, &tx(), "0xhash");
        assert!(matches!(
            outcome,
            SubmissionOutcome::Fail(NodeClientError::TransactionDropped { .. })
        ));
    }

    #[test]
    fn invalid_fails_with_invalid_error() {
        let outcome = SubmissionOutcome::from_status(TxStatus::Invalid, &tx(), "0xhash");
        assert!(matches!(
            outcome,
            SubmissionOutcome::Fail(NodeClientError::TransactionInvalid { .. })
        ));
    }
}