Skip to main content

moonproof_contracts/
contract.rs

1//! Contract handle + lifecycle entry points.
2//!
3//! Brings together:
4//! - [`Contract`] — typed handle returned by either lifecycle path,
5//!   exposing the per-circuit call interface + maintenance interfaces.
6//! - [`deploy_contract`] / [`DeployOptions`] — submit a fresh
7//!   deploy tx + wait for finalization, returning [`Contract::Deployed`].
8//! - [`find_deployed_contract`] / [`FindDeployedContractOptions`] —
9//!   attach to an already-deployed contract by address, verifying the
10//!   on-chain operations table matches the local executable's verifier
11//!   keys, returning [`Contract::Found`].
12//! - [`verify_contract_state`] / [`verifier_keys_equal`] — vk-equality
13//!   helpers used by `find_deployed_contract` and exposed for callers
14//!   that want to validate a state without loading the full contract.
15//!
16//! Port of `@midnight-ntwrk/midnight-js-contracts/src/{deploy-contract,
17//! find-deployed-contract}.ts`. The two TS files merge cleanly: deploy
18//! and find produce the same `Contract<C>` shape on the JS side, and
19//! `verifyContractState` is shared between them.
20
21use std::sync::Arc;
22
23use moonproof_ledger::coin_structure::coin::Info as ShieldedCoinInfo;
24use moonproof_ledger::coin_structure::contract::ContractAddress;
25use moonproof_ledger::onchain_runtime::state::{ContractState, EntryPointBuf};
26use moonproof_ledger::signatures::SigningKey;
27use moonproof_ledger::storage::db::InMemoryDB;
28use moonproof_runtime::ir::witnesses::Witnesses;
29use moonproof_runtime::ir_executable::IrExecutable;
30use moonproof_runtime_ir::RuntimeValue;
31use rand::{CryptoRng, Rng};
32
33use crate::error::{ContractRuntimeError, ContractsError, Result};
34use crate::providers::ErasedProviders;
35use crate::submit_deploy_tx::submit_deploy_tx;
36use crate::tx_interfaces::{
37    CallOptions, CircuitMaintenanceTx, CircuitMaintenanceTxInterfaces, ContractCalls,
38    ContractMaintenanceTx,
39};
40use crate::tx_phase::UnprovenTx;
41use crate::types::{CircuitId, FinalizedTxData, PrivateStateId, VerifierKey};
42pub use crate::unproven_deploy_tx::DeployOptions;
43use crate::utils::zswap_utils::CompactZswapLocalState;
44
45// =====================================================================
46// Contract handle
47// =====================================================================
48
49/// A contract handle bound to providers + executable.
50///
51/// Two variants:
52/// - [`Contract::Deployed`] — produced by [`deploy_contract`].
53///   Carries the full deploy-time payload (initial private state,
54///   initial zswap local state, the unproven tx still in hand,
55///   shielded new-coins) on top of the resolvable shared fields.
56/// - [`Contract::Found`] — produced by [`find_deployed_contract`].
57///   Carries only what the on-chain state + locally-stored signing
58///   key can re-derive. Deploy-time private payload is unavailable on
59///   this path; pattern-match on [`Contract::Deployed`] to reach for
60///   those fields.
61///
62/// Shared accessor methods cover the fields every consumer needs
63/// (address, finalized tx, call / maintenance interfaces). Reach into
64/// the `Deployed` variant directly when the deploy-only fields are
65/// required.
66// Both variants are inherently large deploy-state bundles that differ by
67// a few deploy-only fields; the size gap is not a memory concern (a
68// contract handle is never held in bulk) and boxing would churn the wide
69// field access across consumers.
70#[allow(clippy::large_enum_variant)]
71pub enum Contract<W: Witnesses + 'static> {
72    Deployed {
73        contract_address: ContractAddress,
74        initial_contract_state: ContractState<InMemoryDB>,
75        signing_key: SigningKey,
76        finalized_deploy_tx: FinalizedTxData,
77        calls: ContractCalls<W>,
78        circuit_maintenance_tx: CircuitMaintenanceTxInterfaces,
79        contract_maintenance_tx: ContractMaintenanceTx,
80        initial_private_state: RuntimeValue,
81        initial_zswap_local_state: CompactZswapLocalState,
82        unproven_tx: Option<UnprovenTx>,
83        new_coins: Vec<ShieldedCoinInfo>,
84    },
85    Found {
86        contract_address: ContractAddress,
87        initial_contract_state: ContractState<InMemoryDB>,
88        signing_key: SigningKey,
89        finalized_deploy_tx: FinalizedTxData,
90        calls: ContractCalls<W>,
91        circuit_maintenance_tx: CircuitMaintenanceTxInterfaces,
92        contract_maintenance_tx: ContractMaintenanceTx,
93    },
94}
95
96impl<W: Witnesses + 'static> Contract<W> {
97    /// Address the contract is bound to.
98    #[inline]
99    #[must_use]
100    pub fn contract_address(&self) -> &ContractAddress {
101        match self {
102            Self::Deployed {
103                contract_address, ..
104            }
105            | Self::Found {
106                contract_address, ..
107            } => contract_address,
108        }
109    }
110
111    /// Initial on-chain `ContractState` recorded at deploy time.
112    /// Same shape on both variants.
113    #[inline]
114    #[must_use]
115    pub fn initial_contract_state(&self) -> &ContractState<InMemoryDB> {
116        match self {
117            Self::Deployed {
118                initial_contract_state,
119                ..
120            }
121            | Self::Found {
122                initial_contract_state,
123                ..
124            } => initial_contract_state,
125        }
126    }
127
128    /// Signing key bound to this contract — the maintenance authority
129    /// the deployer registered (deploy variant) or the locally-stored
130    /// key resolved during find (find variant).
131    #[inline]
132    #[must_use]
133    pub fn signing_key(&self) -> &SigningKey {
134        match self {
135            Self::Deployed { signing_key, .. } | Self::Found { signing_key, .. } => signing_key,
136        }
137    }
138
139    /// Finalized tx data of the deploy that produced this contract.
140    /// On the deploy path: the tx the local submission produced. On
141    /// the find path: the deploy tx the indexer surfaced via
142    /// `watch_for_deploy_tx_data`.
143    #[inline]
144    #[must_use]
145    pub fn finalized_deploy_tx(&self) -> &FinalizedTxData {
146        match self {
147            Self::Deployed {
148                finalized_deploy_tx,
149                ..
150            }
151            | Self::Found {
152                finalized_deploy_tx,
153                ..
154            } => finalized_deploy_tx,
155        }
156    }
157
158    /// Per-circuit call dispatcher bound to this contract's address +
159    /// providers. Use [`Self::call`] for the common one-shot path; the
160    /// dispatcher is exposed here for advanced flows that batch or
161    /// interleave staged-builder steps (B1).
162    #[inline]
163    #[must_use]
164    pub fn calls(&self) -> &ContractCalls<W> {
165        match self {
166            Self::Deployed { calls, .. } | Self::Found { calls, .. } => calls,
167        }
168    }
169
170    /// Invoke `circuit_id` against this contract. Forwards to
171    /// [`ContractCalls::call`] on the contract's bound dispatcher —
172    /// `contract.call(rng, "increment", args, opts).await` is the
173    /// idiomatic shape; reach for [`Self::calls`] when batched or
174    /// staged use is needed.
175    ///
176    /// # Errors
177    ///
178    /// Propagates any error from the submit pipeline.
179    pub async fn call<R>(
180        &self,
181        rng: &mut R,
182        circuit_id: impl Into<CircuitId>,
183        args: RuntimeValue,
184        options: CallOptions,
185    ) -> Result<crate::tx_model::FinalizedCallTxData>
186    where
187        R: Rng + CryptoRng,
188    {
189        self.calls().call(rng, circuit_id, args, options).await
190    }
191
192    /// Per-circuit verifier-key maintenance interfaces.
193    #[inline]
194    #[must_use]
195    pub fn circuit_maintenance_tx(&self) -> &CircuitMaintenanceTxInterfaces {
196        match self {
197            Self::Deployed {
198                circuit_maintenance_tx,
199                ..
200            }
201            | Self::Found {
202                circuit_maintenance_tx,
203                ..
204            } => circuit_maintenance_tx,
205        }
206    }
207
208    /// Contract-level maintenance interface (replace authority).
209    #[inline]
210    #[must_use]
211    pub fn contract_maintenance_tx(&self) -> &ContractMaintenanceTx {
212        match self {
213            Self::Deployed {
214                contract_maintenance_tx,
215                ..
216            }
217            | Self::Found {
218                contract_maintenance_tx,
219                ..
220            } => contract_maintenance_tx,
221        }
222    }
223
224    /// `true` when this handle was produced by [`deploy_contract`].
225    /// Use as a quick discriminant before pattern-matching for the
226    /// deploy-only fields.
227    #[inline]
228    #[must_use]
229    pub const fn is_deployed(&self) -> bool {
230        matches!(self, Self::Deployed { .. })
231    }
232
233    /// `true` when this handle was produced by [`find_deployed_contract`].
234    #[inline]
235    #[must_use]
236    pub const fn is_found(&self) -> bool {
237        matches!(self, Self::Found { .. })
238    }
239}
240
241// Deploy-only fields (initial_private_state, initial_zswap_local_state,
242// unproven_tx, new_coins) live exclusively on the `Deployed` variant.
243// Pattern-match on `Contract::Deployed { .. }` to access them; the
244// type system makes the unavailability on `Found` explicit at call
245// sites rather than handing back `Option<&T>` shaped values that
246// callers always have to unwrap.
247
248// =====================================================================
249// deploy_contract
250// =====================================================================
251
252/// Deploy a contract.
253///
254/// On success, returns a [`Contract::Deployed`] with the call +
255/// maintenance interfaces pre-wired. On non-`SucceedEntirely` status,
256/// returns [`crate::ContractsError::DeployTxFailed`] and **no local
257/// state is persisted** (signing key is not stored; private state is
258/// not stored).
259///
260/// `executable` is taken as an [`Arc`] so the returned `call_tx` can
261/// retain a reference — future circuit calls go through the same
262/// executable instance.
263pub async fn deploy_contract<W, R>(
264    rng: &mut R,
265    executable: Arc<IrExecutable<W>>,
266    providers: Arc<ErasedProviders>,
267    options: DeployOptions,
268) -> Result<Contract<W>>
269where
270    W: Witnesses + 'static,
271    R: Rng + CryptoRng,
272{
273    let private_state_id = options.persistent_state.as_ref().map(|(id, _)| id.clone());
274
275    let deploy_tx_data = submit_deploy_tx(rng, executable.as_ref(), &providers, options).await?;
276
277    let crate::tx_model::FinalizedDeployTxData {
278        public:
279            crate::tx_model::FinalizedDeployTxPublicData {
280                finalized,
281                contract_address,
282                initial_contract_state,
283            },
284        private:
285            crate::tx_model::UnsubmittedDeployTxPrivateData {
286                signing_key,
287                initial_private_state,
288                initial_zswap_local_state,
289                unproven_tx,
290                new_coins,
291            },
292    } = deploy_tx_data;
293
294    // Wire the typed interfaces bound to this contract address. The
295    // maintenance-interfaces factory iterates over the executable's
296    // `provable_circuit_ids` — matches TS `getProvableCircuitIds()`.
297    let providers_for_ifaces = providers;
298    let calls = ContractCalls::<W>::new(
299        providers_for_ifaces.clone(),
300        executable.clone(),
301        contract_address,
302        private_state_id,
303    );
304    let circuit_maintenance_tx = CircuitMaintenanceTxInterfaces::new(
305        executable.provable_circuit_ids().into_iter().map(|id| {
306            let iface = CircuitMaintenanceTx::new(
307                providers_for_ifaces.clone(),
308                contract_address,
309                id.clone(),
310            );
311            (id, iface)
312        }),
313    );
314    let contract_maintenance_tx =
315        ContractMaintenanceTx::new(providers_for_ifaces, contract_address);
316
317    Ok(Contract::Deployed {
318        contract_address,
319        initial_contract_state,
320        signing_key,
321        finalized_deploy_tx: finalized,
322        calls,
323        circuit_maintenance_tx,
324        contract_maintenance_tx,
325        initial_private_state,
326        initial_zswap_local_state,
327        unproven_tx,
328        new_coins,
329    })
330}
331
332// =====================================================================
333// find_deployed_contract + verify_contract_state
334// =====================================================================
335
336/// Two [`VerifierKey`]s are equal iff they have the same length and
337/// the same bytes. Port of TS `verifierKeysEqual`.
338#[must_use]
339pub fn verifier_keys_equal(a: &VerifierKey, b: &VerifierKey) -> bool {
340    a.as_bytes() == b.as_bytes()
341}
342
343/// Verify that a [`ContractState`] has each circuit's verifier key
344/// installed and equal to the caller-supplied key. Port of TS
345/// `verifyContractState`.
346///
347/// The on-chain `ContractOperation` stores the verifier key in a
348/// tagged-serialized form. We re-tagged-serialize the caller's local
349/// bytes and compare — equality at that level implies byte-level
350/// equality at the wire level, which is what the ledger's
351/// [`ContractOperation`](moonproof_ledger::onchain_runtime::state::ContractOperation)
352/// uses internally to validate contract calls.
353///
354/// # Errors
355///
356/// [`ContractsError::ContractType`] listing every circuit that's
357/// missing from the on-chain state OR has a mismatched VK.
358pub fn verify_contract_state(
359    verifier_keys: &[(CircuitId, VerifierKey)],
360    contract_state: &ContractState<InMemoryDB>,
361) -> Result<()> {
362    let mut mismatched: Vec<CircuitId> = Vec::new();
363    for (circuit_id, local_vk) in verifier_keys {
364        let entry: EntryPointBuf = circuit_id.as_str().as_bytes().into();
365        let Some(op) = contract_state.operations.get(&entry) else {
366            mismatched.push(circuit_id.clone());
367            continue;
368        };
369
370        // Local VK bytes are the tagged-serialized form compactc
371        // emits. To compare against the ledger's typed VK, we
372        // tagged-deserialize ours and re-serialize the on-chain
373        // one, then byte-compare. This matches TS
374        // `verifierKeysEqual(localVk, contractState.operation(circuitId).verifierKey)`
375        // behaviour at the byte level.
376        let local_parsed: std::result::Result<
377            moonproof_ledger::transient_crypto::proofs::VerifierKey,
378            _,
379        > = moonproof_ledger::serialize::tagged_deserialize(&mut local_vk.as_bytes());
380        let Ok(local_parsed) = local_parsed else {
381            mismatched.push(circuit_id.clone());
382            continue;
383        };
384
385        // Compare the operation's own verifier key, not the operation's
386        // serialized bytes. `VerifierKey` has no `PartialEq`, so the
387        // comparison still goes through the serialized form — but of the
388        // key alone.
389        //
390        // Serializing the whole `ContractOperation` and testing that it
391        // *ends with* the key only worked because ledger 8's operation
392        // holds a single `Option<VerifierKey>` and so trails with it.
393        // Ledger 9's is `{ v2, v3, ir }`, whose bytes end with the `ir`
394        // field, and the suffix test can never match there. `latest()`
395        // returns the key for the current proof stack on both
396        // generations, which is exactly the one to check.
397        let Some(on_chain_vk) = op.latest() else {
398            mismatched.push(circuit_id.clone());
399            continue;
400        };
401        let mut local_bytes = Vec::new();
402        let mut on_chain_bytes = Vec::new();
403        if moonproof_ledger::serialize::Serializable::serialize(&local_parsed, &mut local_bytes)
404            .is_err()
405        {
406            mismatched.push(circuit_id.clone());
407            continue;
408        }
409        if moonproof_ledger::serialize::Serializable::serialize(on_chain_vk, &mut on_chain_bytes)
410            .is_err()
411        {
412            mismatched.push(circuit_id.clone());
413            continue;
414        }
415        if local_bytes != on_chain_bytes {
416            mismatched.push(circuit_id.clone());
417        }
418    }
419
420    if mismatched.is_empty() {
421        Ok(())
422    } else {
423        // Tagged-serialize the on-chain state for diagnostics in the
424        // error payload — lets the caller see exactly what was on
425        // chain when the mismatch triggered.
426        let mut state_bytes = Vec::new();
427        moonproof_ledger::serialize::tagged_serialize(contract_state, &mut state_bytes).ok();
428        Err(ContractRuntimeError::Contracts(
429            ContractsError::contract_type(state_bytes, mismatched),
430        ))
431    }
432}
433
434/// Configuration for [`find_deployed_contract`]. Port of TS
435/// `FindDeployedContractOptions<C>`.
436pub struct FindDeployedContractOptions {
437    pub contract_address: ContractAddress,
438    /// If `Some`, the provided key is stored under the contract
439    /// address. If `None`, and the provider already has a key, the
440    /// existing key is kept. If `None` AND no key is stored, a fresh
441    /// key is sampled and stored.
442    pub signing_key: Option<SigningKey>,
443    /// If `Some`, the call is private-state-aware: subsequent calls
444    /// load private state from this id. `None` for stateless
445    /// contracts.
446    pub private_state_id: Option<PrivateStateId>,
447    /// If `Some`, the provided bytes overwrite whatever's stored at
448    /// `private_state_id` (requires `private_state_id.is_some()`).
449    /// If `None`, the existing private state at `private_state_id` is
450    /// kept. Port of TS
451    /// `FindDeployedContractOptionsStorePrivateState`.
452    pub initial_private_state_bytes: Option<Vec<u8>>,
453}
454
455/// Look up a deployed contract by address, verify its type matches
456/// the caller's executable, and return a [`Contract::Found`] handle.
457/// Port of TS `findDeployedContract`.
458///
459/// `executable` is taken as an [`Arc`] so the returned `call_tx` can
460/// retain a reference for subsequent circuit calls — matches the TS
461/// pattern of embedding `compiledContract` in the callTx interface.
462pub async fn find_deployed_contract<W, R>(
463    rng: &mut R,
464    executable: Arc<IrExecutable<W>>,
465    providers: Arc<ErasedProviders>,
466    options: FindDeployedContractOptions,
467) -> Result<Contract<W>>
468where
469    W: Witnesses + 'static,
470    R: Rng + CryptoRng,
471{
472    providers
473        .private_state
474        .set_contract_address(&options.contract_address)
475        .await?;
476
477    // Wait for the deploy-tx data to appear on chain. Indefinite wait
478    // matches TS contract.
479    let finalized = providers
480        .public_data
481        .watch_for_deploy_tx_data(&options.contract_address)
482        .await?;
483
484    // Load the initial contract state (as recorded at deploy time).
485    let initial_contract_state = providers
486        .public_data
487        .query_deploy_contract_state(&options.contract_address)
488        .await?
489        .ok_or_else(|| {
490            ContractRuntimeError::NotFound(format!(
491                "No contract deployed at contract address {}",
492                moonproof_runtime::state::contract_address_to_hex(&options.contract_address),
493            ))
494        })?;
495
496    // Load the current contract state (which may have advanced past
497    // the deploy).
498    let current_contract_state = providers
499        .public_data
500        .query_contract_state(&options.contract_address, None)
501        .await?
502        .ok_or_else(|| {
503            ContractRuntimeError::NotFound(format!(
504                "No contract deployed at contract address {}",
505                moonproof_runtime::state::contract_address_to_hex(&options.contract_address),
506            ))
507        })?;
508
509    // Verify the on-chain state carries every circuit's vk. Use the
510    // executable's embedded VKs when available; fall back to the
511    // zk-config provider otherwise.
512    let mut verifier_keys: Vec<(CircuitId, VerifierKey)> = Vec::new();
513    for id in executable.provable_circuit_ids() {
514        let vk = match executable.embedded_verifier_key(&id) {
515            Some(vk) => vk,
516            None => providers.zk_config.get_verifier_key(&id).await?,
517        };
518        verifier_keys.push((id, vk));
519    }
520    verify_contract_state(&verifier_keys, &current_contract_state)?;
521
522    // Resolve / rotate the signing key. Order matches TS:
523    // 1. If caller provided one → store + use it.
524    // 2. Else existing stored key → use it.
525    // 3. Else sample fresh + store.
526    let signing_key = match options.signing_key {
527        Some(k) => {
528            providers
529                .private_state
530                .set_signing_key(&options.contract_address, k.clone())
531                .await?;
532            k
533        }
534        None => {
535            if let Some(k) = providers
536                .private_state
537                .get_signing_key(&options.contract_address)
538                .await?
539            {
540                k
541            } else {
542                let mut bytes = [0u8; 32];
543                rng.fill_bytes(&mut bytes);
544                let k = moonproof_ledger::signatures::schnorr_signing_key(&bytes)
545                    .expect("32 random bytes parse into a SigningKey");
546                providers
547                    .private_state
548                    .set_signing_key(&options.contract_address, k.clone())
549                    .await?;
550                k
551            }
552        }
553    };
554
555    // Persist initial_private_state_bytes if the caller supplied one
556    // alongside a private_state_id.
557    if let (Some(psi), Some(bytes)) = (
558        options.private_state_id.as_ref(),
559        options.initial_private_state_bytes.as_ref(),
560    ) {
561        providers.private_state.set(psi, bytes.clone()).await?;
562    }
563
564    // Build the call + maintenance interfaces — mirrors TS
565    // `createContractCallsInterface` etc. at the end of
566    // `findDeployedContract`.
567    let calls = ContractCalls::<W>::new(
568        providers.clone(),
569        executable.clone(),
570        options.contract_address,
571        options.private_state_id.clone(),
572    );
573    let circuit_maintenance_tx = CircuitMaintenanceTxInterfaces::new(
574        executable.provable_circuit_ids().into_iter().map(|id| {
575            (
576                id.clone(),
577                CircuitMaintenanceTx::new(providers.clone(), options.contract_address, id),
578            )
579        }),
580    );
581    let contract_maintenance_tx =
582        ContractMaintenanceTx::new(providers.clone(), options.contract_address);
583
584    Ok(Contract::Found {
585        contract_address: options.contract_address,
586        initial_contract_state,
587        signing_key,
588        finalized_deploy_tx: finalized,
589        calls,
590        circuit_maintenance_tx,
591        contract_maintenance_tx,
592    })
593}
594
595// =====================================================================
596// Tests
597// =====================================================================
598
599#[cfg(test)]
600mod tests {
601    use super::*;
602    use crate::test_helpers::{counter_ir_executable, counter_vk_bytes, scripted_providers};
603    use crate::types::{CircuitId, PrivateStateId, TxStatus, VerifierKey};
604    use moonproof_ledger::onchain_runtime::state::{
605        ContractMaintenanceAuthority, ContractOperation, StateValue,
606    };
607    use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
608    use moonproof_runtime_ir::RuntimeValue as Value;
609    use rand::SeedableRng;
610
611    // --- deploy_contract ---------------------------------------------
612
613    fn baseline_options() -> DeployOptions {
614        DeployOptions {
615            constructor_args: Value::Null,
616            initial_private_state: Value::Null,
617            signing_key: None,
618            additional_coin_enc_public_key_mappings: None,
619            current_time: moonproof_ledger::base_crypto::time::Timestamp::from_secs(0),
620            network_id: "local-test".to_owned(),
621            persistent_state: None,
622            fee_balancing: None,
623            register_circuits: None,
624        }
625    }
626
627    /// ports: `deploy-contract.test.ts::should deploy contract without private state`
628    #[tokio::test]
629    async fn deploys_without_private_state_and_samples_signing_key_when_absent() {
630        let (providers, ps) = scripted_providers(None, None, TxStatus::SucceedEntirely);
631        let executable = Arc::new(counter_ir_executable().await);
632        let mut rng = rand::rngs::StdRng::from_seed([0xD0u8; 32]);
633        let deployed = Box::pin(deploy_contract(
634            &mut rng,
635            executable.clone(),
636            Arc::new(providers),
637            baseline_options(),
638        ))
639        .await
640        .unwrap();
641
642        assert_eq!(
643            deployed.finalized_deploy_tx().status,
644            TxStatus::SucceedEntirely
645        );
646        assert!(deployed
647            .circuit_maintenance_tx()
648            .get(&CircuitId::new("increment"))
649            .is_some());
650        assert_eq!(
651            deployed.contract_maintenance_tx().contract_address(),
652            deployed.contract_address(),
653        );
654        assert_eq!(ps.set_signing_key_calls.lock().unwrap().len(), 1);
655    }
656
657    /// ports: `deploy-contract.test.ts::should deploy contract with provided signing key`
658    #[tokio::test]
659    async fn deploys_with_caller_supplied_signing_key() {
660        let (providers, ps) = scripted_providers(None, None, TxStatus::SucceedEntirely);
661        let executable = Arc::new(counter_ir_executable().await);
662        let provided = moonproof_ledger::signatures::schnorr_signing_key(&[0x77u8; 32]).unwrap();
663        let mut opts = baseline_options();
664        opts.signing_key = Some(provided.clone());
665        let mut rng = rand::rngs::StdRng::from_seed([0xD1u8; 32]);
666        let deployed = Box::pin(deploy_contract(
667            &mut rng,
668            executable.clone(),
669            Arc::new(providers),
670            opts,
671        ))
672        .await
673        .unwrap();
674        assert_eq!(
675            deployed.signing_key().verifying_key(),
676            provided.verifying_key(),
677        );
678        let calls = ps.set_signing_key_calls.lock().unwrap();
679        assert_eq!(calls.len(), 1);
680        assert_eq!(calls[0].1.verifying_key(), provided.verifying_key());
681    }
682
683    /// ports: `deploy-contract.test.ts::should deploy contract with private state`
684    #[tokio::test]
685    async fn deploys_with_private_state_persists_under_id() {
686        let (providers, ps) = scripted_providers(None, None, TxStatus::SucceedEntirely);
687        let executable = Arc::new(counter_ir_executable().await);
688        let mut opts = baseline_options();
689        opts.persistent_state = Some((PrivateStateId::new("counter"), b"seeded".to_vec()));
690        let mut rng = rand::rngs::StdRng::from_seed([0xD2u8; 32]);
691        Box::pin(deploy_contract(
692            &mut rng,
693            executable.clone(),
694            Arc::new(providers),
695            opts,
696        ))
697        .await
698        .unwrap();
699        assert_eq!(ps.set_signing_key_calls.lock().unwrap().len(), 1);
700    }
701
702    /// ports: `deploy-contract.test.ts::should deploy contract with both custom signing key and private state`
703    #[tokio::test]
704    async fn deploys_with_both_custom_signing_key_and_private_state() {
705        let (providers, ps) = scripted_providers(None, None, TxStatus::SucceedEntirely);
706        let executable = Arc::new(counter_ir_executable().await);
707        let provided = moonproof_ledger::signatures::schnorr_signing_key(&[0xB7u8; 32]).unwrap();
708        let mut opts = baseline_options();
709        opts.signing_key = Some(provided.clone());
710        opts.persistent_state = Some((PrivateStateId::new("counter"), b"seeded".to_vec()));
711        let mut rng = rand::rngs::StdRng::from_seed([0xD3u8; 32]);
712        let deployed = Box::pin(deploy_contract(
713            &mut rng,
714            executable,
715            Arc::new(providers),
716            opts,
717        ))
718        .await
719        .unwrap();
720        assert_eq!(
721            deployed.signing_key().verifying_key(),
722            provided.verifying_key(),
723        );
724        let calls = ps.set_signing_key_calls.lock().unwrap();
725        assert_eq!(calls.len(), 1);
726        assert_eq!(calls[0].1.verifying_key(), provided.verifying_key());
727    }
728
729    // --- verify_contract_state --------------------------------------
730
731    async fn counter_vk() -> VerifierKey {
732        counter_vk_bytes().await
733    }
734
735    fn contract_state_with_operation(op: ContractOperation) -> ContractState<InMemoryDB> {
736        let entry: EntryPointBuf = "increment".as_bytes().into();
737        ContractState::<InMemoryDB>::new(
738            StateValue::Null,
739            StorageHashMap::new().insert(entry, op),
740            ContractMaintenanceAuthority::default(),
741        )
742    }
743
744    #[test]
745    fn verifier_keys_equal_byte_comparison() {
746        let a = VerifierKey::new(vec![1, 2, 3]);
747        let b = VerifierKey::new(vec![1, 2, 3]);
748        let c = VerifierKey::new(vec![1, 2, 4]);
749        assert!(verifier_keys_equal(&a, &b));
750        assert!(!verifier_keys_equal(&a, &c));
751    }
752
753    /// ports: `find-deployed-contract.test.ts::should find deployed contract without private state`
754    #[tokio::test]
755    async fn verify_contract_state_accepts_matching_vk() {
756        let vk = counter_vk().await;
757        let parsed: moonproof_ledger::transient_crypto::proofs::VerifierKey =
758            moonproof_ledger::serialize::tagged_deserialize(&mut vk.as_bytes()).unwrap();
759        let op = moonproof_ledger::contract_operation(Some(parsed));
760        let state = contract_state_with_operation(op);
761        verify_contract_state(&[(CircuitId::new("increment"), vk)], &state)
762            .expect("matching vk should be accepted");
763    }
764
765    /// ports: `find-deployed-contract.test.ts::should throw error when contract is not found`
766    #[tokio::test]
767    async fn verify_contract_state_rejects_when_circuit_missing_from_state() {
768        let vk = counter_vk().await;
769        let state = ContractState::<InMemoryDB>::new(
770            StateValue::Null,
771            StorageHashMap::new(),
772            ContractMaintenanceAuthority::default(),
773        );
774        let err = verify_contract_state(&[(CircuitId::new("increment"), vk)], &state).unwrap_err();
775        matches!(
776            err,
777            ContractRuntimeError::Contracts(ContractsError::ContractType { .. })
778        );
779    }
780
781    #[tokio::test]
782    async fn verify_contract_state_rejects_when_operation_has_no_vk() {
783        let vk = counter_vk().await;
784        let op_no_vk = moonproof_ledger::contract_operation(None);
785        let state = contract_state_with_operation(op_no_vk);
786        let err = verify_contract_state(&[(CircuitId::new("increment"), vk)], &state).unwrap_err();
787        matches!(
788            err,
789            ContractRuntimeError::Contracts(ContractsError::ContractType { .. })
790        );
791    }
792
793    #[tokio::test]
794    async fn verify_contract_state_lists_every_mismatched_circuit() {
795        let vk = counter_vk().await;
796        let state = ContractState::<InMemoryDB>::new(
797            StateValue::Null,
798            StorageHashMap::new(),
799            ContractMaintenanceAuthority::default(),
800        );
801        let err = verify_contract_state(
802            &[
803                (CircuitId::new("a"), vk.clone()),
804                (CircuitId::new("b"), vk.clone()),
805                (CircuitId::new("c"), vk),
806            ],
807            &state,
808        )
809        .unwrap_err();
810        let msg = format!("{err}");
811        assert!(
812            msg.contains('a') && msg.contains('b') && msg.contains('c'),
813            "{msg}"
814        );
815    }
816}