moonproof-node-client 0.2.1

Rust client for the Midnight node's Substrate submission RPC
Documentation
//! Submission events emitted while a transaction progresses through the node.
//!
//! The TS reference (`SubmissionEvent.ts`) collapses the Substrate tx-pool
//! status stream into three observable events: [`SubmissionEvent::Submitted`]
//! (for `Ready`/`Future`/`Broadcast`/`Retracted`), [`SubmissionEvent::InBlock`],
//! and [`SubmissionEvent::Finalized`]. Terminal-error statuses
//! (`FinalityTimeout`/`Usurped`/`Dropped`/`Invalid`) do not appear here — they
//! are surfaced as [`crate::NodeClientError`] variants instead.

/// Hex string with `0x` prefix, matching the TS `HexString` alias. Used for
/// transaction and block hashes on the wire and in event payloads.
pub type HexString = String;

/// Event stream item emitted while a submitted transaction progresses through
/// the node's tx pool.
///
/// Each variant carries the original transaction bytes for correlation —
/// matches the TS `SubmissionEvent` which attaches `tx` to every case.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SubmissionEvent {
    /// Node accepted the extrinsic into its pool. Covers Substrate's
    /// `Ready`, `Future`, `Broadcast`, and `Retracted` statuses — from the
    /// wallet's point of view, the transaction is in flight but not yet
    /// included in a block. A `Retracted` can reappear as a later `InBlock`
    /// once the replacement block is imported.
    Submitted { tx: Vec<u8>, tx_hash: HexString },

    /// The transaction was included in a block. Not yet finalized — the chain
    /// could still re-org. Wallets that need strong finality should wait for
    /// [`SubmissionEvent::Finalized`].
    InBlock {
        tx: Vec<u8>,
        block_hash: HexString,
        block_height: u64,
        tx_hash: HexString,
    },

    /// The transaction's including block reached GRANDPA finality. Terminal
    /// success — stream completes after this.
    Finalized {
        tx: Vec<u8>,
        block_hash: HexString,
        block_height: u64,
        tx_hash: HexString,
    },
}

impl SubmissionEvent {
    /// Identify which [`SubmissionStage`] this event corresponds to. Useful
    /// for the `send_and_wait_for` pattern where callers pick the stage they
    /// want to block on.
    #[must_use]
    pub fn stage(&self) -> SubmissionStage {
        match self {
            Self::Submitted { .. } => SubmissionStage::Submitted,
            Self::InBlock { .. } => SubmissionStage::InBlock,
            Self::Finalized { .. } => SubmissionStage::Finalized,
        }
    }

    /// Shared transaction hash. Present on every variant.
    #[must_use]
    pub fn tx_hash(&self) -> &str {
        match self {
            Self::Submitted { tx_hash, .. }
            | Self::InBlock { tx_hash, .. }
            | Self::Finalized { tx_hash, .. } => tx_hash,
        }
    }

    /// Underlying transaction bytes. Present on every variant.
    #[must_use]
    pub fn tx_bytes(&self) -> &[u8] {
        match self {
            Self::Submitted { tx, .. } | Self::InBlock { tx, .. } | Self::Finalized { tx, .. } => {
                tx
            }
        }
    }

    /// Block hash and height — `Some` only for [`SubmissionEvent::InBlock`]
    /// and [`SubmissionEvent::Finalized`]. `None` for [`SubmissionEvent::Submitted`].
    #[must_use]
    pub fn block(&self) -> Option<(&str, u64)> {
        match self {
            Self::Submitted { .. } => None,
            Self::InBlock {
                block_hash,
                block_height,
                ..
            }
            | Self::Finalized {
                block_hash,
                block_height,
                ..
            } => Some((block_hash, *block_height)),
        }
    }
}

/// Coarse-grained stage label — ordered (`Submitted < InBlock < Finalized`)
/// so callers can say "wait for at least `InBlock`" semantically.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SubmissionStage {
    Submitted,
    InBlock,
    Finalized,
}

impl SubmissionStage {
    /// Stable short name matching the TS `_tag` field: `"Submitted"`,
    /// `"InBlock"`, `"Finalized"`. Used in error messages so logs read the
    /// same across runtimes.
    #[must_use]
    pub fn as_tag(&self) -> &'static str {
        match self {
            Self::Submitted => "Submitted",
            Self::InBlock => "InBlock",
            Self::Finalized => "Finalized",
        }
    }
}

impl std::fmt::Display for SubmissionStage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_tag())
    }
}

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

    fn sample_tx() -> Vec<u8> {
        vec![0xde, 0xad, 0xbe, 0xef]
    }

    #[test]
    fn submitted_event_exposes_tag_hash_and_bytes() {
        let event = SubmissionEvent::Submitted {
            tx: sample_tx(),
            tx_hash: "0xabc".into(),
        };
        assert_eq!(event.stage(), SubmissionStage::Submitted);
        assert_eq!(event.tx_hash(), "0xabc");
        assert_eq!(event.tx_bytes(), sample_tx().as_slice());
        assert_eq!(event.block(), None);
    }

    #[test]
    fn in_block_event_exposes_block_height_and_hash() {
        let event = SubmissionEvent::InBlock {
            tx: sample_tx(),
            block_hash: "0xblk".into(),
            block_height: 7,
            tx_hash: "0xabc".into(),
        };
        assert_eq!(event.stage(), SubmissionStage::InBlock);
        assert_eq!(event.block(), Some(("0xblk", 7)));
    }

    #[test]
    fn finalized_event_exposes_block_height_and_hash() {
        let event = SubmissionEvent::Finalized {
            tx: sample_tx(),
            block_hash: "0xfin".into(),
            block_height: 8,
            tx_hash: "0xabc".into(),
        };
        assert_eq!(event.stage(), SubmissionStage::Finalized);
        assert_eq!(event.block(), Some(("0xfin", 8)));
    }

    #[test]
    fn submission_stage_ordering_matches_tx_lifecycle() {
        assert!(SubmissionStage::Submitted < SubmissionStage::InBlock);
        assert!(SubmissionStage::InBlock < SubmissionStage::Finalized);
    }

    #[test]
    fn submission_stage_tags_are_stable_strings() {
        assert_eq!(SubmissionStage::Submitted.as_tag(), "Submitted");
        assert_eq!(SubmissionStage::InBlock.as_tag(), "InBlock");
        assert_eq!(SubmissionStage::Finalized.as_tag(), "Finalized");
        assert_eq!(format!("{}", SubmissionStage::Finalized), "Finalized");
    }
}