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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
//! Port of
//! `@midnight-ntwrk/midnight-js-contracts/src/tx-interfaces.ts`.
//!
//! Factories that bind a specific deployed contract to the providers
//! bundle and expose ergonomic call / maintenance entry points.
//!
//! # Shape differences from TS
//!
//! The TS `ContractCallsInterface<C>` is a mapped type keyed by
//! circuit id, where each value is a typed variadic closure. Rust's
//! generic system can't express "function type that depends on a key
//! in a struct-level map", so the Rust port uses an explicit
//! `call(circuit_id, args)` method on [`ContractCalls`]. Semantically
//! equivalent — slightly more explicit at the call site.
//!
//! Maintenance interfaces are a 1:1 port.

use std::sync::Arc;

use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::signatures::SigningKey;
use rand::{CryptoRng, Rng};

use crate::error::Result;
use crate::fee_balancing::FeeBalancingConfig;
use crate::providers::{
    ErasedProviders, MidnightProvider, ProofProvider, ProveTxConfig, PublicDataProvider,
    WalletProvider,
};
use crate::submit_call_tx::{submit_call_tx, PreSubmitTxHook, PrivateStateSerializer};
use crate::submit_insert_vk_tx::{submit_insert_verifier_key_tx, SubmitInsertVerifierKeyTxOptions};
use crate::submit_remove_vk_tx::{submit_remove_verifier_key_tx, SubmitRemoveVerifierKeyTxOptions};
use crate::submit_replace_authority_tx::{
    submit_replace_authority_tx, SubmitReplaceAuthorityTxOptions,
};
use crate::tx_model::{FinalizedCallTxData, UnsubmittedCallTxData};
use crate::tx_phase::{FinalizedTx, ProvenTx, UnprovenTx};
use crate::types::{CircuitId, FinalizedTxData, PrivateStateId, TransactionId, VerifierKey};
use crate::unproven_call_tx::{create_unproven_call_tx, BuildCallOptions};
use moonproof_runtime::ir::witnesses::Witnesses;
use moonproof_runtime::ir_executable::IrExecutable;
use moonproof_runtime_ir::RuntimeValue;

// =====================================================================
// ContractCalls — contract-specific call tx factory
// =====================================================================

/// Per-call options for maintenance methods on [`CircuitMaintenanceTx`]
/// and [`ContractMaintenanceTx`]. Bundles the chain-derived time +
/// network id + optional dust-fee balancing. Keeps the method
/// signatures readable.
#[derive(Debug, Clone)]
pub struct MaintenanceOptions {
    pub current_time: Timestamp,
    pub network_id: String,
    pub fee_balancing: Option<FeeBalancingConfig>,
}

/// Per-call options for [`ContractCalls::call`]. Bundles the
/// chain-derived time + network id + optional dust-fee balancing +
/// optional private-state plumbing into a single struct so the
/// method signature stays readable.
pub struct CallOptions {
    /// Chain-tip timestamp — used to derive the intent's TTL and
    /// passed to the circuit's `tblock` context value. Must be
    /// chain-derived (indexer's latest block time).
    pub current_time: Timestamp,
    /// Network id the transaction targets.
    pub network_id: String,
    /// Optional dust-fee balancing. Live-harness callers supply a
    /// [`FeeBalancingConfig`]; offline tests pass `None`.
    pub fee_balancing: Option<FeeBalancingConfig>,
    /// Override the circuit's initial private state. `None` means
    /// "load from the provider using
    /// [`ContractCalls::private_state_id`]".
    pub initial_private_state: Option<RuntimeValue>,
    /// Serializer for the circuit's next-private-state. Needed for
    /// private-state-aware contracts so the call tx can persist the
    /// post-call state on `SucceedEntirely`. `None` skips
    /// persistence — matches TS's "only persist when both id and
    /// provider are present" semantics.
    pub serialize_next_private_state: Option<PrivateStateSerializer>,
    /// Optional extra `(CoinPublicKey, EncPublicKey)` mappings for
    /// circuits that emit shielded outputs to recipients other than
    /// the calling wallet. Threaded into the
    /// [`zswap_state_to_offer`](crate::utils::zswap_utils::zswap_state_to_offer)
    /// resolver. Mirrors TS `additionalCoinEncPublicKeyMappings`.
    pub additional_coin_enc_public_key_mappings:
        Option<std::collections::HashMap<crate::types::CoinPublicKey, crate::types::EncPublicKey>>,
    /// Optional pre-submit hook.  See
    /// [`crate::submit_call_tx::PreSubmitTxHook`] — typically populated
    /// with the wallet-side shielded balancer
    /// (`moonproof_wallet::shielded::balance_contract_call_tx`) that
    /// closes the imbalance left by Compact's `receiveShielded(coin)`.
    pub pre_submit: Option<PreSubmitTxHook>,
}

impl Default for CallOptions {
    fn default() -> Self {
        Self {
            current_time: Timestamp::from_secs(0),
            network_id: String::new(),
            fee_balancing: None,
            initial_private_state: None,
            serialize_next_private_state: None,
            additional_coin_enc_public_key_mappings: None,
            pre_submit: None,
        }
    }
}

impl std::fmt::Debug for CallOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CallOptions")
            .field("current_time", &self.current_time)
            .field("network_id", &self.network_id)
            .field("fee_balancing", &self.fee_balancing.is_some())
            .field(
                "initial_private_state",
                &self.initial_private_state.is_some(),
            )
            .field(
                "serialize_next_private_state",
                &self.serialize_next_private_state.is_some(),
            )
            .finish_non_exhaustive()
    }
}

/// A contract-specific wrapper around the call-tx pipeline.
///
/// Port of TS `ContractCallsInterface<C>`. Each instance is bound to
/// one deployed contract (contract address + optional private state
/// id) and a providers bundle; calling
/// [`ContractCalls::call`](Self::call) routes through the submit
/// pipeline and returns the finalized tx data.
///
/// Concrete typed call-tx wrappers live at the caller's boundary — we
/// don't know circuit signatures at this layer, so the Rust API is
/// dynamically typed at the edge (via `AlignedValue`). Typed wrappers
/// are trivial to write on top (e.g. `counter.increment()` →
/// `call_tx.call(&CircuitId::new("increment"), vec![], ...)`).
pub struct ContractCalls<W: Witnesses + 'static> {
    providers: Arc<ErasedProviders>,
    executable: Arc<IrExecutable<W>>,
    contract_address: ContractAddress,
    private_state_id: Option<PrivateStateId>,
}

// Manual `Clone` impl — `#[derive(Clone)]` would add a `W: Clone`
// bound, but every field's clone is independent of `W`'s own Clone
// (the executable rides as `Arc<IrExecutable<W>>`, cloned via Arc).
// Hand-writing keeps the bound at `W: Witnesses + 'static`.
impl<W: Witnesses + 'static> Clone for ContractCalls<W> {
    fn clone(&self) -> Self {
        Self {
            providers: self.providers.clone(),
            executable: self.executable.clone(),
            contract_address: self.contract_address,
            private_state_id: self.private_state_id.clone(),
        }
    }
}

impl<W: Witnesses + 'static> std::fmt::Debug for ContractCalls<W> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ContractCalls")
            .field("contract_address", &self.contract_address)
            .field("private_state_id", &self.private_state_id)
            .finish_non_exhaustive()
    }
}

impl<W: Witnesses + 'static> ContractCalls<W> {
    /// Construct a new call-tx interface for `contract_address`.
    /// Port of TS `createContractCallsInterface`.
    #[must_use]
    pub fn new(
        providers: Arc<ErasedProviders>,
        executable: Arc<IrExecutable<W>>,
        contract_address: ContractAddress,
        private_state_id: Option<PrivateStateId>,
    ) -> Self {
        Self {
            providers,
            executable,
            contract_address,
            private_state_id,
        }
    }

    /// The contract address this interface is bound to.
    #[inline]
    #[must_use]
    pub fn contract_address(&self) -> &ContractAddress {
        &self.contract_address
    }

    /// The private state id this interface is bound to (if any).
    #[inline]
    #[must_use]
    pub fn private_state_id(&self) -> Option<&PrivateStateId> {
        self.private_state_id.as_ref()
    }

    /// Invoke `circuit_id` with `args`. Routes through
    /// [`submit_call_tx`] and returns the finalized call-tx data.
    ///
    /// Wire-level Rust equivalent of the TS variadic
    /// `contract.circuits.increment(...args)`. The Rust port is
    /// explicit about the per-call options — chain time, network id,
    /// fee balancing, optional private-state overrides — because the
    /// Rust RNG isn't implicit and we don't have a global "chain
    /// context" to thread from.
    ///
    /// Stage 1: build an unproven call tx. Runs the circuit
    /// off-chain via the bound executable, assembles the unproven
    /// `Transaction`, and returns the unsubmitted bundle. No proof is
    /// computed; no network calls are made.
    ///
    /// Pair with [`Self::prove`] / [`Self::balance`] /
    /// [`Self::submit`] / [`Self::submit_and_wait`] to drive the
    /// submission pipeline stage by stage. The one-shot [`Self::call`]
    /// chains all of these for callers that want a single entry
    /// point.
    pub async fn build_unproven<R>(
        &self,
        rng: &mut R,
        circuit_id: impl Into<CircuitId>,
        args: RuntimeValue,
        options: CallOptions,
    ) -> Result<UnsubmittedCallTxData>
    where
        R: Rng + CryptoRng,
    {
        let build_opts = self.build_call_options(circuit_id, args, options);
        Box::pin(create_unproven_call_tx(
            rng,
            self.executable.as_ref(),
            &self.providers,
            build_opts,
        ))
        .await
    }

    /// Stage 2: hand the unproven tx to the proof provider. Returns
    /// the proven tx phase. Apply any pre-prove balancing (e.g. the
    /// wallet-side shielded balancer
    /// `moonproof_wallet::shielded::balance_contract_call_tx`) to the
    /// `UnprovenTx` before passing it in here.
    pub async fn prove(&self, unproven: UnprovenTx) -> Result<ProvenTx> {
        self.providers
            .proof
            .prove_tx(unproven, &ProveTxConfig::default())
            .await
    }

    /// Stage 3: hand the proven tx to the wallet provider for fee
    /// balancing + sealing. Returns the wire-format finalized tx ready
    /// for submission. `ttl_ms = None` uses the wallet provider's
    /// default TTL (typically chain-now + 1h).
    pub async fn balance(&self, proven: ProvenTx, ttl_ms: Option<i64>) -> Result<FinalizedTx> {
        self.providers.wallet.balance_tx(proven, ttl_ms).await
    }

    /// Stage 4 (fire-and-forget): submit the finalized tx to the
    /// node, return the chain-assigned [`TransactionId`] without
    /// waiting for finalization. Pair with
    /// [`Self::wait_for_finalization`] when the caller needs the
    /// finalized tx data.
    pub async fn submit(&self, tx: FinalizedTx) -> Result<TransactionId> {
        self.providers.midnight.submit_tx(tx).await
    }

    /// Block until the indexer reports the tx as finalized. Pair
    /// with [`Self::submit`] when the caller wants to drive the wait
    /// separately.
    pub async fn wait_for_finalization(&self, tx_id: &TransactionId) -> Result<FinalizedTxData> {
        self.providers.public_data.watch_for_tx_data(tx_id).await
    }

    /// Stage 4 (one-shot): submit the finalized tx and wait for the
    /// indexer to report finalization. Equivalent to
    /// [`Self::submit`] followed by [`Self::wait_for_finalization`].
    pub async fn submit_and_wait(&self, tx: FinalizedTx) -> Result<FinalizedTxData> {
        let tx_id = self.submit(tx).await?;
        self.wait_for_finalization(&tx_id).await
    }

    /// One-shot: build → optionally pre-submit hook → prove → balance
    /// → submit → wait. The common case for "invoke a circuit and
    /// return the finalized tx data".
    ///
    /// `circuit_id: impl Into<CircuitId>` — accepts `&str`, `String`,
    /// or an owned `CircuitId`. `options.pre_submit` is applied
    /// between [`Self::build_unproven`] and [`Self::prove`];
    /// `options.serialize_next_private_state` is invoked on success
    /// to persist the next private state (when
    /// `private_state_id` is bound on this dispatcher).
    pub async fn call<R>(
        &self,
        rng: &mut R,
        circuit_id: impl Into<CircuitId>,
        args: RuntimeValue,
        options: CallOptions,
    ) -> Result<FinalizedCallTxData>
    where
        R: Rng + CryptoRng,
    {
        let outcome = self
            .call_with_optional_scope(rng, circuit_id, args, options, None)
            .await?;
        outcome
            .finalized
            .ok_or_else(|| crate::error::ContractRuntimeError::Provider {
                provider: "ContractCalls::call",
                message: "submit_call_tx returned no finalized data on the unscoped path"
                    .to_owned(),
            })
    }

    /// Like [`Self::call`] but accepts an optional scoped-tx context.
    /// When `tx_ctx = Some(ctx)`, the call is merged into the scope's
    /// queue and submission is deferred to the surrounding
    /// [`crate::with_contract_scoped_transaction`] closure exit. When
    /// `tx_ctx = None`, behaviour matches [`Self::call`].
    pub async fn call_with_optional_scope<R>(
        &self,
        rng: &mut R,
        circuit_id: impl Into<CircuitId>,
        args: RuntimeValue,
        options: CallOptions,
        tx_ctx: Option<&Arc<crate::transaction::TransactionContextImpl>>,
    ) -> Result<crate::submit_call_tx::CallTxOutcome>
    where
        R: Rng + CryptoRng,
    {
        let build_opts = self.build_call_options(circuit_id, args, options);
        Box::pin(submit_call_tx(
            rng,
            self.executable.as_ref(),
            &self.providers,
            build_opts,
            tx_ctx,
        ))
        .await
    }

    /// Lift the per-call [`CallOptions`] + circuit id + args into a
    /// full [`BuildCallOptions`] using the dispatcher's bound
    /// `contract_address` + `private_state_id`.
    fn build_call_options(
        &self,
        circuit_id: impl Into<CircuitId>,
        args: RuntimeValue,
        options: CallOptions,
    ) -> BuildCallOptions {
        BuildCallOptions {
            contract_address: self.contract_address,
            circuit_id: circuit_id.into(),
            args,
            private_state_id: self.private_state_id.clone(),
            initial_private_state: options.initial_private_state,
            network_id: options.network_id,
            current_time: options.current_time,
            fee_balancing: options.fee_balancing,
            additional_coin_enc_public_key_mappings: options
                .additional_coin_enc_public_key_mappings,
            serialize_next_private_state: options.serialize_next_private_state,
            pre_submit: options.pre_submit,
        }
    }
}

// =====================================================================
// CircuitMaintenanceTx — per-circuit VK maintenance
// =====================================================================

/// Port of TS `CircuitMaintenanceTxInterface`.
///
/// One instance per (contract, circuit id) pair. Exposes the two
/// circuit-level maintenance operations: remove the current verifier
/// key, or insert a new one.
#[derive(Clone)]
pub struct CircuitMaintenanceTx {
    providers: Arc<ErasedProviders>,
    contract_address: ContractAddress,
    circuit_id: CircuitId,
}

impl std::fmt::Debug for CircuitMaintenanceTx {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CircuitMaintenanceTx")
            .field("contract_address", &self.contract_address)
            .field("circuit_id", &self.circuit_id)
            .finish_non_exhaustive()
    }
}

impl CircuitMaintenanceTx {
    #[must_use]
    pub fn new(
        providers: Arc<ErasedProviders>,
        contract_address: ContractAddress,
        circuit_id: CircuitId,
    ) -> Self {
        Self {
            providers,
            contract_address,
            circuit_id,
        }
    }

    #[inline]
    #[must_use]
    pub fn contract_address(&self) -> &ContractAddress {
        &self.contract_address
    }

    #[inline]
    #[must_use]
    pub fn circuit_id(&self) -> &CircuitId {
        &self.circuit_id
    }

    /// Remove the current verifier key. Port of TS
    /// `removeVerifierKey()`. Delegated to
    /// [`crate::submit_remove_vk_tx::submit_remove_verifier_key_tx`].
    ///
    pub async fn remove_verifier_key<R>(
        &self,
        rng: &mut R,
        options: MaintenanceOptions,
    ) -> Result<FinalizedTxData>
    where
        R: Rng + CryptoRng,
    {
        submit_remove_verifier_key_tx(
            rng,
            &self.providers,
            SubmitRemoveVerifierKeyTxOptions {
                contract_address: self.contract_address,
                circuit_id: self.circuit_id.clone(),
                current_time: options.current_time,
                network_id: options.network_id,
                fee_balancing: options.fee_balancing,
            },
        )
        .await
    }

    /// Insert a new verifier key. Delegates to
    /// [`crate::submit_insert_vk_tx::submit_insert_verifier_key_tx`].
    pub async fn insert_verifier_key<R>(
        &self,
        rng: &mut R,
        new_vk: VerifierKey,
        options: MaintenanceOptions,
    ) -> Result<FinalizedTxData>
    where
        R: Rng + CryptoRng,
    {
        submit_insert_verifier_key_tx(
            rng,
            &self.providers,
            SubmitInsertVerifierKeyTxOptions {
                contract_address: self.contract_address,
                circuit_id: self.circuit_id.clone(),
                new_vk,
                current_time: options.current_time,
                network_id: options.network_id,
                fee_balancing: options.fee_balancing,
            },
        )
        .await
    }
}

/// A set of [`CircuitMaintenanceTx`] instances keyed by circuit id.
/// Port of TS `CircuitMaintenanceTxInterfaces<C>`.
///
/// Rust uses a `Vec<(CircuitId, CircuitMaintenanceTx)>` instead of a
/// map because preserving the insertion order from the contract's
/// `getProvableCircuitIds()` output is semantically meaningful for
/// maintenance UI flows (first-declared-first-shown).
#[derive(Debug, Clone)]
pub struct CircuitMaintenanceTxInterfaces {
    entries: indexmap::IndexMap<CircuitId, CircuitMaintenanceTx>,
}

impl CircuitMaintenanceTxInterfaces {
    /// Construct from any iterator of `(circuit_id, interface)`.
    /// Insertion order is preserved by the underlying `IndexMap`.
    #[must_use]
    pub fn new<I>(entries: I) -> Self
    where
        I: IntoIterator<Item = (CircuitId, CircuitMaintenanceTx)>,
    {
        Self {
            entries: entries.into_iter().collect(),
        }
    }

    /// Find the maintenance-tx interface for a circuit. Returns `None`
    /// if the circuit wasn't declared on the contract.
    #[must_use]
    pub fn get(&self, circuit_id: &CircuitId) -> Option<&CircuitMaintenanceTx> {
        self.entries.get(circuit_id)
    }

    /// Iterate in contract-declared order.
    pub fn iter(&self) -> impl Iterator<Item = (&CircuitId, &CircuitMaintenanceTx)> {
        self.entries.iter()
    }

    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

// =====================================================================
// ContractMaintenanceTx — contract-level maintenance
// =====================================================================

/// Port of TS `ContractMaintenanceTxInterface`. One operation:
/// `replaceAuthority(newAuthority)`.
#[derive(Clone)]
pub struct ContractMaintenanceTx {
    providers: Arc<ErasedProviders>,
    contract_address: ContractAddress,
}

impl std::fmt::Debug for ContractMaintenanceTx {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ContractMaintenanceTx")
            .field("contract_address", &self.contract_address)
            .finish_non_exhaustive()
    }
}

impl ContractMaintenanceTx {
    #[must_use]
    pub fn new(providers: Arc<ErasedProviders>, contract_address: ContractAddress) -> Self {
        Self {
            providers,
            contract_address,
        }
    }

    #[inline]
    #[must_use]
    pub fn contract_address(&self) -> &ContractAddress {
        &self.contract_address
    }

    /// Replace the contract's maintenance authority with a new
    /// signing key. Port of TS `replaceAuthority(newAuthority)`.
    /// Delegated to
    /// [`crate::submit_replace_authority_tx::submit_replace_authority_tx`].
    pub async fn replace_authority<R>(
        &self,
        rng: &mut R,
        new_authority: SigningKey,
        options: MaintenanceOptions,
    ) -> Result<FinalizedTxData>
    where
        R: Rng + CryptoRng,
    {
        submit_replace_authority_tx(
            rng,
            &self.providers,
            SubmitReplaceAuthorityTxOptions {
                contract_address: self.contract_address,
                new_authority,
                current_time: options.current_time,
                network_id: options.network_id,
                fee_balancing: options.fee_balancing,
            },
        )
        .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use moonproof_ledger::base_crypto::hash::HashOutput;

    fn dummy_address() -> ContractAddress {
        ContractAddress(HashOutput([0x11u8; 32]))
    }

    /// ports: `tx-interfaces.test.ts::createCircuitMaintenanceTxInterfaces::should create maintenance interfaces for all circuits`
    #[test]
    fn circuit_maintenance_tx_interfaces_preserves_order() {
        let providers = dummy_providers();
        let addr = dummy_address();
        let interfaces = CircuitMaintenanceTxInterfaces::new(vec![
            (
                CircuitId::new("b"),
                CircuitMaintenanceTx::new(providers.clone(), addr, CircuitId::new("b")),
            ),
            (
                CircuitId::new("a"),
                CircuitMaintenanceTx::new(providers.clone(), addr, CircuitId::new("a")),
            ),
            (
                CircuitId::new("c"),
                CircuitMaintenanceTx::new(providers, addr, CircuitId::new("c")),
            ),
        ]);
        let ids: Vec<_> = interfaces.iter().map(|(id, _)| id.as_str()).collect();
        assert_eq!(ids, vec!["b", "a", "c"]);
        assert_eq!(interfaces.len(), 3);
        assert!(!interfaces.is_empty());
    }

    /// ports: `tx-interfaces.test.ts::createCircuitMaintenanceTxInterface::should create circuit maintenance interface`
    /// ports: `tx-interfaces.test.ts::createCircuitMaintenanceTxInterface::should call removeVerifierKey function`
    /// ports: `tx-interfaces.test.ts::createCircuitMaintenanceTxInterface::should call insertVerifierKey function`
    /// (the get-by-id accessor is the call site every TS interface
    /// method goes through; the insert/remove paths are unit-tested
    /// against scripted providers in `submit_insert_vk_tx` /
    /// `submit_remove_vk_tx`.)
    #[test]
    fn circuit_maintenance_tx_interfaces_get_by_circuit_id() {
        let providers = dummy_providers();
        let addr = dummy_address();
        let interfaces = CircuitMaintenanceTxInterfaces::new(vec![(
            CircuitId::new("increment"),
            CircuitMaintenanceTx::new(providers, addr, CircuitId::new("increment")),
        )]);
        assert!(interfaces.get(&CircuitId::new("increment")).is_some());
        assert!(interfaces.get(&CircuitId::new("missing")).is_none());
    }

    /// ports: `tx-interfaces.test.ts::createContractMaintenanceTxInterface::should create contract maintenance interface`
    #[test]
    fn empty_maintenance_interfaces_are_empty() {
        let interfaces = CircuitMaintenanceTxInterfaces::new(vec![]);
        assert_eq!(interfaces.len(), 0);
        assert!(interfaces.is_empty());
    }

    // -----------------------------------------------------------------
    // Helpers
    // -----------------------------------------------------------------

    // A cheap way to stand up an `ErasedProviders` for layout-only
    // tests: route every trait method through panics.
    mod dummy {
        use super::*;
        use crate::providers::{
            logger::LogLevel, logger::LoggerProvider, MidnightProvider, PrivateStateProvider,
            ProofProvider, PublicDataProvider, WalletProvider, ZkConfigProvider,
        };

        #[derive(Debug)]
        pub(super) struct Dummy;

        macro_rules! dummy_call {
            () => {
                unimplemented!("dummy provider used in layout-only tests")
            };
        }

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

        #[moonproof_macros::async_trait]
        impl PublicDataProvider for Dummy {
            async fn query_contract_state(
                &self,
                _address: &ContractAddress,
                _at: Option<crate::types::ContractStateQueryAt>,
            ) -> crate::Result<
                Option<
                    moonproof_ledger::onchain_runtime::state::ContractState<
                        moonproof_ledger::storage::db::InMemoryDB,
                    >,
                >,
            > {
                dummy_call!()
            }
            async fn query_zswap_and_contract_state(
                &self,
                _address: &ContractAddress,
                _at: Option<crate::types::ContractStateQueryAt>,
            ) -> crate::Result<Option<crate::providers::public_data::ZSwapAndContractState>>
            {
                dummy_call!()
            }
            async fn query_deploy_contract_state(
                &self,
                _address: &ContractAddress,
            ) -> crate::Result<
                Option<
                    moonproof_ledger::onchain_runtime::state::ContractState<
                        moonproof_ledger::storage::db::InMemoryDB,
                    >,
                >,
            > {
                dummy_call!()
            }
            async fn query_unshielded_balances(
                &self,
                _address: &ContractAddress,
                _at: Option<crate::types::ContractStateQueryAt>,
            ) -> crate::Result<Option<crate::types::UnshieldedBalances>> {
                dummy_call!()
            }
            async fn watch_for_deploy_tx_data(
                &self,
                _address: &ContractAddress,
            ) -> crate::Result<crate::types::FinalizedTxData> {
                dummy_call!()
            }
            async fn watch_for_tx_data(
                &self,
                _tx_id: &crate::types::TransactionId,
            ) -> crate::Result<crate::types::FinalizedTxData> {
                dummy_call!()
            }
            async fn watch_for_contract_state(
                &self,
                _address: &ContractAddress,
            ) -> crate::Result<
                moonproof_ledger::onchain_runtime::state::ContractState<
                    moonproof_ledger::storage::db::InMemoryDB,
                >,
            > {
                dummy_call!()
            }
            async fn watch_for_unshielded_balances(
                &self,
                _address: &ContractAddress,
            ) -> crate::Result<crate::types::UnshieldedBalances> {
                dummy_call!()
            }
            async fn contract_state_stream(
                &self,
                _address: &ContractAddress,
                _start: crate::types::ContractStateStreamStart,
            ) -> crate::Result<
                crate::providers::public_data::PublicDataStream<
                    moonproof_ledger::onchain_runtime::state::ContractState<
                        moonproof_ledger::storage::db::InMemoryDB,
                    >,
                >,
            > {
                dummy_call!()
            }
            async fn unshielded_balances_stream(
                &self,
                _address: &ContractAddress,
                _start: crate::types::ContractStateStreamStart,
            ) -> crate::Result<
                crate::providers::public_data::PublicDataStream<crate::types::UnshieldedBalances>,
            > {
                dummy_call!()
            }
        }

        #[moonproof_macros::async_trait]
        impl ZkConfigProvider for Dummy {
            async fn get_zkir(&self, _circuit_id: &CircuitId) -> crate::Result<crate::types::Zkir> {
                dummy_call!()
            }
            async fn get_prover_key(
                &self,
                _circuit_id: &CircuitId,
            ) -> crate::Result<crate::types::ProverKey> {
                dummy_call!()
            }
            async fn get_verifier_key(
                &self,
                _circuit_id: &CircuitId,
            ) -> crate::Result<crate::types::VerifierKey> {
                dummy_call!()
            }
        }

        #[moonproof_macros::async_trait]
        impl ProofProvider for Dummy {
            async fn prove_tx(
                &self,
                _tx: crate::tx_phase::UnprovenTx,
                _config: &crate::providers::ProveTxConfig,
            ) -> crate::Result<crate::tx_phase::ProvenTx> {
                dummy_call!()
            }
        }

        #[moonproof_macros::async_trait]
        impl WalletProvider for Dummy {
            async fn balance_tx(
                &self,
                _tx: crate::tx_phase::ProvenTx,
                _ttl_ms: Option<i64>,
            ) -> crate::Result<crate::tx_phase::FinalizedTx> {
                dummy_call!()
            }
            fn coin_public_key(&self) -> crate::types::CoinPublicKey {
                dummy_call!()
            }
            fn encryption_public_key(&self) -> crate::types::EncPublicKey {
                dummy_call!()
            }
        }

        #[moonproof_macros::async_trait]
        impl MidnightProvider for Dummy {
            async fn submit_tx(
                &self,
                _tx: crate::tx_phase::FinalizedTx,
            ) -> crate::Result<crate::types::TransactionId> {
                dummy_call!()
            }
        }

        impl LoggerProvider for Dummy {
            fn log(&self, _level: LogLevel, _message: &str) {}
        }
    }

    fn dummy_providers() -> Arc<ErasedProviders> {
        let d = Arc::new(dummy::Dummy);
        Arc::new(
            ErasedProviders::builder()
                .private_state(d.clone())
                .public_data(d.clone())
                .zk_config(d.clone())
                .proof(d.clone())
                .wallet(d.clone())
                .midnight(d)
                .build(),
        )
    }
}