Skip to main content

moonproof_node_client/
polkadot.rs

1//! `PolkadotNodeClient` — subxt-backed implementation of [`NodeClient`].
2//!
3//! Wraps [`subxt::OnlineClient<SubstrateConfig>`] and speaks the Substrate
4//! submission RPC. Constructs an **unsigned** extrinsic for
5//! `midnight.send_mn_transaction(Vec<u8>)` and translates subxt's
6//! [`subxt::tx::TransactionStatus`] stream into our wallet-level
7//! [`crate::SubmissionEvent`] / [`crate::NodeClientError`] types via
8//! [`crate::status::SubmissionOutcome::from_status`].
9//!
10//! ## Transport
11//!
12//! `ws://127.0.0.1:9944` in the local dev harness. `wss://...` for TLS. The
13//! client uses [`subxt::OnlineClient::from_insecure_url`] for `ws://` and
14//! `http://` URLs (subxt rejects non-TLS URLs via its default entry point);
15//! this is correct behavior for localhost integration tests.
16//!
17//! ## Block-height attribution
18//!
19//! subxt's `TransactionStatus::InBestBlock` / `InFinalizedBlock` variants
20//! carry a block hash but not a number. We resolve the number with an extra
21//! `at_block(hash)` call per event — one round trip per block-level status.
22//! The alternative (leaving height as `Option`) would make the
23//! [`crate::SubmissionEvent`] shape lossy; correctness wins.
24
25use futures::stream::{BoxStream, StreamExt, TryStreamExt};
26use moonproof_macros::async_trait;
27use subxt::config::substrate::H256;
28use subxt::{OnlineClient, SubstrateConfig};
29
30use crate::client::{Genesis, NodeClient, SerializedTransaction};
31use crate::config::Config;
32use crate::error::NodeClientError;
33use crate::event::SubmissionEvent;
34use crate::status::{SubmissionOutcome, TxStatus};
35
36/// Pallet name for Midnight's transaction-submission pallet. `PascalCase`,
37/// matching Substrate metadata conventions (`pallet_midnight` → `"Midnight"`).
38const MIDNIGHT_PALLET: &str = "Midnight";
39
40/// Call name inside [`MIDNIGHT_PALLET`]. Substrate's `#[pallet::call]` macro
41/// uses the `snake_case` fn name directly — confirmed against the TS
42/// `api.tx.midnight.sendMnTransaction` dispatch (Polkadot.js camel-cases
43/// `send_mn_transaction` for JS ergonomics).
44const SEND_MN_TRANSACTION: &str = "send_mn_transaction";
45
46/// subxt-backed Midnight node client.
47///
48/// Construct with [`PolkadotNodeClient::connect`] (async — fetches runtime
49/// metadata). Each call to [`PolkadotNodeClient::send_midnight_transaction`]
50/// reuses the held [`OnlineClient`] — subxt keeps the WebSocket open across
51/// submissions.
52pub struct PolkadotNodeClient {
53    config: Config,
54    api: OnlineClient<SubstrateConfig>,
55}
56
57impl PolkadotNodeClient {
58    /// Connect to the node and fetch runtime metadata.
59    ///
60    /// Fails with [`NodeClientError::Connection`] if the node is unreachable
61    /// or the metadata download fails.
62    pub async fn connect(config: Config) -> Result<Self, NodeClientError> {
63        let url = config.node_url.to_string();
64        let api = OnlineClient::<SubstrateConfig>::from_insecure_url(&url)
65            .await
66            .map_err(|e| NodeClientError::Connection {
67                message: format!("failed to connect to {url}: {e}"),
68                source: Some(Box::new(e)),
69            })?;
70        Ok(Self { config, api })
71    }
72
73    /// Access the wrapped subxt client — escape hatch for advanced callers
74    /// who need to issue custom queries against the same connection.
75    #[must_use]
76    pub fn api(&self) -> &OnlineClient<SubstrateConfig> {
77        &self.api
78    }
79
80    /// The config this client was built with.
81    #[must_use]
82    pub fn config(&self) -> &Config {
83        &self.config
84    }
85}
86
87fn format_hash(hash: H256) -> String {
88    format!("0x{}", hex::encode(hash.as_bytes()))
89}
90
91async fn resolve_block_height(
92    api: &OnlineClient<SubstrateConfig>,
93    block_hash: H256,
94) -> Result<u64, NodeClientError> {
95    let at_block = api
96        .at_block(block_hash)
97        .await
98        .map_err(|e| NodeClientError::Parse {
99            message: format!(
100                "failed to fetch header for block {}: {e}",
101                format_hash(block_hash)
102            ),
103            source: Some(Box::new(e)),
104        })?;
105    Ok(at_block.block_number())
106}
107
108/// Translate a single subxt [`subxt::tx::TransactionStatus`] into a wallet
109/// [`SubmissionEvent`] (or error). Does one extra RPC per `InBlock` /
110/// `InFinalizedBlock` to resolve the block height.
111async fn translate_status(
112    status: subxt::tx::TransactionStatus<
113        SubstrateConfig,
114        subxt::client::OnlineClientAtBlockImpl<SubstrateConfig>,
115    >,
116    api: &OnlineClient<SubstrateConfig>,
117    tx: &[u8],
118    tx_hash: &str,
119) -> Result<SubmissionOutcome, NodeClientError> {
120    use subxt::tx::TransactionStatus as S;
121    let outcome = match status {
122        // All "in flight, not yet in a block" statuses collapse to Submitted.
123        // subxt doesn't surface Polkadot's `Future` (rolled into `Validated`)
124        // or `Retracted` explicitly; its `NoLongerInBestBlock` plays that role.
125        S::Validated | S::Broadcasted | S::NoLongerInBestBlock => {
126            SubmissionOutcome::from_status(TxStatus::Ready, tx, tx_hash)
127        }
128        S::InBestBlock(info) => {
129            let block_hash = info.block_hash();
130            let block_height = resolve_block_height(api, block_hash).await?;
131            SubmissionOutcome::from_status(
132                TxStatus::InBlock {
133                    block_hash: format_hash(block_hash),
134                    block_height,
135                },
136                tx,
137                tx_hash,
138            )
139        }
140        S::InFinalizedBlock(info) => {
141            let block_hash = info.block_hash();
142            let block_height = resolve_block_height(api, block_hash).await?;
143            SubmissionOutcome::from_status(
144                TxStatus::Finalized {
145                    block_hash: format_hash(block_hash),
146                    block_height,
147                },
148                tx,
149                tx_hash,
150            )
151        }
152        S::Error { message } => SubmissionOutcome::Fail(NodeClientError::Submission {
153            message: format!("node reported transaction error: {message}"),
154            tx_data: tx.to_vec(),
155            source: None,
156        }),
157        S::Invalid { message } => SubmissionOutcome::Fail(NodeClientError::TransactionInvalid {
158            tx_data: tx.to_vec(),
159            source: Some(message.into()),
160        }),
161        // subxt 0.50 folds Polkadot's Usurped into Dropped. The `message`
162        // argument carries the underlying status string when that detail
163        // matters (e.g., "tx was usurped").
164        S::Dropped { message: _ } => SubmissionOutcome::Fail(NodeClientError::TransactionDropped {
165            tx_data: tx.to_vec(),
166        }),
167    };
168    Ok(outcome)
169}
170
171#[async_trait]
172impl NodeClient for PolkadotNodeClient {
173    fn genesis_hash_hex(&self) -> Option<String> {
174        Some(format_hash(self.api.genesis_hash()))
175    }
176
177    async fn send_midnight_transaction(
178        &self,
179        tx: SerializedTransaction,
180    ) -> Result<BoxStream<'static, Result<SubmissionEvent, NodeClientError>>, NodeClientError> {
181        // Build the unsigned extrinsic: `pallet Midnight :: send_mn_transaction(tx: Vec<u8>)`.
182        // We go through subxt's dynamic API so we don't have to statically
183        // codegen Midnight's runtime — the pallet and call names are resolved
184        // against live metadata at tx-creation time.
185        let payload = subxt::dynamic::tx(
186            MIDNIGHT_PALLET,
187            SEND_MN_TRANSACTION,
188            vec![subxt::dynamic::Value::from_bytes(tx.clone())],
189        );
190
191        let txs = self
192            .api
193            .tx()
194            .await
195            .map_err(|e| NodeClientError::Connection {
196                message: format!("failed to fetch transactions client: {e}"),
197                source: Some(Box::new(e)),
198            })?;
199
200        let submittable = txs.create_unsigned(&payload).map_err(|e| {
201            NodeClientError::Submission {
202                message: format!(
203                    "failed to build unsigned extrinsic for {MIDNIGHT_PALLET}.{SEND_MN_TRANSACTION}: {e}"
204                ),
205                tx_data: tx.clone(),
206                source: Some(Box::new(e)),
207            }
208        })?;
209
210        let progress =
211            submittable
212                .submit_and_watch()
213                .await
214                .map_err(|e| NodeClientError::Submission {
215                    message: format!("submit_and_watch rejected the extrinsic: {e}"),
216                    tx_data: tx.clone(),
217                    source: Some(Box::new(e)),
218                })?;
219
220        let tx_hash = format_hash(progress.extrinsic_hash());
221        let api = self.api.clone();
222        // Two owned clones: one for map_err (closure invoked per error), one
223        // for and_then (closure invoked per status). Both closures have
224        // `move` semantics and get called repeatedly, so they each clone
225        // internally on every call.
226        let tx_for_err = tx.clone();
227        let tx_for_ok = tx;
228
229        // Map each subxt status into our event/error. `EmitAndFinish` is
230        // flattened into `Emit` — subxt's `TransactionProgress` stream
231        // already terminates after `InFinalizedBlock` so we don't need to
232        // manually stop.
233        let mapped = progress
234            .map_err(move |e| NodeClientError::Submission {
235                message: format!("transaction progress error: {e}"),
236                tx_data: tx_for_err.clone(),
237                source: Some(Box::new(e)),
238            })
239            .and_then(move |status| {
240                let api = api.clone();
241                let tx_bytes = tx_for_ok.clone();
242                let tx_hash = tx_hash.clone();
243                async move {
244                    let outcome = translate_status(status, &api, &tx_bytes, &tx_hash).await?;
245                    match outcome {
246                        SubmissionOutcome::Emit(ev) | SubmissionOutcome::EmitAndFinish(ev) => {
247                            Ok(ev)
248                        }
249                        SubmissionOutcome::Fail(e) => Err(e),
250                    }
251                }
252            });
253
254        Ok(mapped.boxed())
255    }
256
257    async fn get_genesis(&self) -> Result<Genesis, NodeClientError> {
258        let genesis_hash = self.api.genesis_hash();
259        let at_block =
260            self.api
261                .at_block(genesis_hash)
262                .await
263                .map_err(|e| NodeClientError::Connection {
264                    message: format!(
265                        "failed to load genesis block {}: {e}",
266                        format_hash(genesis_hash)
267                    ),
268                    source: Some(Box::new(e)),
269                })?;
270
271        let extrinsics =
272            at_block
273                .extrinsics()
274                .fetch()
275                .await
276                .map_err(|e| NodeClientError::Connection {
277                    message: format!("failed to fetch genesis extrinsics: {e}"),
278                    source: Some(Box::new(e)),
279                })?;
280
281        let mut transactions: Vec<SerializedTransaction> = Vec::new();
282        for item in extrinsics.iter() {
283            let ext = item.map_err(|e| NodeClientError::Parse {
284                message: format!("failed to decode genesis extrinsic: {e}"),
285                source: Some(Box::new(e)),
286            })?;
287
288            // Skip anything that isn't our pallet/call — the genesis block
289            // may include system-level extrinsics (timestamp, parachain
290            // inherent, etc.) whose field decoders would be wrong for
291            // `Vec<u8>`.
292            if ext.pallet_name() != MIDNIGHT_PALLET || ext.call_name() != SEND_MN_TRANSACTION {
293                tracing::debug!(
294                    target: "moonproof::node-client",
295                    "skipping genesis extrinsic #{}: {}.{}",
296                    ext.index(),
297                    ext.pallet_name(),
298                    ext.call_name(),
299                );
300                continue;
301            }
302
303            // `send_mn_transaction(tx: Vec<u8>)` — one field. Decode as a
304            // one-tuple via subxt's *fields* API, NOT the outer-Call API.
305            // `decode_call_data_as::<Vec<u8>>` tries to SCALE-decode the
306            // args as the entire root Call enum, which fails with
307            // "Unexpected variant" because `Vec<u8>` isn't the enum shape.
308            // `decode_call_data_fields_unchecked_as::<(Vec<u8>,)>` decodes
309            // just the fields against the metadata-typed field list.
310            let (tx_bytes,): (Vec<u8>,) = ext
311                .decode_call_data_fields_unchecked_as()
312                .map_err(|e| NodeClientError::Parse {
313                    message: format!(
314                        "failed to decode {MIDNIGHT_PALLET}.{SEND_MN_TRANSACTION} args as (Vec<u8>,): {e}"
315                    ),
316                    source: Some(Box::new(e)),
317                })?;
318            transactions.push(tx_bytes);
319        }
320
321        Ok(Genesis { transactions })
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    #[test]
330    fn format_hash_renders_canonical_hex_with_prefix() {
331        let bytes = [0xabu8; 32];
332        let hash = H256::from(bytes);
333        let rendered = format_hash(hash);
334        assert!(rendered.starts_with("0x"));
335        assert_eq!(rendered.len(), 2 + 64);
336        assert!(rendered.chars().skip(2).all(|c| c.is_ascii_hexdigit()));
337    }
338
339    #[test]
340    fn midnight_pallet_constants_match_ts_dispatch_names() {
341        // Load-bearing: these constants are how subxt looks up the call in
342        // live runtime metadata. The TS dispatch `api.tx.midnight.sendMnTransaction`
343        // camel-cases these for JS ergonomics — in the metadata they are
344        // PascalCase pallet + snake_case call. If midnight-node ever renames
345        // the pallet or call, THIS test fails first (metadata lookup would
346        // succeed silently and submit to the wrong dispatch).
347        assert_eq!(MIDNIGHT_PALLET, "Midnight");
348        assert_eq!(SEND_MN_TRANSACTION, "send_mn_transaction");
349    }
350}