moonproof-contracts 0.2.1

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Port of `@midnight-ntwrk/midnight-js-contracts/src/submit-tx.ts`.
//!
//! The three-step submission pipeline every contract transaction
//! (deploy, call, maintenance) runs through:
//!
//! 1. **Prove** — hand the unproven tx bytes to
//!    [`ProofProvider::prove_tx`]; it runs the ZK prover on every
//!    contract-call / zswap proof inside the transaction and returns
//!    tagged-serialized bytes of the post-prove shape
//!    (`Transaction<Signature, ProofMarker, PedersenRandomness, _>`).
//! 2. **Balance** — hand the proven bytes to
//!    [`WalletProvider::balance_tx`]; it adds dust coins to cover the
//!    fee and seals the binding commitment, returning the finalized
//!    wire bytes the node accepts.
//! 3. **Submit** — hand the finalized bytes to
//!    [`MidnightProvider::submit_tx`]; it submits to the node via
//!    `pallet_midnight.send_mn_transaction` and returns the chain-
//!    assigned transaction id.
//!
//! After submission, [`submit_tx`] waits for the transaction to
//! finalize on-chain via
//! [`PublicDataProvider::watch_for_tx_data`] and returns the full
//! [`FinalizedTxData`]. [`submit_tx_async`] skips the wait and
//! returns immediately with the transaction id — callers that need
//! finalization subscribe to `watch_for_tx_data` themselves.

use crate::error::Result;
use crate::providers::{
    HasLogger, HasMidnight, HasProof, HasPublicData, HasWallet, LoggerProvider, MidnightProvider,
    ProofProvider, ProveTxConfig, PublicDataProvider, WalletProvider,
};
use crate::tx_phase::UnprovenTx;
use crate::types::{CircuitId, FinalizedTxData, TransactionId};

/// Options for [`submit_tx`] / [`submit_tx_async`]. Port of TS
/// `SubmitTxOptions`.
#[derive(Debug, Clone)]
pub struct SubmitTxOptions {
    /// The pre-prove transaction the proof provider consumes.
    pub unproven_tx: UnprovenTx,
    /// The circuit id(s) this submission covers. `None` for deploys,
    /// `Some([id])` for a single-call tx, `Some([id1, id2, ...])`
    /// for scoped-transaction batches. Preserved for diagnostics
    /// (the TS variant uses it for failure-logging + scope
    /// identification).
    pub circuit_ids: Option<Vec<CircuitId>>,
    /// Proof-request configuration (timeout etc.) threaded to the
    /// proof provider.
    pub prove_config: ProveTxConfig,
    /// Optional transaction TTL in milliseconds. Threaded to
    /// [`WalletProvider::balance_tx`]. `None` uses the wallet
    /// provider's default (typically "chain-now + 1h").
    pub ttl_ms: Option<i64>,
}

impl SubmitTxOptions {
    /// Convenience constructor for deploy tx submissions — no
    /// circuit ids, no timeout override.
    #[must_use]
    pub fn for_deploy(unproven_tx: UnprovenTx) -> Self {
        Self {
            unproven_tx,
            circuit_ids: None,
            prove_config: ProveTxConfig::default(),
            ttl_ms: None,
        }
    }

    /// Convenience constructor for call tx submissions — tags the
    /// circuit id for diagnostics.
    #[must_use]
    pub fn for_call(unproven_tx: UnprovenTx, circuit_id: CircuitId) -> Self {
        Self {
            unproven_tx,
            circuit_ids: Some(vec![circuit_id]),
            prove_config: ProveTxConfig::default(),
            ttl_ms: None,
        }
    }
}

/// Core pipeline stage: prove → balance → submit. Returns the
/// chain-assigned transaction id. Port of TS `submitTxCore`.
///
/// # Errors
///
/// Propagates any error from the three provider calls —
/// [`ProofProvider::prove_tx`], [`WalletProvider::balance_tx`],
/// [`MidnightProvider::submit_tx`]. Each is wrapped in its own
/// `ContractRuntimeError::Provider` / `Proving` / `Wallet` variant at
/// the provider layer, so call-site handlers can pattern-match on the
/// stage that failed.
async fn submit_tx_core<C>(providers: &C, options: SubmitTxOptions) -> Result<TransactionId>
where
    C: HasProof + HasWallet + HasMidnight + HasLogger + ?Sized,
{
    let SubmitTxOptions {
        unproven_tx,
        circuit_ids,
        prove_config,
        ttl_ms,
    } = options;

    let proven = providers
        .proof()
        .prove_tx(unproven_tx, &prove_config)
        .await?;
    let finalized = providers.wallet().balance_tx(proven, ttl_ms).await?;
    if let Some(logger) = providers.logger() {
        let circuit_summary = circuit_ids.as_ref().map_or_else(
            || "deploy".to_owned(),
            |ids| {
                ids.iter()
                    .map(moonproof_runtime::CircuitId::as_str)
                    .collect::<Vec<_>>()
                    .join(",")
            },
        );
        // `as_bytes()` reuses the cached form populated either by
        // `from_tagged_bytes` at the FFI boundary or by the wallet
        // provider's seal step — so the only `tagged_serialize` cost
        // here is paid once across the whole pipeline.
        let size = finalized.as_bytes().map_or(0, <[u8]>::len);
        logger.debug(&format!(
            "submit_tx: submitting {size} bytes (circuits={circuit_summary})"
        ));
    }
    providers.midnight().submit_tx(finalized).await
}

/// Prove, balance, submit, and block until the transaction finalizes
/// on-chain. Returns the full [`FinalizedTxData`]. Port of TS
/// `submitTx`.
///
/// This method **waits indefinitely** for the transaction to appear
/// on-chain, matching TS's explicit contract. Callers that need a
/// timeout either wrap this future in their own timeout primitive,
/// or use [`submit_tx_async`] + drive `watch_for_tx_data` themselves.
pub async fn submit_tx<C>(providers: &C, options: SubmitTxOptions) -> Result<FinalizedTxData>
where
    C: HasProof + HasWallet + HasMidnight + HasPublicData + HasLogger + ?Sized,
{
    let tx_id = submit_tx_core(providers, options).await?;
    providers.public_data().watch_for_tx_data(&tx_id).await
}

/// Prove, balance, submit, and return immediately with the
/// chain-assigned transaction id — no finalization wait. Callers
/// drive their own `watch_for_tx_data` subscription.
///
/// Port of TS `submitTxAsync`.
pub async fn submit_tx_async<C>(providers: &C, options: SubmitTxOptions) -> Result<TransactionId>
where
    C: HasProof + HasWallet + HasMidnight + HasLogger + ?Sized,
{
    submit_tx_core(providers, options).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ContractRuntimeError;
    use crate::providers::public_data::{PublicDataStream, ZSwapAndContractState};
    use crate::providers::{
        ErasedProviders, MidnightProvider, PrivateStateProvider, ProofProvider, PublicDataProvider,
        WalletProvider, ZkConfigProvider,
    };
    use crate::types::{
        ContractStateQueryAt, ContractStateStreamStart, PrivateStateId, TxStatus,
        UnshieldedBalances,
    };
    use async_trait::async_trait;
    use moonproof_ledger::coin_structure::contract::ContractAddress;
    use moonproof_ledger::onchain_runtime::state::ContractState;
    use moonproof_ledger::signatures::SigningKey;
    use moonproof_ledger::storage::db::InMemoryDB;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    // ---------------------------------------------------------------
    // Mock providers — one per trait, captures inputs / returns
    // scripted outputs so we can assert pipeline wiring.
    // ---------------------------------------------------------------

    // The pipeline-ordering checks the byte-marker mocks did in the
    // original TS port (assert prove → balance → submit by appending
    // 'P' / 'B' to flowing bytes) are now structural: wrong-phase
    // input is a compile error, not a runtime byte-suffix mismatch.
    // The remaining mocks track call counts only.

    #[derive(Debug, Default)]
    struct CapturingProofProvider {
        prove_calls: AtomicUsize,
    }
    #[async_trait]
    impl ProofProvider for CapturingProofProvider {
        async fn prove_tx(
            &self,
            tx: crate::tx_phase::UnprovenTx,
            _config: &ProveTxConfig,
        ) -> Result<crate::tx_phase::ProvenTx> {
            self.prove_calls.fetch_add(1, Ordering::Relaxed);
            // Reuse the offline-tests `PassThroughProof` machinery —
            // empty txs walk through with no real preimages.
            crate::test_helpers::PassThroughProof
                .prove_tx(tx, _config)
                .await
        }
    }

    #[derive(Debug, Default)]
    struct CapturingWalletProvider {
        balance_calls: AtomicUsize,
    }
    #[async_trait]
    impl WalletProvider for CapturingWalletProvider {
        async fn balance_tx(
            &self,
            tx: crate::tx_phase::ProvenTx,
            _ttl_ms: Option<i64>,
        ) -> Result<crate::tx_phase::FinalizedTx> {
            use rand::SeedableRng;

            self.balance_calls.fetch_add(1, Ordering::Relaxed);
            let sealed = tx
                .into_inner()
                .seal(rand::rngs::StdRng::seed_from_u64(0xfeed_face));
            Ok(crate::tx_phase::FinalizedTx::new(sealed))
        }
        fn coin_public_key(&self) -> crate::types::CoinPublicKey {
            crate::types::CoinPublicKey([0u8; 32])
        }
        fn encryption_public_key(&self) -> crate::types::EncPublicKey {
            crate::types::EncPublicKey([0u8; 32])
        }
    }

    #[derive(Debug, Default)]
    struct CapturingMidnightProvider {
        submit_calls: AtomicUsize,
    }
    #[async_trait]
    impl MidnightProvider for CapturingMidnightProvider {
        async fn submit_tx(&self, _tx: crate::tx_phase::FinalizedTx) -> Result<TransactionId> {
            self.submit_calls.fetch_add(1, Ordering::Relaxed);
            Ok(TransactionId::new("0xabc123"))
        }
    }

    #[derive(Debug, Default)]
    struct StubPublicData {
        watch_tx_calls: AtomicUsize,
    }
    #[async_trait]
    impl PublicDataProvider for StubPublicData {
        async fn query_contract_state(
            &self,
            _address: &ContractAddress,
            _at: Option<ContractStateQueryAt>,
        ) -> Result<Option<ContractState<InMemoryDB>>> {
            unimplemented!("not used in submit_tx tests")
        }
        async fn query_zswap_and_contract_state(
            &self,
            _address: &ContractAddress,
            _at: Option<ContractStateQueryAt>,
        ) -> Result<Option<ZSwapAndContractState>> {
            unimplemented!("not used")
        }
        async fn query_deploy_contract_state(
            &self,
            _address: &ContractAddress,
        ) -> Result<Option<ContractState<InMemoryDB>>> {
            unimplemented!("not used")
        }
        async fn query_unshielded_balances(
            &self,
            _address: &ContractAddress,
            _at: Option<ContractStateQueryAt>,
        ) -> Result<Option<UnshieldedBalances>> {
            unimplemented!("not used")
        }
        async fn watch_for_deploy_tx_data(
            &self,
            _address: &ContractAddress,
        ) -> Result<FinalizedTxData> {
            unimplemented!("not used")
        }
        async fn watch_for_tx_data(&self, tx_id: &TransactionId) -> Result<FinalizedTxData> {
            self.watch_tx_calls.fetch_add(1, Ordering::Relaxed);
            Ok(stub_finalized_tx_data(tx_id))
        }
        async fn watch_for_contract_state(
            &self,
            _address: &ContractAddress,
        ) -> Result<ContractState<InMemoryDB>> {
            unimplemented!("not used")
        }
        async fn watch_for_unshielded_balances(
            &self,
            _address: &ContractAddress,
        ) -> Result<UnshieldedBalances> {
            unimplemented!("not used")
        }
        async fn contract_state_stream(
            &self,
            _address: &ContractAddress,
            _start: ContractStateStreamStart,
        ) -> Result<PublicDataStream<ContractState<InMemoryDB>>> {
            unimplemented!("not used")
        }
        async fn unshielded_balances_stream(
            &self,
            _address: &ContractAddress,
            _start: ContractStateStreamStart,
        ) -> Result<PublicDataStream<UnshieldedBalances>> {
            unimplemented!("not used")
        }
    }

    fn stub_finalized_tx_data(tx_id: &TransactionId) -> FinalizedTxData {
        FinalizedTxData {
            tx_id: tx_id.clone(),
            identifiers: vec![tx_id.clone()],
            tx_hash: crate::types::TransactionHash::new("0xhash"),
            block_hash: crate::types::BlockHash::new("0xblock"),
            block_height: 1,
            block_timestamp_ms: 0,
            block_author: None,
            indexer_id: 0,
            protocol_version: moonproof_wallet::ProtocolVersion(8),
            status: TxStatus::SucceedEntirely,
            segment_status_map: None,
            fees: crate::types::Fees {
                paid_fees: "0".into(),
                estimated_fees: "0".into(),
            },
            unshielded: crate::types::UnshieldedUtxos::default(),
            tx_bytes: Vec::new(),
        }
    }

    #[derive(Debug, Default)]
    struct NoopPrivateStateProvider;
    #[async_trait]
    impl PrivateStateProvider for NoopPrivateStateProvider {
        async fn set_contract_address(&self, _address: &ContractAddress) -> Result<()> {
            Ok(())
        }
        async fn set(&self, _private_state_id: &PrivateStateId, _state: Vec<u8>) -> Result<()> {
            Ok(())
        }
        async fn get(&self, _private_state_id: &PrivateStateId) -> Result<Option<Vec<u8>>> {
            Ok(None)
        }
        async fn remove(&self, _private_state_id: &PrivateStateId) -> Result<()> {
            Ok(())
        }
        async fn clear(&self) -> Result<()> {
            Ok(())
        }
        async fn set_signing_key(
            &self,
            _address: &ContractAddress,
            _signing_key: SigningKey,
        ) -> Result<()> {
            Ok(())
        }
        async fn get_signing_key(&self, _address: &ContractAddress) -> Result<Option<SigningKey>> {
            Ok(None)
        }
        async fn remove_signing_key(&self, _address: &ContractAddress) -> Result<()> {
            Ok(())
        }
        async fn clear_signing_keys(&self) -> Result<()> {
            Ok(())
        }
        async fn export_private_states(
            &self,
            _options: &crate::providers::ExportPrivateStatesOptions,
        ) -> Result<crate::providers::PrivateStateExport> {
            unimplemented!()
        }
        async fn import_private_states(
            &self,
            _export: &crate::providers::PrivateStateExport,
            _options: &crate::providers::ImportPrivateStatesOptions,
        ) -> Result<crate::providers::ImportPrivateStatesResult> {
            unimplemented!()
        }
        async fn export_signing_keys(
            &self,
            _options: &crate::providers::private_state::ExportSigningKeysOptions,
        ) -> Result<crate::providers::SigningKeyExport> {
            unimplemented!()
        }
        async fn import_signing_keys(
            &self,
            _export: &crate::providers::SigningKeyExport,
            _options: &crate::providers::private_state::ImportSigningKeysOptions,
        ) -> Result<crate::providers::private_state::ImportSigningKeysResult> {
            unimplemented!()
        }
    }

    #[derive(Debug, Default)]
    struct NoopZkConfig;
    #[async_trait]
    impl ZkConfigProvider for NoopZkConfig {
        async fn get_zkir(&self, _circuit_id: &CircuitId) -> Result<crate::types::Zkir> {
            unimplemented!()
        }
        async fn get_prover_key(&self, _circuit_id: &CircuitId) -> Result<crate::types::ProverKey> {
            unimplemented!()
        }
        async fn get_verifier_key(
            &self,
            _circuit_id: &CircuitId,
        ) -> Result<crate::types::VerifierKey> {
            unimplemented!()
        }
    }

    fn capturing_providers() -> (
        ErasedProviders,
        Arc<CapturingProofProvider>,
        Arc<CapturingWalletProvider>,
        Arc<CapturingMidnightProvider>,
        Arc<StubPublicData>,
    ) {
        let proof = Arc::new(CapturingProofProvider::default());
        let wallet = Arc::new(CapturingWalletProvider::default());
        let midnight = Arc::new(CapturingMidnightProvider::default());
        let public_data = Arc::new(StubPublicData::default());
        let bundle = ErasedProviders::builder()
            .private_state(Arc::new(NoopPrivateStateProvider))
            .public_data(public_data.clone())
            .zk_config(Arc::new(NoopZkConfig))
            .proof(proof.clone())
            .wallet(wallet.clone())
            .midnight(midnight.clone())
            .build();
        (bundle, proof, wallet, midnight, public_data)
    }

    // ---------------------------------------------------------------
    // Tests
    // ---------------------------------------------------------------

    fn empty_unproven_tx() -> crate::tx_phase::UnprovenTx {
        use moonproof_ledger::ledger::structure::Transaction;
        let tx: Transaction<
            moonproof_ledger::signatures::Signature,
            moonproof_ledger::ledger::structure::ProofPreimageMarker,
            moonproof_ledger::transient_crypto::commitment::PedersenRandomness,
            InMemoryDB,
        > = Transaction::from_intents(
            "local-test",
            moonproof_ledger::storage::storage::HashMap::new(),
        );
        crate::tx_phase::UnprovenTx::new(tx)
    }

    /// ports: `submit-tx.test.ts::submitTxAsync::should submit transaction and return txId without waiting for finalization`
    /// ports: `submit-tx.test.ts::submitTxAsync::should submit transaction with circuit ID and return txId`
    #[tokio::test]
    async fn submit_tx_async_calls_each_stage_once_in_order() {
        let (providers, proof, wallet, midnight, _) = capturing_providers();
        let opts = SubmitTxOptions::for_deploy(empty_unproven_tx());
        let tx_id = submit_tx_async(&providers, opts).await.unwrap();
        assert_eq!(tx_id.as_str(), "0xabc123");
        // Each stage called exactly once. Pipeline ordering itself is
        // structurally enforced — prove returns a `ProvenTx`, balance
        // requires a `ProvenTx`, etc — wrong order is a compile
        // error.
        assert_eq!(proof.prove_calls.load(Ordering::Relaxed), 1);
        assert_eq!(wallet.balance_calls.load(Ordering::Relaxed), 1);
        assert_eq!(midnight.submit_calls.load(Ordering::Relaxed), 1);
    }

    /// ports: `submit-tx.test.ts::submitTx::should successfully submit transaction without circuit ID`
    /// ports: `submit-tx.test.ts::submitTx::should successfully submit transaction with circuit ID`
    #[tokio::test]
    async fn submit_tx_waits_for_finalization_and_returns_full_data() {
        let (providers, _, _, midnight, public_data) = capturing_providers();
        let opts = SubmitTxOptions::for_call(empty_unproven_tx(), CircuitId::new("increment"));
        let finalized = submit_tx(&providers, opts).await.unwrap();
        assert_eq!(finalized.tx_id.as_str(), "0xabc123");
        assert_eq!(finalized.status, TxStatus::SucceedEntirely);
        assert_eq!(midnight.submit_calls.load(Ordering::Relaxed), 1);
        assert_eq!(public_data.watch_tx_calls.load(Ordering::Relaxed), 1);
    }

    /// ports: `submit-tx.test.ts::error handling::should propagate proveTx errors`
    #[tokio::test]
    async fn prove_failure_short_circuits_the_pipeline() {
        #[derive(Debug, Default)]
        struct FailingProof;
        #[async_trait]
        impl ProofProvider for FailingProof {
            async fn prove_tx(
                &self,
                _tx: crate::tx_phase::UnprovenTx,
                _config: &ProveTxConfig,
            ) -> Result<crate::tx_phase::ProvenTx> {
                Err(ContractRuntimeError::Proving(
                    "simulated prove failure".to_owned(),
                ))
            }
        }
        let wallet = Arc::new(CapturingWalletProvider::default());
        let midnight = Arc::new(CapturingMidnightProvider::default());
        let providers = ErasedProviders::builder()
            .private_state(Arc::new(NoopPrivateStateProvider))
            .public_data(Arc::new(StubPublicData::default()))
            .zk_config(Arc::new(NoopZkConfig))
            .proof(Arc::new(FailingProof))
            .wallet(wallet.clone())
            .midnight(midnight.clone())
            .build();
        let opts = SubmitTxOptions::for_deploy(empty_unproven_tx());
        let err = submit_tx_async(&providers, opts).await.unwrap_err();
        matches!(err, ContractRuntimeError::Proving(_));
        // Wallet + midnight should not have been called.
        assert_eq!(wallet.balance_calls.load(Ordering::Relaxed), 0);
        assert_eq!(midnight.submit_calls.load(Ordering::Relaxed), 0);
    }

    /// ports: `submit-tx.test.ts::error handling::should propagate balanceTx errors`
    /// ports: `submit-tx.test.ts::error handling::should propagate submitTx errors`
    #[tokio::test]
    async fn balance_failure_stops_before_submit() {
        #[derive(Debug, Default)]
        struct FailingWallet;
        #[async_trait]
        impl WalletProvider for FailingWallet {
            async fn balance_tx(
                &self,
                _tx: crate::tx_phase::ProvenTx,
                _ttl_ms: Option<i64>,
            ) -> Result<crate::tx_phase::FinalizedTx> {
                Err(ContractRuntimeError::Provider {
                    provider: "wallet",
                    message: "simulated balance failure".to_owned(),
                })
            }
            fn coin_public_key(&self) -> crate::types::CoinPublicKey {
                crate::types::CoinPublicKey([0; 32])
            }
            fn encryption_public_key(&self) -> crate::types::EncPublicKey {
                crate::types::EncPublicKey([0; 32])
            }
        }
        let midnight = Arc::new(CapturingMidnightProvider::default());
        let providers = ErasedProviders::builder()
            .private_state(Arc::new(NoopPrivateStateProvider))
            .public_data(Arc::new(StubPublicData::default()))
            .zk_config(Arc::new(NoopZkConfig))
            .proof(Arc::new(CapturingProofProvider::default()))
            .wallet(Arc::new(FailingWallet))
            .midnight(midnight.clone())
            .build();
        let opts = SubmitTxOptions::for_deploy(empty_unproven_tx());
        let err = submit_tx_async(&providers, opts).await.unwrap_err();
        matches!(err, ContractRuntimeError::Provider { .. });
        assert_eq!(midnight.submit_calls.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn for_deploy_builds_options_with_no_circuit_id() {
        let o = SubmitTxOptions::for_deploy(empty_unproven_tx());
        assert!(o.circuit_ids.is_none());
        assert!(o.ttl_ms.is_none());
    }

    #[test]
    fn for_call_tags_circuit_id() {
        let o = SubmitTxOptions::for_call(empty_unproven_tx(), CircuitId::new("c"));
        assert_eq!(o.circuit_ids.as_ref().unwrap()[0].as_str(), "c");
    }
}