Skip to main content

moonproof_contracts/
tx_interfaces.rs

1//! Port of
2//! `@midnight-ntwrk/midnight-js-contracts/src/tx-interfaces.ts`.
3//!
4//! Factories that bind a specific deployed contract to the providers
5//! bundle and expose ergonomic call / maintenance entry points.
6//!
7//! # Shape differences from TS
8//!
9//! The TS `ContractCallsInterface<C>` is a mapped type keyed by
10//! circuit id, where each value is a typed variadic closure. Rust's
11//! generic system can't express "function type that depends on a key
12//! in a struct-level map", so the Rust port uses an explicit
13//! `call(circuit_id, args)` method on [`ContractCalls`]. Semantically
14//! equivalent — slightly more explicit at the call site.
15//!
16//! Maintenance interfaces are a 1:1 port.
17
18use std::sync::Arc;
19
20use moonproof_ledger::base_crypto::time::Timestamp;
21use moonproof_ledger::coin_structure::contract::ContractAddress;
22use moonproof_ledger::signatures::SigningKey;
23use rand::{CryptoRng, Rng};
24
25use crate::error::Result;
26use crate::fee_balancing::FeeBalancingConfig;
27use crate::providers::{
28    ErasedProviders, MidnightProvider, ProofProvider, ProveTxConfig, PublicDataProvider,
29    WalletProvider,
30};
31use crate::submit_call_tx::{submit_call_tx, PreSubmitTxHook, PrivateStateSerializer};
32use crate::submit_insert_vk_tx::{submit_insert_verifier_key_tx, SubmitInsertVerifierKeyTxOptions};
33use crate::submit_remove_vk_tx::{submit_remove_verifier_key_tx, SubmitRemoveVerifierKeyTxOptions};
34use crate::submit_replace_authority_tx::{
35    submit_replace_authority_tx, SubmitReplaceAuthorityTxOptions,
36};
37use crate::tx_model::{FinalizedCallTxData, UnsubmittedCallTxData};
38use crate::tx_phase::{FinalizedTx, ProvenTx, UnprovenTx};
39use crate::types::{CircuitId, FinalizedTxData, PrivateStateId, TransactionId, VerifierKey};
40use crate::unproven_call_tx::{create_unproven_call_tx, BuildCallOptions};
41use moonproof_runtime::ir::witnesses::Witnesses;
42use moonproof_runtime::ir_executable::IrExecutable;
43use moonproof_runtime_ir::RuntimeValue;
44
45// =====================================================================
46// ContractCalls — contract-specific call tx factory
47// =====================================================================
48
49/// Per-call options for maintenance methods on [`CircuitMaintenanceTx`]
50/// and [`ContractMaintenanceTx`]. Bundles the chain-derived time +
51/// network id + optional dust-fee balancing. Keeps the method
52/// signatures readable.
53#[derive(Debug, Clone)]
54pub struct MaintenanceOptions {
55    pub current_time: Timestamp,
56    pub network_id: String,
57    pub fee_balancing: Option<FeeBalancingConfig>,
58}
59
60/// Per-call options for [`ContractCalls::call`]. Bundles the
61/// chain-derived time + network id + optional dust-fee balancing +
62/// optional private-state plumbing into a single struct so the
63/// method signature stays readable.
64pub struct CallOptions {
65    /// Chain-tip timestamp — used to derive the intent's TTL and
66    /// passed to the circuit's `tblock` context value. Must be
67    /// chain-derived (indexer's latest block time).
68    pub current_time: Timestamp,
69    /// Network id the transaction targets.
70    pub network_id: String,
71    /// Optional dust-fee balancing. Live-harness callers supply a
72    /// [`FeeBalancingConfig`]; offline tests pass `None`.
73    pub fee_balancing: Option<FeeBalancingConfig>,
74    /// Override the circuit's initial private state. `None` means
75    /// "load from the provider using
76    /// [`ContractCalls::private_state_id`]".
77    pub initial_private_state: Option<RuntimeValue>,
78    /// Serializer for the circuit's next-private-state. Needed for
79    /// private-state-aware contracts so the call tx can persist the
80    /// post-call state on `SucceedEntirely`. `None` skips
81    /// persistence — matches TS's "only persist when both id and
82    /// provider are present" semantics.
83    pub serialize_next_private_state: Option<PrivateStateSerializer>,
84    /// Optional extra `(CoinPublicKey, EncPublicKey)` mappings for
85    /// circuits that emit shielded outputs to recipients other than
86    /// the calling wallet. Threaded into the
87    /// [`zswap_state_to_offer`](crate::utils::zswap_utils::zswap_state_to_offer)
88    /// resolver. Mirrors TS `additionalCoinEncPublicKeyMappings`.
89    pub additional_coin_enc_public_key_mappings:
90        Option<std::collections::HashMap<crate::types::CoinPublicKey, crate::types::EncPublicKey>>,
91    /// Optional pre-submit hook.  See
92    /// [`crate::submit_call_tx::PreSubmitTxHook`] — typically populated
93    /// with the wallet-side shielded balancer
94    /// (`moonproof_wallet::shielded::balance_contract_call_tx`) that
95    /// closes the imbalance left by Compact's `receiveShielded(coin)`.
96    pub pre_submit: Option<PreSubmitTxHook>,
97}
98
99impl Default for CallOptions {
100    fn default() -> Self {
101        Self {
102            current_time: Timestamp::from_secs(0),
103            network_id: String::new(),
104            fee_balancing: None,
105            initial_private_state: None,
106            serialize_next_private_state: None,
107            additional_coin_enc_public_key_mappings: None,
108            pre_submit: None,
109        }
110    }
111}
112
113impl std::fmt::Debug for CallOptions {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        f.debug_struct("CallOptions")
116            .field("current_time", &self.current_time)
117            .field("network_id", &self.network_id)
118            .field("fee_balancing", &self.fee_balancing.is_some())
119            .field(
120                "initial_private_state",
121                &self.initial_private_state.is_some(),
122            )
123            .field(
124                "serialize_next_private_state",
125                &self.serialize_next_private_state.is_some(),
126            )
127            .finish_non_exhaustive()
128    }
129}
130
131/// A contract-specific wrapper around the call-tx pipeline.
132///
133/// Port of TS `ContractCallsInterface<C>`. Each instance is bound to
134/// one deployed contract (contract address + optional private state
135/// id) and a providers bundle; calling
136/// [`ContractCalls::call`](Self::call) routes through the submit
137/// pipeline and returns the finalized tx data.
138///
139/// Concrete typed call-tx wrappers live at the caller's boundary — we
140/// don't know circuit signatures at this layer, so the Rust API is
141/// dynamically typed at the edge (via `AlignedValue`). Typed wrappers
142/// are trivial to write on top (e.g. `counter.increment()` →
143/// `call_tx.call(&CircuitId::new("increment"), vec![], ...)`).
144pub struct ContractCalls<W: Witnesses + 'static> {
145    providers: Arc<ErasedProviders>,
146    executable: Arc<IrExecutable<W>>,
147    contract_address: ContractAddress,
148    private_state_id: Option<PrivateStateId>,
149}
150
151// Manual `Clone` impl — `#[derive(Clone)]` would add a `W: Clone`
152// bound, but every field's clone is independent of `W`'s own Clone
153// (the executable rides as `Arc<IrExecutable<W>>`, cloned via Arc).
154// Hand-writing keeps the bound at `W: Witnesses + 'static`.
155impl<W: Witnesses + 'static> Clone for ContractCalls<W> {
156    fn clone(&self) -> Self {
157        Self {
158            providers: self.providers.clone(),
159            executable: self.executable.clone(),
160            contract_address: self.contract_address,
161            private_state_id: self.private_state_id.clone(),
162        }
163    }
164}
165
166impl<W: Witnesses + 'static> std::fmt::Debug for ContractCalls<W> {
167    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168        f.debug_struct("ContractCalls")
169            .field("contract_address", &self.contract_address)
170            .field("private_state_id", &self.private_state_id)
171            .finish_non_exhaustive()
172    }
173}
174
175impl<W: Witnesses + 'static> ContractCalls<W> {
176    /// Construct a new call-tx interface for `contract_address`.
177    /// Port of TS `createContractCallsInterface`.
178    #[must_use]
179    pub fn new(
180        providers: Arc<ErasedProviders>,
181        executable: Arc<IrExecutable<W>>,
182        contract_address: ContractAddress,
183        private_state_id: Option<PrivateStateId>,
184    ) -> Self {
185        Self {
186            providers,
187            executable,
188            contract_address,
189            private_state_id,
190        }
191    }
192
193    /// The contract address this interface is bound to.
194    #[inline]
195    #[must_use]
196    pub fn contract_address(&self) -> &ContractAddress {
197        &self.contract_address
198    }
199
200    /// The private state id this interface is bound to (if any).
201    #[inline]
202    #[must_use]
203    pub fn private_state_id(&self) -> Option<&PrivateStateId> {
204        self.private_state_id.as_ref()
205    }
206
207    /// Invoke `circuit_id` with `args`. Routes through
208    /// [`submit_call_tx`] and returns the finalized call-tx data.
209    ///
210    /// Wire-level Rust equivalent of the TS variadic
211    /// `contract.circuits.increment(...args)`. The Rust port is
212    /// explicit about the per-call options — chain time, network id,
213    /// fee balancing, optional private-state overrides — because the
214    /// Rust RNG isn't implicit and we don't have a global "chain
215    /// context" to thread from.
216    ///
217    /// Stage 1: build an unproven call tx. Runs the circuit
218    /// off-chain via the bound executable, assembles the unproven
219    /// `Transaction`, and returns the unsubmitted bundle. No proof is
220    /// computed; no network calls are made.
221    ///
222    /// Pair with [`Self::prove`] / [`Self::balance`] /
223    /// [`Self::submit`] / [`Self::submit_and_wait`] to drive the
224    /// submission pipeline stage by stage. The one-shot [`Self::call`]
225    /// chains all of these for callers that want a single entry
226    /// point.
227    pub async fn build_unproven<R>(
228        &self,
229        rng: &mut R,
230        circuit_id: impl Into<CircuitId>,
231        args: RuntimeValue,
232        options: CallOptions,
233    ) -> Result<UnsubmittedCallTxData>
234    where
235        R: Rng + CryptoRng,
236    {
237        let build_opts = self.build_call_options(circuit_id, args, options);
238        Box::pin(create_unproven_call_tx(
239            rng,
240            self.executable.as_ref(),
241            &self.providers,
242            build_opts,
243        ))
244        .await
245    }
246
247    /// Stage 2: hand the unproven tx to the proof provider. Returns
248    /// the proven tx phase. Apply any pre-prove balancing (e.g. the
249    /// wallet-side shielded balancer
250    /// `moonproof_wallet::shielded::balance_contract_call_tx`) to the
251    /// `UnprovenTx` before passing it in here.
252    pub async fn prove(&self, unproven: UnprovenTx) -> Result<ProvenTx> {
253        self.providers
254            .proof
255            .prove_tx(unproven, &ProveTxConfig::default())
256            .await
257    }
258
259    /// Stage 3: hand the proven tx to the wallet provider for fee
260    /// balancing + sealing. Returns the wire-format finalized tx ready
261    /// for submission. `ttl_ms = None` uses the wallet provider's
262    /// default TTL (typically chain-now + 1h).
263    pub async fn balance(&self, proven: ProvenTx, ttl_ms: Option<i64>) -> Result<FinalizedTx> {
264        self.providers.wallet.balance_tx(proven, ttl_ms).await
265    }
266
267    /// Stage 4 (fire-and-forget): submit the finalized tx to the
268    /// node, return the chain-assigned [`TransactionId`] without
269    /// waiting for finalization. Pair with
270    /// [`Self::wait_for_finalization`] when the caller needs the
271    /// finalized tx data.
272    pub async fn submit(&self, tx: FinalizedTx) -> Result<TransactionId> {
273        self.providers.midnight.submit_tx(tx).await
274    }
275
276    /// Block until the indexer reports the tx as finalized. Pair
277    /// with [`Self::submit`] when the caller wants to drive the wait
278    /// separately.
279    pub async fn wait_for_finalization(&self, tx_id: &TransactionId) -> Result<FinalizedTxData> {
280        self.providers.public_data.watch_for_tx_data(tx_id).await
281    }
282
283    /// Stage 4 (one-shot): submit the finalized tx and wait for the
284    /// indexer to report finalization. Equivalent to
285    /// [`Self::submit`] followed by [`Self::wait_for_finalization`].
286    pub async fn submit_and_wait(&self, tx: FinalizedTx) -> Result<FinalizedTxData> {
287        let tx_id = self.submit(tx).await?;
288        self.wait_for_finalization(&tx_id).await
289    }
290
291    /// One-shot: build → optionally pre-submit hook → prove → balance
292    /// → submit → wait. The common case for "invoke a circuit and
293    /// return the finalized tx data".
294    ///
295    /// `circuit_id: impl Into<CircuitId>` — accepts `&str`, `String`,
296    /// or an owned `CircuitId`. `options.pre_submit` is applied
297    /// between [`Self::build_unproven`] and [`Self::prove`];
298    /// `options.serialize_next_private_state` is invoked on success
299    /// to persist the next private state (when
300    /// `private_state_id` is bound on this dispatcher).
301    pub async fn call<R>(
302        &self,
303        rng: &mut R,
304        circuit_id: impl Into<CircuitId>,
305        args: RuntimeValue,
306        options: CallOptions,
307    ) -> Result<FinalizedCallTxData>
308    where
309        R: Rng + CryptoRng,
310    {
311        let outcome = self
312            .call_with_optional_scope(rng, circuit_id, args, options, None)
313            .await?;
314        outcome
315            .finalized
316            .ok_or_else(|| crate::error::ContractRuntimeError::Provider {
317                provider: "ContractCalls::call",
318                message: "submit_call_tx returned no finalized data on the unscoped path"
319                    .to_owned(),
320            })
321    }
322
323    /// Like [`Self::call`] but accepts an optional scoped-tx context.
324    /// When `tx_ctx = Some(ctx)`, the call is merged into the scope's
325    /// queue and submission is deferred to the surrounding
326    /// [`crate::with_contract_scoped_transaction`] closure exit. When
327    /// `tx_ctx = None`, behaviour matches [`Self::call`].
328    pub async fn call_with_optional_scope<R>(
329        &self,
330        rng: &mut R,
331        circuit_id: impl Into<CircuitId>,
332        args: RuntimeValue,
333        options: CallOptions,
334        tx_ctx: Option<&Arc<crate::transaction::TransactionContextImpl>>,
335    ) -> Result<crate::submit_call_tx::CallTxOutcome>
336    where
337        R: Rng + CryptoRng,
338    {
339        let build_opts = self.build_call_options(circuit_id, args, options);
340        Box::pin(submit_call_tx(
341            rng,
342            self.executable.as_ref(),
343            &self.providers,
344            build_opts,
345            tx_ctx,
346        ))
347        .await
348    }
349
350    /// Lift the per-call [`CallOptions`] + circuit id + args into a
351    /// full [`BuildCallOptions`] using the dispatcher's bound
352    /// `contract_address` + `private_state_id`.
353    fn build_call_options(
354        &self,
355        circuit_id: impl Into<CircuitId>,
356        args: RuntimeValue,
357        options: CallOptions,
358    ) -> BuildCallOptions {
359        BuildCallOptions {
360            contract_address: self.contract_address,
361            circuit_id: circuit_id.into(),
362            args,
363            private_state_id: self.private_state_id.clone(),
364            initial_private_state: options.initial_private_state,
365            network_id: options.network_id,
366            current_time: options.current_time,
367            fee_balancing: options.fee_balancing,
368            additional_coin_enc_public_key_mappings: options
369                .additional_coin_enc_public_key_mappings,
370            serialize_next_private_state: options.serialize_next_private_state,
371            pre_submit: options.pre_submit,
372        }
373    }
374}
375
376// =====================================================================
377// CircuitMaintenanceTx — per-circuit VK maintenance
378// =====================================================================
379
380/// Port of TS `CircuitMaintenanceTxInterface`.
381///
382/// One instance per (contract, circuit id) pair. Exposes the two
383/// circuit-level maintenance operations: remove the current verifier
384/// key, or insert a new one.
385#[derive(Clone)]
386pub struct CircuitMaintenanceTx {
387    providers: Arc<ErasedProviders>,
388    contract_address: ContractAddress,
389    circuit_id: CircuitId,
390}
391
392impl std::fmt::Debug for CircuitMaintenanceTx {
393    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
394        f.debug_struct("CircuitMaintenanceTx")
395            .field("contract_address", &self.contract_address)
396            .field("circuit_id", &self.circuit_id)
397            .finish_non_exhaustive()
398    }
399}
400
401impl CircuitMaintenanceTx {
402    #[must_use]
403    pub fn new(
404        providers: Arc<ErasedProviders>,
405        contract_address: ContractAddress,
406        circuit_id: CircuitId,
407    ) -> Self {
408        Self {
409            providers,
410            contract_address,
411            circuit_id,
412        }
413    }
414
415    #[inline]
416    #[must_use]
417    pub fn contract_address(&self) -> &ContractAddress {
418        &self.contract_address
419    }
420
421    #[inline]
422    #[must_use]
423    pub fn circuit_id(&self) -> &CircuitId {
424        &self.circuit_id
425    }
426
427    /// Remove the current verifier key. Port of TS
428    /// `removeVerifierKey()`. Delegated to
429    /// [`crate::submit_remove_vk_tx::submit_remove_verifier_key_tx`].
430    ///
431    pub async fn remove_verifier_key<R>(
432        &self,
433        rng: &mut R,
434        options: MaintenanceOptions,
435    ) -> Result<FinalizedTxData>
436    where
437        R: Rng + CryptoRng,
438    {
439        submit_remove_verifier_key_tx(
440            rng,
441            &self.providers,
442            SubmitRemoveVerifierKeyTxOptions {
443                contract_address: self.contract_address,
444                circuit_id: self.circuit_id.clone(),
445                current_time: options.current_time,
446                network_id: options.network_id,
447                fee_balancing: options.fee_balancing,
448            },
449        )
450        .await
451    }
452
453    /// Insert a new verifier key. Delegates to
454    /// [`crate::submit_insert_vk_tx::submit_insert_verifier_key_tx`].
455    pub async fn insert_verifier_key<R>(
456        &self,
457        rng: &mut R,
458        new_vk: VerifierKey,
459        options: MaintenanceOptions,
460    ) -> Result<FinalizedTxData>
461    where
462        R: Rng + CryptoRng,
463    {
464        submit_insert_verifier_key_tx(
465            rng,
466            &self.providers,
467            SubmitInsertVerifierKeyTxOptions {
468                contract_address: self.contract_address,
469                circuit_id: self.circuit_id.clone(),
470                new_vk,
471                current_time: options.current_time,
472                network_id: options.network_id,
473                fee_balancing: options.fee_balancing,
474            },
475        )
476        .await
477    }
478}
479
480/// A set of [`CircuitMaintenanceTx`] instances keyed by circuit id.
481/// Port of TS `CircuitMaintenanceTxInterfaces<C>`.
482///
483/// Rust uses a `Vec<(CircuitId, CircuitMaintenanceTx)>` instead of a
484/// map because preserving the insertion order from the contract's
485/// `getProvableCircuitIds()` output is semantically meaningful for
486/// maintenance UI flows (first-declared-first-shown).
487#[derive(Debug, Clone)]
488pub struct CircuitMaintenanceTxInterfaces {
489    entries: indexmap::IndexMap<CircuitId, CircuitMaintenanceTx>,
490}
491
492impl CircuitMaintenanceTxInterfaces {
493    /// Construct from any iterator of `(circuit_id, interface)`.
494    /// Insertion order is preserved by the underlying `IndexMap`.
495    #[must_use]
496    pub fn new<I>(entries: I) -> Self
497    where
498        I: IntoIterator<Item = (CircuitId, CircuitMaintenanceTx)>,
499    {
500        Self {
501            entries: entries.into_iter().collect(),
502        }
503    }
504
505    /// Find the maintenance-tx interface for a circuit. Returns `None`
506    /// if the circuit wasn't declared on the contract.
507    #[must_use]
508    pub fn get(&self, circuit_id: &CircuitId) -> Option<&CircuitMaintenanceTx> {
509        self.entries.get(circuit_id)
510    }
511
512    /// Iterate in contract-declared order.
513    pub fn iter(&self) -> impl Iterator<Item = (&CircuitId, &CircuitMaintenanceTx)> {
514        self.entries.iter()
515    }
516
517    #[inline]
518    #[must_use]
519    pub fn len(&self) -> usize {
520        self.entries.len()
521    }
522
523    #[inline]
524    #[must_use]
525    pub fn is_empty(&self) -> bool {
526        self.entries.is_empty()
527    }
528}
529
530// =====================================================================
531// ContractMaintenanceTx — contract-level maintenance
532// =====================================================================
533
534/// Port of TS `ContractMaintenanceTxInterface`. One operation:
535/// `replaceAuthority(newAuthority)`.
536#[derive(Clone)]
537pub struct ContractMaintenanceTx {
538    providers: Arc<ErasedProviders>,
539    contract_address: ContractAddress,
540}
541
542impl std::fmt::Debug for ContractMaintenanceTx {
543    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
544        f.debug_struct("ContractMaintenanceTx")
545            .field("contract_address", &self.contract_address)
546            .finish_non_exhaustive()
547    }
548}
549
550impl ContractMaintenanceTx {
551    #[must_use]
552    pub fn new(providers: Arc<ErasedProviders>, contract_address: ContractAddress) -> Self {
553        Self {
554            providers,
555            contract_address,
556        }
557    }
558
559    #[inline]
560    #[must_use]
561    pub fn contract_address(&self) -> &ContractAddress {
562        &self.contract_address
563    }
564
565    /// Replace the contract's maintenance authority with a new
566    /// signing key. Port of TS `replaceAuthority(newAuthority)`.
567    /// Delegated to
568    /// [`crate::submit_replace_authority_tx::submit_replace_authority_tx`].
569    pub async fn replace_authority<R>(
570        &self,
571        rng: &mut R,
572        new_authority: SigningKey,
573        options: MaintenanceOptions,
574    ) -> Result<FinalizedTxData>
575    where
576        R: Rng + CryptoRng,
577    {
578        submit_replace_authority_tx(
579            rng,
580            &self.providers,
581            SubmitReplaceAuthorityTxOptions {
582                contract_address: self.contract_address,
583                new_authority,
584                current_time: options.current_time,
585                network_id: options.network_id,
586                fee_balancing: options.fee_balancing,
587            },
588        )
589        .await
590    }
591}
592
593#[cfg(test)]
594mod tests {
595    use super::*;
596    use moonproof_ledger::base_crypto::hash::HashOutput;
597
598    fn dummy_address() -> ContractAddress {
599        ContractAddress(HashOutput([0x11u8; 32]))
600    }
601
602    /// ports: `tx-interfaces.test.ts::createCircuitMaintenanceTxInterfaces::should create maintenance interfaces for all circuits`
603    #[test]
604    fn circuit_maintenance_tx_interfaces_preserves_order() {
605        let providers = dummy_providers();
606        let addr = dummy_address();
607        let interfaces = CircuitMaintenanceTxInterfaces::new(vec![
608            (
609                CircuitId::new("b"),
610                CircuitMaintenanceTx::new(providers.clone(), addr, CircuitId::new("b")),
611            ),
612            (
613                CircuitId::new("a"),
614                CircuitMaintenanceTx::new(providers.clone(), addr, CircuitId::new("a")),
615            ),
616            (
617                CircuitId::new("c"),
618                CircuitMaintenanceTx::new(providers, addr, CircuitId::new("c")),
619            ),
620        ]);
621        let ids: Vec<_> = interfaces.iter().map(|(id, _)| id.as_str()).collect();
622        assert_eq!(ids, vec!["b", "a", "c"]);
623        assert_eq!(interfaces.len(), 3);
624        assert!(!interfaces.is_empty());
625    }
626
627    /// ports: `tx-interfaces.test.ts::createCircuitMaintenanceTxInterface::should create circuit maintenance interface`
628    /// ports: `tx-interfaces.test.ts::createCircuitMaintenanceTxInterface::should call removeVerifierKey function`
629    /// ports: `tx-interfaces.test.ts::createCircuitMaintenanceTxInterface::should call insertVerifierKey function`
630    /// (the get-by-id accessor is the call site every TS interface
631    /// method goes through; the insert/remove paths are unit-tested
632    /// against scripted providers in `submit_insert_vk_tx` /
633    /// `submit_remove_vk_tx`.)
634    #[test]
635    fn circuit_maintenance_tx_interfaces_get_by_circuit_id() {
636        let providers = dummy_providers();
637        let addr = dummy_address();
638        let interfaces = CircuitMaintenanceTxInterfaces::new(vec![(
639            CircuitId::new("increment"),
640            CircuitMaintenanceTx::new(providers, addr, CircuitId::new("increment")),
641        )]);
642        assert!(interfaces.get(&CircuitId::new("increment")).is_some());
643        assert!(interfaces.get(&CircuitId::new("missing")).is_none());
644    }
645
646    /// ports: `tx-interfaces.test.ts::createContractMaintenanceTxInterface::should create contract maintenance interface`
647    #[test]
648    fn empty_maintenance_interfaces_are_empty() {
649        let interfaces = CircuitMaintenanceTxInterfaces::new(vec![]);
650        assert_eq!(interfaces.len(), 0);
651        assert!(interfaces.is_empty());
652    }
653
654    // -----------------------------------------------------------------
655    // Helpers
656    // -----------------------------------------------------------------
657
658    // A cheap way to stand up an `ErasedProviders` for layout-only
659    // tests: route every trait method through panics.
660    mod dummy {
661        use super::*;
662        use crate::providers::{
663            logger::LogLevel, logger::LoggerProvider, MidnightProvider, PrivateStateProvider,
664            ProofProvider, PublicDataProvider, WalletProvider, ZkConfigProvider,
665        };
666
667        #[derive(Debug)]
668        pub(super) struct Dummy;
669
670        macro_rules! dummy_call {
671            () => {
672                unimplemented!("dummy provider used in layout-only tests")
673            };
674        }
675
676        #[moonproof_macros::async_trait]
677        impl PrivateStateProvider for Dummy {
678            async fn set_contract_address(&self, _address: &ContractAddress) -> crate::Result<()> {
679                dummy_call!()
680            }
681            async fn set(
682                &self,
683                _private_state_id: &PrivateStateId,
684                _state: Vec<u8>,
685            ) -> crate::Result<()> {
686                dummy_call!()
687            }
688            async fn get(
689                &self,
690                _private_state_id: &PrivateStateId,
691            ) -> crate::Result<Option<Vec<u8>>> {
692                dummy_call!()
693            }
694            async fn remove(&self, _private_state_id: &PrivateStateId) -> crate::Result<()> {
695                dummy_call!()
696            }
697            async fn clear(&self) -> crate::Result<()> {
698                dummy_call!()
699            }
700            async fn set_signing_key(
701                &self,
702                _address: &ContractAddress,
703                _signing_key: SigningKey,
704            ) -> crate::Result<()> {
705                dummy_call!()
706            }
707            async fn get_signing_key(
708                &self,
709                _address: &ContractAddress,
710            ) -> crate::Result<Option<SigningKey>> {
711                dummy_call!()
712            }
713            async fn remove_signing_key(&self, _address: &ContractAddress) -> crate::Result<()> {
714                dummy_call!()
715            }
716            async fn clear_signing_keys(&self) -> crate::Result<()> {
717                dummy_call!()
718            }
719            async fn export_private_states(
720                &self,
721                _options: &crate::providers::ExportPrivateStatesOptions,
722            ) -> crate::Result<crate::providers::PrivateStateExport> {
723                dummy_call!()
724            }
725            async fn import_private_states(
726                &self,
727                _export: &crate::providers::PrivateStateExport,
728                _options: &crate::providers::ImportPrivateStatesOptions,
729            ) -> crate::Result<crate::providers::ImportPrivateStatesResult> {
730                dummy_call!()
731            }
732            async fn export_signing_keys(
733                &self,
734                _options: &crate::providers::private_state::ExportSigningKeysOptions,
735            ) -> crate::Result<crate::providers::SigningKeyExport> {
736                dummy_call!()
737            }
738            async fn import_signing_keys(
739                &self,
740                _export: &crate::providers::SigningKeyExport,
741                _options: &crate::providers::private_state::ImportSigningKeysOptions,
742            ) -> crate::Result<crate::providers::private_state::ImportSigningKeysResult>
743            {
744                dummy_call!()
745            }
746        }
747
748        #[moonproof_macros::async_trait]
749        impl PublicDataProvider for Dummy {
750            async fn query_contract_state(
751                &self,
752                _address: &ContractAddress,
753                _at: Option<crate::types::ContractStateQueryAt>,
754            ) -> crate::Result<
755                Option<
756                    moonproof_ledger::onchain_runtime::state::ContractState<
757                        moonproof_ledger::storage::db::InMemoryDB,
758                    >,
759                >,
760            > {
761                dummy_call!()
762            }
763            async fn query_zswap_and_contract_state(
764                &self,
765                _address: &ContractAddress,
766                _at: Option<crate::types::ContractStateQueryAt>,
767            ) -> crate::Result<Option<crate::providers::public_data::ZSwapAndContractState>>
768            {
769                dummy_call!()
770            }
771            async fn query_deploy_contract_state(
772                &self,
773                _address: &ContractAddress,
774            ) -> crate::Result<
775                Option<
776                    moonproof_ledger::onchain_runtime::state::ContractState<
777                        moonproof_ledger::storage::db::InMemoryDB,
778                    >,
779                >,
780            > {
781                dummy_call!()
782            }
783            async fn query_unshielded_balances(
784                &self,
785                _address: &ContractAddress,
786                _at: Option<crate::types::ContractStateQueryAt>,
787            ) -> crate::Result<Option<crate::types::UnshieldedBalances>> {
788                dummy_call!()
789            }
790            async fn watch_for_deploy_tx_data(
791                &self,
792                _address: &ContractAddress,
793            ) -> crate::Result<crate::types::FinalizedTxData> {
794                dummy_call!()
795            }
796            async fn watch_for_tx_data(
797                &self,
798                _tx_id: &crate::types::TransactionId,
799            ) -> crate::Result<crate::types::FinalizedTxData> {
800                dummy_call!()
801            }
802            async fn watch_for_contract_state(
803                &self,
804                _address: &ContractAddress,
805            ) -> crate::Result<
806                moonproof_ledger::onchain_runtime::state::ContractState<
807                    moonproof_ledger::storage::db::InMemoryDB,
808                >,
809            > {
810                dummy_call!()
811            }
812            async fn watch_for_unshielded_balances(
813                &self,
814                _address: &ContractAddress,
815            ) -> crate::Result<crate::types::UnshieldedBalances> {
816                dummy_call!()
817            }
818            async fn contract_state_stream(
819                &self,
820                _address: &ContractAddress,
821                _start: crate::types::ContractStateStreamStart,
822            ) -> crate::Result<
823                crate::providers::public_data::PublicDataStream<
824                    moonproof_ledger::onchain_runtime::state::ContractState<
825                        moonproof_ledger::storage::db::InMemoryDB,
826                    >,
827                >,
828            > {
829                dummy_call!()
830            }
831            async fn unshielded_balances_stream(
832                &self,
833                _address: &ContractAddress,
834                _start: crate::types::ContractStateStreamStart,
835            ) -> crate::Result<
836                crate::providers::public_data::PublicDataStream<crate::types::UnshieldedBalances>,
837            > {
838                dummy_call!()
839            }
840        }
841
842        #[moonproof_macros::async_trait]
843        impl ZkConfigProvider for Dummy {
844            async fn get_zkir(&self, _circuit_id: &CircuitId) -> crate::Result<crate::types::Zkir> {
845                dummy_call!()
846            }
847            async fn get_prover_key(
848                &self,
849                _circuit_id: &CircuitId,
850            ) -> crate::Result<crate::types::ProverKey> {
851                dummy_call!()
852            }
853            async fn get_verifier_key(
854                &self,
855                _circuit_id: &CircuitId,
856            ) -> crate::Result<crate::types::VerifierKey> {
857                dummy_call!()
858            }
859        }
860
861        #[moonproof_macros::async_trait]
862        impl ProofProvider for Dummy {
863            async fn prove_tx(
864                &self,
865                _tx: crate::tx_phase::UnprovenTx,
866                _config: &crate::providers::ProveTxConfig,
867            ) -> crate::Result<crate::tx_phase::ProvenTx> {
868                dummy_call!()
869            }
870        }
871
872        #[moonproof_macros::async_trait]
873        impl WalletProvider for Dummy {
874            async fn balance_tx(
875                &self,
876                _tx: crate::tx_phase::ProvenTx,
877                _ttl_ms: Option<i64>,
878            ) -> crate::Result<crate::tx_phase::FinalizedTx> {
879                dummy_call!()
880            }
881            fn coin_public_key(&self) -> crate::types::CoinPublicKey {
882                dummy_call!()
883            }
884            fn encryption_public_key(&self) -> crate::types::EncPublicKey {
885                dummy_call!()
886            }
887        }
888
889        #[moonproof_macros::async_trait]
890        impl MidnightProvider for Dummy {
891            async fn submit_tx(
892                &self,
893                _tx: crate::tx_phase::FinalizedTx,
894            ) -> crate::Result<crate::types::TransactionId> {
895                dummy_call!()
896            }
897        }
898
899        impl LoggerProvider for Dummy {
900            fn log(&self, _level: LogLevel, _message: &str) {}
901        }
902    }
903
904    fn dummy_providers() -> Arc<ErasedProviders> {
905        let d = Arc::new(dummy::Dummy);
906        Arc::new(
907            ErasedProviders::builder()
908                .private_state(d.clone())
909                .public_data(d.clone())
910                .zk_config(d.clone())
911                .proof(d.clone())
912                .wallet(d.clone())
913                .midnight(d)
914                .build(),
915        )
916    }
917}