moonproof-node-client 0.2.1

Rust client for the Midnight node's Substrate submission RPC
Documentation
//! `PolkadotNodeClient` — subxt-backed implementation of [`NodeClient`].
//!
//! Wraps [`subxt::OnlineClient<SubstrateConfig>`] and speaks the Substrate
//! submission RPC. Constructs an **unsigned** extrinsic for
//! `midnight.send_mn_transaction(Vec<u8>)` and translates subxt's
//! [`subxt::tx::TransactionStatus`] stream into our wallet-level
//! [`crate::SubmissionEvent`] / [`crate::NodeClientError`] types via
//! [`crate::status::SubmissionOutcome::from_status`].
//!
//! ## Transport
//!
//! `ws://127.0.0.1:9944` in the local dev harness. `wss://...` for TLS. The
//! client uses [`subxt::OnlineClient::from_insecure_url`] for `ws://` and
//! `http://` URLs (subxt rejects non-TLS URLs via its default entry point);
//! this is correct behavior for localhost integration tests.
//!
//! ## Block-height attribution
//!
//! subxt's `TransactionStatus::InBestBlock` / `InFinalizedBlock` variants
//! carry a block hash but not a number. We resolve the number with an extra
//! `at_block(hash)` call per event — one round trip per block-level status.
//! The alternative (leaving height as `Option`) would make the
//! [`crate::SubmissionEvent`] shape lossy; correctness wins.

use futures::stream::{BoxStream, StreamExt, TryStreamExt};
use moonproof_macros::async_trait;
use subxt::config::substrate::H256;
use subxt::{OnlineClient, SubstrateConfig};

use crate::client::{Genesis, NodeClient, SerializedTransaction};
use crate::config::Config;
use crate::error::NodeClientError;
use crate::event::SubmissionEvent;
use crate::status::{SubmissionOutcome, TxStatus};

/// Pallet name for Midnight's transaction-submission pallet. `PascalCase`,
/// matching Substrate metadata conventions (`pallet_midnight` → `"Midnight"`).
const MIDNIGHT_PALLET: &str = "Midnight";

/// Call name inside [`MIDNIGHT_PALLET`]. Substrate's `#[pallet::call]` macro
/// uses the `snake_case` fn name directly — confirmed against the TS
/// `api.tx.midnight.sendMnTransaction` dispatch (Polkadot.js camel-cases
/// `send_mn_transaction` for JS ergonomics).
const SEND_MN_TRANSACTION: &str = "send_mn_transaction";

/// subxt-backed Midnight node client.
///
/// Construct with [`PolkadotNodeClient::connect`] (async — fetches runtime
/// metadata). Each call to [`PolkadotNodeClient::send_midnight_transaction`]
/// reuses the held [`OnlineClient`] — subxt keeps the WebSocket open across
/// submissions.
pub struct PolkadotNodeClient {
    config: Config,
    api: OnlineClient<SubstrateConfig>,
}

impl PolkadotNodeClient {
    /// Connect to the node and fetch runtime metadata.
    ///
    /// Fails with [`NodeClientError::Connection`] if the node is unreachable
    /// or the metadata download fails.
    pub async fn connect(config: Config) -> Result<Self, NodeClientError> {
        let url = config.node_url.to_string();
        let api = OnlineClient::<SubstrateConfig>::from_insecure_url(&url)
            .await
            .map_err(|e| NodeClientError::Connection {
                message: format!("failed to connect to {url}: {e}"),
                source: Some(Box::new(e)),
            })?;
        Ok(Self { config, api })
    }

    /// Access the wrapped subxt client — escape hatch for advanced callers
    /// who need to issue custom queries against the same connection.
    #[must_use]
    pub fn api(&self) -> &OnlineClient<SubstrateConfig> {
        &self.api
    }

    /// The config this client was built with.
    #[must_use]
    pub fn config(&self) -> &Config {
        &self.config
    }
}

fn format_hash(hash: H256) -> String {
    format!("0x{}", hex::encode(hash.as_bytes()))
}

async fn resolve_block_height(
    api: &OnlineClient<SubstrateConfig>,
    block_hash: H256,
) -> Result<u64, NodeClientError> {
    let at_block = api
        .at_block(block_hash)
        .await
        .map_err(|e| NodeClientError::Parse {
            message: format!(
                "failed to fetch header for block {}: {e}",
                format_hash(block_hash)
            ),
            source: Some(Box::new(e)),
        })?;
    Ok(at_block.block_number())
}

/// Translate a single subxt [`subxt::tx::TransactionStatus`] into a wallet
/// [`SubmissionEvent`] (or error). Does one extra RPC per `InBlock` /
/// `InFinalizedBlock` to resolve the block height.
async fn translate_status(
    status: subxt::tx::TransactionStatus<
        SubstrateConfig,
        subxt::client::OnlineClientAtBlockImpl<SubstrateConfig>,
    >,
    api: &OnlineClient<SubstrateConfig>,
    tx: &[u8],
    tx_hash: &str,
) -> Result<SubmissionOutcome, NodeClientError> {
    use subxt::tx::TransactionStatus as S;
    let outcome = match status {
        // All "in flight, not yet in a block" statuses collapse to Submitted.
        // subxt doesn't surface Polkadot's `Future` (rolled into `Validated`)
        // or `Retracted` explicitly; its `NoLongerInBestBlock` plays that role.
        S::Validated | S::Broadcasted | S::NoLongerInBestBlock => {
            SubmissionOutcome::from_status(TxStatus::Ready, tx, tx_hash)
        }
        S::InBestBlock(info) => {
            let block_hash = info.block_hash();
            let block_height = resolve_block_height(api, block_hash).await?;
            SubmissionOutcome::from_status(
                TxStatus::InBlock {
                    block_hash: format_hash(block_hash),
                    block_height,
                },
                tx,
                tx_hash,
            )
        }
        S::InFinalizedBlock(info) => {
            let block_hash = info.block_hash();
            let block_height = resolve_block_height(api, block_hash).await?;
            SubmissionOutcome::from_status(
                TxStatus::Finalized {
                    block_hash: format_hash(block_hash),
                    block_height,
                },
                tx,
                tx_hash,
            )
        }
        S::Error { message } => SubmissionOutcome::Fail(NodeClientError::Submission {
            message: format!("node reported transaction error: {message}"),
            tx_data: tx.to_vec(),
            source: None,
        }),
        S::Invalid { message } => SubmissionOutcome::Fail(NodeClientError::TransactionInvalid {
            tx_data: tx.to_vec(),
            source: Some(message.into()),
        }),
        // subxt 0.50 folds Polkadot's Usurped into Dropped. The `message`
        // argument carries the underlying status string when that detail
        // matters (e.g., "tx was usurped").
        S::Dropped { message: _ } => SubmissionOutcome::Fail(NodeClientError::TransactionDropped {
            tx_data: tx.to_vec(),
        }),
    };
    Ok(outcome)
}

#[async_trait]
impl NodeClient for PolkadotNodeClient {
    fn genesis_hash_hex(&self) -> Option<String> {
        Some(format_hash(self.api.genesis_hash()))
    }

    async fn send_midnight_transaction(
        &self,
        tx: SerializedTransaction,
    ) -> Result<BoxStream<'static, Result<SubmissionEvent, NodeClientError>>, NodeClientError> {
        // Build the unsigned extrinsic: `pallet Midnight :: send_mn_transaction(tx: Vec<u8>)`.
        // We go through subxt's dynamic API so we don't have to statically
        // codegen Midnight's runtime — the pallet and call names are resolved
        // against live metadata at tx-creation time.
        let payload = subxt::dynamic::tx(
            MIDNIGHT_PALLET,
            SEND_MN_TRANSACTION,
            vec![subxt::dynamic::Value::from_bytes(tx.clone())],
        );

        let txs = self
            .api
            .tx()
            .await
            .map_err(|e| NodeClientError::Connection {
                message: format!("failed to fetch transactions client: {e}"),
                source: Some(Box::new(e)),
            })?;

        let submittable = txs.create_unsigned(&payload).map_err(|e| {
            NodeClientError::Submission {
                message: format!(
                    "failed to build unsigned extrinsic for {MIDNIGHT_PALLET}.{SEND_MN_TRANSACTION}: {e}"
                ),
                tx_data: tx.clone(),
                source: Some(Box::new(e)),
            }
        })?;

        let progress =
            submittable
                .submit_and_watch()
                .await
                .map_err(|e| NodeClientError::Submission {
                    message: format!("submit_and_watch rejected the extrinsic: {e}"),
                    tx_data: tx.clone(),
                    source: Some(Box::new(e)),
                })?;

        let tx_hash = format_hash(progress.extrinsic_hash());
        let api = self.api.clone();
        // Two owned clones: one for map_err (closure invoked per error), one
        // for and_then (closure invoked per status). Both closures have
        // `move` semantics and get called repeatedly, so they each clone
        // internally on every call.
        let tx_for_err = tx.clone();
        let tx_for_ok = tx;

        // Map each subxt status into our event/error. `EmitAndFinish` is
        // flattened into `Emit` — subxt's `TransactionProgress` stream
        // already terminates after `InFinalizedBlock` so we don't need to
        // manually stop.
        let mapped = progress
            .map_err(move |e| NodeClientError::Submission {
                message: format!("transaction progress error: {e}"),
                tx_data: tx_for_err.clone(),
                source: Some(Box::new(e)),
            })
            .and_then(move |status| {
                let api = api.clone();
                let tx_bytes = tx_for_ok.clone();
                let tx_hash = tx_hash.clone();
                async move {
                    let outcome = translate_status(status, &api, &tx_bytes, &tx_hash).await?;
                    match outcome {
                        SubmissionOutcome::Emit(ev) | SubmissionOutcome::EmitAndFinish(ev) => {
                            Ok(ev)
                        }
                        SubmissionOutcome::Fail(e) => Err(e),
                    }
                }
            });

        Ok(mapped.boxed())
    }

    async fn get_genesis(&self) -> Result<Genesis, NodeClientError> {
        let genesis_hash = self.api.genesis_hash();
        let at_block =
            self.api
                .at_block(genesis_hash)
                .await
                .map_err(|e| NodeClientError::Connection {
                    message: format!(
                        "failed to load genesis block {}: {e}",
                        format_hash(genesis_hash)
                    ),
                    source: Some(Box::new(e)),
                })?;

        let extrinsics =
            at_block
                .extrinsics()
                .fetch()
                .await
                .map_err(|e| NodeClientError::Connection {
                    message: format!("failed to fetch genesis extrinsics: {e}"),
                    source: Some(Box::new(e)),
                })?;

        let mut transactions: Vec<SerializedTransaction> = Vec::new();
        for item in extrinsics.iter() {
            let ext = item.map_err(|e| NodeClientError::Parse {
                message: format!("failed to decode genesis extrinsic: {e}"),
                source: Some(Box::new(e)),
            })?;

            // Skip anything that isn't our pallet/call — the genesis block
            // may include system-level extrinsics (timestamp, parachain
            // inherent, etc.) whose field decoders would be wrong for
            // `Vec<u8>`.
            if ext.pallet_name() != MIDNIGHT_PALLET || ext.call_name() != SEND_MN_TRANSACTION {
                tracing::debug!(
                    target: "moonproof::node-client",
                    "skipping genesis extrinsic #{}: {}.{}",
                    ext.index(),
                    ext.pallet_name(),
                    ext.call_name(),
                );
                continue;
            }

            // `send_mn_transaction(tx: Vec<u8>)` — one field. Decode as a
            // one-tuple via subxt's *fields* API, NOT the outer-Call API.
            // `decode_call_data_as::<Vec<u8>>` tries to SCALE-decode the
            // args as the entire root Call enum, which fails with
            // "Unexpected variant" because `Vec<u8>` isn't the enum shape.
            // `decode_call_data_fields_unchecked_as::<(Vec<u8>,)>` decodes
            // just the fields against the metadata-typed field list.
            let (tx_bytes,): (Vec<u8>,) = ext
                .decode_call_data_fields_unchecked_as()
                .map_err(|e| NodeClientError::Parse {
                    message: format!(
                        "failed to decode {MIDNIGHT_PALLET}.{SEND_MN_TRANSACTION} args as (Vec<u8>,): {e}"
                    ),
                    source: Some(Box::new(e)),
                })?;
            transactions.push(tx_bytes);
        }

        Ok(Genesis { transactions })
    }
}

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

    #[test]
    fn format_hash_renders_canonical_hex_with_prefix() {
        let bytes = [0xabu8; 32];
        let hash = H256::from(bytes);
        let rendered = format_hash(hash);
        assert!(rendered.starts_with("0x"));
        assert_eq!(rendered.len(), 2 + 64);
        assert!(rendered.chars().skip(2).all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn midnight_pallet_constants_match_ts_dispatch_names() {
        // Load-bearing: these constants are how subxt looks up the call in
        // live runtime metadata. The TS dispatch `api.tx.midnight.sendMnTransaction`
        // camel-cases these for JS ergonomics — in the metadata they are
        // PascalCase pallet + snake_case call. If midnight-node ever renames
        // the pallet or call, THIS test fails first (metadata lookup would
        // succeed silently and submit to the wrong dispatch).
        assert_eq!(MIDNIGHT_PALLET, "Midnight");
        assert_eq!(SEND_MN_TRANSACTION, "send_mn_transaction");
    }
}