Skip to main content

moonproof_contracts/
submit_tx.rs

1//! Port of `@midnight-ntwrk/midnight-js-contracts/src/submit-tx.ts`.
2//!
3//! The three-step submission pipeline every contract transaction
4//! (deploy, call, maintenance) runs through:
5//!
6//! 1. **Prove** — hand the unproven tx bytes to
7//!    [`ProofProvider::prove_tx`]; it runs the ZK prover on every
8//!    contract-call / zswap proof inside the transaction and returns
9//!    tagged-serialized bytes of the post-prove shape
10//!    (`Transaction<Signature, ProofMarker, PedersenRandomness, _>`).
11//! 2. **Balance** — hand the proven bytes to
12//!    [`WalletProvider::balance_tx`]; it adds dust coins to cover the
13//!    fee and seals the binding commitment, returning the finalized
14//!    wire bytes the node accepts.
15//! 3. **Submit** — hand the finalized bytes to
16//!    [`MidnightProvider::submit_tx`]; it submits to the node via
17//!    `pallet_midnight.send_mn_transaction` and returns the chain-
18//!    assigned transaction id.
19//!
20//! After submission, [`submit_tx`] waits for the transaction to
21//! finalize on-chain via
22//! [`PublicDataProvider::watch_for_tx_data`] and returns the full
23//! [`FinalizedTxData`]. [`submit_tx_async`] skips the wait and
24//! returns immediately with the transaction id — callers that need
25//! finalization subscribe to `watch_for_tx_data` themselves.
26
27use crate::error::Result;
28use crate::providers::{
29    HasLogger, HasMidnight, HasProof, HasPublicData, HasWallet, LoggerProvider, MidnightProvider,
30    ProofProvider, ProveTxConfig, PublicDataProvider, WalletProvider,
31};
32use crate::tx_phase::UnprovenTx;
33use crate::types::{CircuitId, FinalizedTxData, TransactionId};
34
35/// Options for [`submit_tx`] / [`submit_tx_async`]. Port of TS
36/// `SubmitTxOptions`.
37#[derive(Debug, Clone)]
38pub struct SubmitTxOptions {
39    /// The pre-prove transaction the proof provider consumes.
40    pub unproven_tx: UnprovenTx,
41    /// The circuit id(s) this submission covers. `None` for deploys,
42    /// `Some([id])` for a single-call tx, `Some([id1, id2, ...])`
43    /// for scoped-transaction batches. Preserved for diagnostics
44    /// (the TS variant uses it for failure-logging + scope
45    /// identification).
46    pub circuit_ids: Option<Vec<CircuitId>>,
47    /// Proof-request configuration (timeout etc.) threaded to the
48    /// proof provider.
49    pub prove_config: ProveTxConfig,
50    /// Optional transaction TTL in milliseconds. Threaded to
51    /// [`WalletProvider::balance_tx`]. `None` uses the wallet
52    /// provider's default (typically "chain-now + 1h").
53    pub ttl_ms: Option<i64>,
54}
55
56impl SubmitTxOptions {
57    /// Convenience constructor for deploy tx submissions — no
58    /// circuit ids, no timeout override.
59    #[must_use]
60    pub fn for_deploy(unproven_tx: UnprovenTx) -> Self {
61        Self {
62            unproven_tx,
63            circuit_ids: None,
64            prove_config: ProveTxConfig::default(),
65            ttl_ms: None,
66        }
67    }
68
69    /// Convenience constructor for call tx submissions — tags the
70    /// circuit id for diagnostics.
71    #[must_use]
72    pub fn for_call(unproven_tx: UnprovenTx, circuit_id: CircuitId) -> Self {
73        Self {
74            unproven_tx,
75            circuit_ids: Some(vec![circuit_id]),
76            prove_config: ProveTxConfig::default(),
77            ttl_ms: None,
78        }
79    }
80}
81
82/// Core pipeline stage: prove → balance → submit. Returns the
83/// chain-assigned transaction id. Port of TS `submitTxCore`.
84///
85/// # Errors
86///
87/// Propagates any error from the three provider calls —
88/// [`ProofProvider::prove_tx`], [`WalletProvider::balance_tx`],
89/// [`MidnightProvider::submit_tx`]. Each is wrapped in its own
90/// `ContractRuntimeError::Provider` / `Proving` / `Wallet` variant at
91/// the provider layer, so call-site handlers can pattern-match on the
92/// stage that failed.
93async fn submit_tx_core<C>(providers: &C, options: SubmitTxOptions) -> Result<TransactionId>
94where
95    C: HasProof + HasWallet + HasMidnight + HasLogger + ?Sized,
96{
97    let SubmitTxOptions {
98        unproven_tx,
99        circuit_ids,
100        prove_config,
101        ttl_ms,
102    } = options;
103
104    let proven = providers
105        .proof()
106        .prove_tx(unproven_tx, &prove_config)
107        .await?;
108    let finalized = providers.wallet().balance_tx(proven, ttl_ms).await?;
109    if let Some(logger) = providers.logger() {
110        let circuit_summary = circuit_ids.as_ref().map_or_else(
111            || "deploy".to_owned(),
112            |ids| {
113                ids.iter()
114                    .map(moonproof_runtime::CircuitId::as_str)
115                    .collect::<Vec<_>>()
116                    .join(",")
117            },
118        );
119        // `as_bytes()` reuses the cached form populated either by
120        // `from_tagged_bytes` at the FFI boundary or by the wallet
121        // provider's seal step — so the only `tagged_serialize` cost
122        // here is paid once across the whole pipeline.
123        let size = finalized.as_bytes().map_or(0, <[u8]>::len);
124        logger.debug(&format!(
125            "submit_tx: submitting {size} bytes (circuits={circuit_summary})"
126        ));
127    }
128    providers.midnight().submit_tx(finalized).await
129}
130
131/// Prove, balance, submit, and block until the transaction finalizes
132/// on-chain. Returns the full [`FinalizedTxData`]. Port of TS
133/// `submitTx`.
134///
135/// This method **waits indefinitely** for the transaction to appear
136/// on-chain, matching TS's explicit contract. Callers that need a
137/// timeout either wrap this future in their own timeout primitive,
138/// or use [`submit_tx_async`] + drive `watch_for_tx_data` themselves.
139pub async fn submit_tx<C>(providers: &C, options: SubmitTxOptions) -> Result<FinalizedTxData>
140where
141    C: HasProof + HasWallet + HasMidnight + HasPublicData + HasLogger + ?Sized,
142{
143    let tx_id = submit_tx_core(providers, options).await?;
144    providers.public_data().watch_for_tx_data(&tx_id).await
145}
146
147/// Prove, balance, submit, and return immediately with the
148/// chain-assigned transaction id — no finalization wait. Callers
149/// drive their own `watch_for_tx_data` subscription.
150///
151/// Port of TS `submitTxAsync`.
152pub async fn submit_tx_async<C>(providers: &C, options: SubmitTxOptions) -> Result<TransactionId>
153where
154    C: HasProof + HasWallet + HasMidnight + HasLogger + ?Sized,
155{
156    submit_tx_core(providers, options).await
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162    use crate::error::ContractRuntimeError;
163    use crate::providers::public_data::{PublicDataStream, ZSwapAndContractState};
164    use crate::providers::{
165        ErasedProviders, MidnightProvider, PrivateStateProvider, ProofProvider, PublicDataProvider,
166        WalletProvider, ZkConfigProvider,
167    };
168    use crate::types::{
169        ContractStateQueryAt, ContractStateStreamStart, PrivateStateId, TxStatus,
170        UnshieldedBalances,
171    };
172    use async_trait::async_trait;
173    use moonproof_ledger::coin_structure::contract::ContractAddress;
174    use moonproof_ledger::onchain_runtime::state::ContractState;
175    use moonproof_ledger::signatures::SigningKey;
176    use moonproof_ledger::storage::db::InMemoryDB;
177    use std::sync::atomic::{AtomicUsize, Ordering};
178    use std::sync::Arc;
179
180    // ---------------------------------------------------------------
181    // Mock providers — one per trait, captures inputs / returns
182    // scripted outputs so we can assert pipeline wiring.
183    // ---------------------------------------------------------------
184
185    // The pipeline-ordering checks the byte-marker mocks did in the
186    // original TS port (assert prove → balance → submit by appending
187    // 'P' / 'B' to flowing bytes) are now structural: wrong-phase
188    // input is a compile error, not a runtime byte-suffix mismatch.
189    // The remaining mocks track call counts only.
190
191    #[derive(Debug, Default)]
192    struct CapturingProofProvider {
193        prove_calls: AtomicUsize,
194    }
195    #[async_trait]
196    impl ProofProvider for CapturingProofProvider {
197        async fn prove_tx(
198            &self,
199            tx: crate::tx_phase::UnprovenTx,
200            _config: &ProveTxConfig,
201        ) -> Result<crate::tx_phase::ProvenTx> {
202            self.prove_calls.fetch_add(1, Ordering::Relaxed);
203            // Reuse the offline-tests `PassThroughProof` machinery —
204            // empty txs walk through with no real preimages.
205            crate::test_helpers::PassThroughProof
206                .prove_tx(tx, _config)
207                .await
208        }
209    }
210
211    #[derive(Debug, Default)]
212    struct CapturingWalletProvider {
213        balance_calls: AtomicUsize,
214    }
215    #[async_trait]
216    impl WalletProvider for CapturingWalletProvider {
217        async fn balance_tx(
218            &self,
219            tx: crate::tx_phase::ProvenTx,
220            _ttl_ms: Option<i64>,
221        ) -> Result<crate::tx_phase::FinalizedTx> {
222            use rand::SeedableRng;
223
224            self.balance_calls.fetch_add(1, Ordering::Relaxed);
225            let sealed = tx
226                .into_inner()
227                .seal(rand::rngs::StdRng::seed_from_u64(0xfeed_face));
228            Ok(crate::tx_phase::FinalizedTx::new(sealed))
229        }
230        fn coin_public_key(&self) -> crate::types::CoinPublicKey {
231            crate::types::CoinPublicKey([0u8; 32])
232        }
233        fn encryption_public_key(&self) -> crate::types::EncPublicKey {
234            crate::types::EncPublicKey([0u8; 32])
235        }
236    }
237
238    #[derive(Debug, Default)]
239    struct CapturingMidnightProvider {
240        submit_calls: AtomicUsize,
241    }
242    #[async_trait]
243    impl MidnightProvider for CapturingMidnightProvider {
244        async fn submit_tx(&self, _tx: crate::tx_phase::FinalizedTx) -> Result<TransactionId> {
245            self.submit_calls.fetch_add(1, Ordering::Relaxed);
246            Ok(TransactionId::new("0xabc123"))
247        }
248    }
249
250    #[derive(Debug, Default)]
251    struct StubPublicData {
252        watch_tx_calls: AtomicUsize,
253    }
254    #[async_trait]
255    impl PublicDataProvider for StubPublicData {
256        async fn query_contract_state(
257            &self,
258            _address: &ContractAddress,
259            _at: Option<ContractStateQueryAt>,
260        ) -> Result<Option<ContractState<InMemoryDB>>> {
261            unimplemented!("not used in submit_tx tests")
262        }
263        async fn query_zswap_and_contract_state(
264            &self,
265            _address: &ContractAddress,
266            _at: Option<ContractStateQueryAt>,
267        ) -> Result<Option<ZSwapAndContractState>> {
268            unimplemented!("not used")
269        }
270        async fn query_deploy_contract_state(
271            &self,
272            _address: &ContractAddress,
273        ) -> Result<Option<ContractState<InMemoryDB>>> {
274            unimplemented!("not used")
275        }
276        async fn query_unshielded_balances(
277            &self,
278            _address: &ContractAddress,
279            _at: Option<ContractStateQueryAt>,
280        ) -> Result<Option<UnshieldedBalances>> {
281            unimplemented!("not used")
282        }
283        async fn watch_for_deploy_tx_data(
284            &self,
285            _address: &ContractAddress,
286        ) -> Result<FinalizedTxData> {
287            unimplemented!("not used")
288        }
289        async fn watch_for_tx_data(&self, tx_id: &TransactionId) -> Result<FinalizedTxData> {
290            self.watch_tx_calls.fetch_add(1, Ordering::Relaxed);
291            Ok(stub_finalized_tx_data(tx_id))
292        }
293        async fn watch_for_contract_state(
294            &self,
295            _address: &ContractAddress,
296        ) -> Result<ContractState<InMemoryDB>> {
297            unimplemented!("not used")
298        }
299        async fn watch_for_unshielded_balances(
300            &self,
301            _address: &ContractAddress,
302        ) -> Result<UnshieldedBalances> {
303            unimplemented!("not used")
304        }
305        async fn contract_state_stream(
306            &self,
307            _address: &ContractAddress,
308            _start: ContractStateStreamStart,
309        ) -> Result<PublicDataStream<ContractState<InMemoryDB>>> {
310            unimplemented!("not used")
311        }
312        async fn unshielded_balances_stream(
313            &self,
314            _address: &ContractAddress,
315            _start: ContractStateStreamStart,
316        ) -> Result<PublicDataStream<UnshieldedBalances>> {
317            unimplemented!("not used")
318        }
319    }
320
321    fn stub_finalized_tx_data(tx_id: &TransactionId) -> FinalizedTxData {
322        FinalizedTxData {
323            tx_id: tx_id.clone(),
324            identifiers: vec![tx_id.clone()],
325            tx_hash: crate::types::TransactionHash::new("0xhash"),
326            block_hash: crate::types::BlockHash::new("0xblock"),
327            block_height: 1,
328            block_timestamp_ms: 0,
329            block_author: None,
330            indexer_id: 0,
331            protocol_version: moonproof_wallet::ProtocolVersion(8),
332            status: TxStatus::SucceedEntirely,
333            segment_status_map: None,
334            fees: crate::types::Fees {
335                paid_fees: "0".into(),
336                estimated_fees: "0".into(),
337            },
338            unshielded: crate::types::UnshieldedUtxos::default(),
339            tx_bytes: Vec::new(),
340        }
341    }
342
343    #[derive(Debug, Default)]
344    struct NoopPrivateStateProvider;
345    #[async_trait]
346    impl PrivateStateProvider for NoopPrivateStateProvider {
347        async fn set_contract_address(&self, _address: &ContractAddress) -> Result<()> {
348            Ok(())
349        }
350        async fn set(&self, _private_state_id: &PrivateStateId, _state: Vec<u8>) -> Result<()> {
351            Ok(())
352        }
353        async fn get(&self, _private_state_id: &PrivateStateId) -> Result<Option<Vec<u8>>> {
354            Ok(None)
355        }
356        async fn remove(&self, _private_state_id: &PrivateStateId) -> Result<()> {
357            Ok(())
358        }
359        async fn clear(&self) -> Result<()> {
360            Ok(())
361        }
362        async fn set_signing_key(
363            &self,
364            _address: &ContractAddress,
365            _signing_key: SigningKey,
366        ) -> Result<()> {
367            Ok(())
368        }
369        async fn get_signing_key(&self, _address: &ContractAddress) -> Result<Option<SigningKey>> {
370            Ok(None)
371        }
372        async fn remove_signing_key(&self, _address: &ContractAddress) -> Result<()> {
373            Ok(())
374        }
375        async fn clear_signing_keys(&self) -> Result<()> {
376            Ok(())
377        }
378        async fn export_private_states(
379            &self,
380            _options: &crate::providers::ExportPrivateStatesOptions,
381        ) -> Result<crate::providers::PrivateStateExport> {
382            unimplemented!()
383        }
384        async fn import_private_states(
385            &self,
386            _export: &crate::providers::PrivateStateExport,
387            _options: &crate::providers::ImportPrivateStatesOptions,
388        ) -> Result<crate::providers::ImportPrivateStatesResult> {
389            unimplemented!()
390        }
391        async fn export_signing_keys(
392            &self,
393            _options: &crate::providers::private_state::ExportSigningKeysOptions,
394        ) -> Result<crate::providers::SigningKeyExport> {
395            unimplemented!()
396        }
397        async fn import_signing_keys(
398            &self,
399            _export: &crate::providers::SigningKeyExport,
400            _options: &crate::providers::private_state::ImportSigningKeysOptions,
401        ) -> Result<crate::providers::private_state::ImportSigningKeysResult> {
402            unimplemented!()
403        }
404    }
405
406    #[derive(Debug, Default)]
407    struct NoopZkConfig;
408    #[async_trait]
409    impl ZkConfigProvider for NoopZkConfig {
410        async fn get_zkir(&self, _circuit_id: &CircuitId) -> Result<crate::types::Zkir> {
411            unimplemented!()
412        }
413        async fn get_prover_key(&self, _circuit_id: &CircuitId) -> Result<crate::types::ProverKey> {
414            unimplemented!()
415        }
416        async fn get_verifier_key(
417            &self,
418            _circuit_id: &CircuitId,
419        ) -> Result<crate::types::VerifierKey> {
420            unimplemented!()
421        }
422    }
423
424    fn capturing_providers() -> (
425        ErasedProviders,
426        Arc<CapturingProofProvider>,
427        Arc<CapturingWalletProvider>,
428        Arc<CapturingMidnightProvider>,
429        Arc<StubPublicData>,
430    ) {
431        let proof = Arc::new(CapturingProofProvider::default());
432        let wallet = Arc::new(CapturingWalletProvider::default());
433        let midnight = Arc::new(CapturingMidnightProvider::default());
434        let public_data = Arc::new(StubPublicData::default());
435        let bundle = ErasedProviders::builder()
436            .private_state(Arc::new(NoopPrivateStateProvider))
437            .public_data(public_data.clone())
438            .zk_config(Arc::new(NoopZkConfig))
439            .proof(proof.clone())
440            .wallet(wallet.clone())
441            .midnight(midnight.clone())
442            .build();
443        (bundle, proof, wallet, midnight, public_data)
444    }
445
446    // ---------------------------------------------------------------
447    // Tests
448    // ---------------------------------------------------------------
449
450    fn empty_unproven_tx() -> crate::tx_phase::UnprovenTx {
451        use moonproof_ledger::ledger::structure::Transaction;
452        let tx: Transaction<
453            moonproof_ledger::signatures::Signature,
454            moonproof_ledger::ledger::structure::ProofPreimageMarker,
455            moonproof_ledger::transient_crypto::commitment::PedersenRandomness,
456            InMemoryDB,
457        > = Transaction::from_intents(
458            "local-test",
459            moonproof_ledger::storage::storage::HashMap::new(),
460        );
461        crate::tx_phase::UnprovenTx::new(tx)
462    }
463
464    /// ports: `submit-tx.test.ts::submitTxAsync::should submit transaction and return txId without waiting for finalization`
465    /// ports: `submit-tx.test.ts::submitTxAsync::should submit transaction with circuit ID and return txId`
466    #[tokio::test]
467    async fn submit_tx_async_calls_each_stage_once_in_order() {
468        let (providers, proof, wallet, midnight, _) = capturing_providers();
469        let opts = SubmitTxOptions::for_deploy(empty_unproven_tx());
470        let tx_id = submit_tx_async(&providers, opts).await.unwrap();
471        assert_eq!(tx_id.as_str(), "0xabc123");
472        // Each stage called exactly once. Pipeline ordering itself is
473        // structurally enforced — prove returns a `ProvenTx`, balance
474        // requires a `ProvenTx`, etc — wrong order is a compile
475        // error.
476        assert_eq!(proof.prove_calls.load(Ordering::Relaxed), 1);
477        assert_eq!(wallet.balance_calls.load(Ordering::Relaxed), 1);
478        assert_eq!(midnight.submit_calls.load(Ordering::Relaxed), 1);
479    }
480
481    /// ports: `submit-tx.test.ts::submitTx::should successfully submit transaction without circuit ID`
482    /// ports: `submit-tx.test.ts::submitTx::should successfully submit transaction with circuit ID`
483    #[tokio::test]
484    async fn submit_tx_waits_for_finalization_and_returns_full_data() {
485        let (providers, _, _, midnight, public_data) = capturing_providers();
486        let opts = SubmitTxOptions::for_call(empty_unproven_tx(), CircuitId::new("increment"));
487        let finalized = submit_tx(&providers, opts).await.unwrap();
488        assert_eq!(finalized.tx_id.as_str(), "0xabc123");
489        assert_eq!(finalized.status, TxStatus::SucceedEntirely);
490        assert_eq!(midnight.submit_calls.load(Ordering::Relaxed), 1);
491        assert_eq!(public_data.watch_tx_calls.load(Ordering::Relaxed), 1);
492    }
493
494    /// ports: `submit-tx.test.ts::error handling::should propagate proveTx errors`
495    #[tokio::test]
496    async fn prove_failure_short_circuits_the_pipeline() {
497        #[derive(Debug, Default)]
498        struct FailingProof;
499        #[async_trait]
500        impl ProofProvider for FailingProof {
501            async fn prove_tx(
502                &self,
503                _tx: crate::tx_phase::UnprovenTx,
504                _config: &ProveTxConfig,
505            ) -> Result<crate::tx_phase::ProvenTx> {
506                Err(ContractRuntimeError::Proving(
507                    "simulated prove failure".to_owned(),
508                ))
509            }
510        }
511        let wallet = Arc::new(CapturingWalletProvider::default());
512        let midnight = Arc::new(CapturingMidnightProvider::default());
513        let providers = ErasedProviders::builder()
514            .private_state(Arc::new(NoopPrivateStateProvider))
515            .public_data(Arc::new(StubPublicData::default()))
516            .zk_config(Arc::new(NoopZkConfig))
517            .proof(Arc::new(FailingProof))
518            .wallet(wallet.clone())
519            .midnight(midnight.clone())
520            .build();
521        let opts = SubmitTxOptions::for_deploy(empty_unproven_tx());
522        let err = submit_tx_async(&providers, opts).await.unwrap_err();
523        matches!(err, ContractRuntimeError::Proving(_));
524        // Wallet + midnight should not have been called.
525        assert_eq!(wallet.balance_calls.load(Ordering::Relaxed), 0);
526        assert_eq!(midnight.submit_calls.load(Ordering::Relaxed), 0);
527    }
528
529    /// ports: `submit-tx.test.ts::error handling::should propagate balanceTx errors`
530    /// ports: `submit-tx.test.ts::error handling::should propagate submitTx errors`
531    #[tokio::test]
532    async fn balance_failure_stops_before_submit() {
533        #[derive(Debug, Default)]
534        struct FailingWallet;
535        #[async_trait]
536        impl WalletProvider for FailingWallet {
537            async fn balance_tx(
538                &self,
539                _tx: crate::tx_phase::ProvenTx,
540                _ttl_ms: Option<i64>,
541            ) -> Result<crate::tx_phase::FinalizedTx> {
542                Err(ContractRuntimeError::Provider {
543                    provider: "wallet",
544                    message: "simulated balance failure".to_owned(),
545                })
546            }
547            fn coin_public_key(&self) -> crate::types::CoinPublicKey {
548                crate::types::CoinPublicKey([0; 32])
549            }
550            fn encryption_public_key(&self) -> crate::types::EncPublicKey {
551                crate::types::EncPublicKey([0; 32])
552            }
553        }
554        let midnight = Arc::new(CapturingMidnightProvider::default());
555        let providers = ErasedProviders::builder()
556            .private_state(Arc::new(NoopPrivateStateProvider))
557            .public_data(Arc::new(StubPublicData::default()))
558            .zk_config(Arc::new(NoopZkConfig))
559            .proof(Arc::new(CapturingProofProvider::default()))
560            .wallet(Arc::new(FailingWallet))
561            .midnight(midnight.clone())
562            .build();
563        let opts = SubmitTxOptions::for_deploy(empty_unproven_tx());
564        let err = submit_tx_async(&providers, opts).await.unwrap_err();
565        matches!(err, ContractRuntimeError::Provider { .. });
566        assert_eq!(midnight.submit_calls.load(Ordering::Relaxed), 0);
567    }
568
569    #[test]
570    fn for_deploy_builds_options_with_no_circuit_id() {
571        let o = SubmitTxOptions::for_deploy(empty_unproven_tx());
572        assert!(o.circuit_ids.is_none());
573        assert!(o.ttl_ms.is_none());
574    }
575
576    #[test]
577    fn for_call_tags_circuit_id() {
578        let o = SubmitTxOptions::for_call(empty_unproven_tx(), CircuitId::new("c"));
579        assert_eq!(o.circuit_ids.as_ref().unwrap()[0].as_str(), "c");
580    }
581}