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
//! Build an unproven deploy transaction.
//!
//! Runs the contract's constructor via
//! [`IrExecutable::initialize`], wraps the result in a
//! [`ContractDeploy`](moonproof_ledger::ledger::structure::ContractDeploy),
//! tagged-serializes into the [`UnsubmittedDeployTxData`] bundle the
//! submit-tx pipeline consumes.
//!
//! Two entry points:
//!
//! - [`create_unproven_deploy_tx`] — full-providers entry. Takes a
//!   provider bundle and pulls coin / encryption public keys off the
//!   wallet provider.
//! - [`create_unproven_deploy_tx_from_keys`] — lower-level entry that
//!   takes the keys + zk-config provider directly. Useful for test
//!   harnesses without a full provider bundle.
//!
//! Both accept a [`DeployOptions`] bundle. `signing_key` is
//! `Option<SigningKey>` — when `None`, a fresh key is sampled from the
//! supplied RNG and persisted on the returned tx data. The contract's
//! `initial_private_state` is always [`RuntimeValue`]; pass
//! [`RuntimeValue::Null`] for stateless contracts.

use std::collections::HashMap;
#[cfg(test)]
use std::sync::Arc;

use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::onchain_runtime::state::EntryPointBuf;
use moonproof_ledger::signatures::SigningKey;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
use rand::{CryptoRng, Rng};

use crate::error::{ContractRuntimeError, Result};
use crate::fee_balancing::{apply_fee_balancing, FeeBalancingConfig};
use crate::providers::{HasWallet, HasZkConfig, WalletProvider, ZkConfigProvider};
use crate::tx_model::{
    UnsubmittedDeployTxData, UnsubmittedDeployTxPrivateData, UnsubmittedDeployTxPublicData,
};
use crate::types::{CircuitId, CoinPublicKey, EncPublicKey, PrivateStateId};
use crate::utils::ledger_utils::{build_contract_deploy, ttl_one_hour};
use moonproof_runtime::executable::ConstructorContext;
use moonproof_runtime::ir::witnesses::Witnesses;
use moonproof_runtime::ir_executable::IrExecutable;
use moonproof_runtime_ir::RuntimeValue;

// =====================================================================
// Options
// =====================================================================

/// Configuration for [`deploy_contract`](crate::contract::deploy_contract)
/// and the lower-level [`create_unproven_deploy_tx`] / [`submit_deploy_tx`](crate::submit_deploy_tx)
/// entry points.
pub struct DeployOptions {
    /// Constructor arguments. [`RuntimeValue::Null`] for no-arg constructors.
    pub constructor_args: RuntimeValue,
    /// Initial private state the constructor runs against.
    /// [`RuntimeValue::Null`] for stateless contracts.
    pub initial_private_state: RuntimeValue,
    /// The signing key the deploy will install as the contract's
    /// maintenance authority. When `None`, a fresh key is sampled
    /// from the supplied RNG. Callers should persist the resolved key
    /// under the deployed contract's address on tx success.
    pub signing_key: Option<SigningKey>,
    /// Optional extra `(CoinPublicKey, EncPublicKey)` pairs — merged
    /// into the encryption-key resolver so circuits that produce
    /// outputs addressed to third parties (not the current wallet)
    /// can encrypt them correctly.
    pub additional_coin_enc_public_key_mappings: Option<HashMap<CoinPublicKey, EncPublicKey>>,
    /// Chain-tip timestamp. The intent's TTL is derived as
    /// `current_time + 1 hour`. Must be chain-derived
    /// (indexer's latest block time) — not `SystemTime::now()`.
    pub current_time: Timestamp,
    /// Network id the transaction targets (e.g. `"local-test"`).
    pub network_id: String,
    /// If `Some((id, bytes))`, persist `bytes` under `id` in the
    /// private-state provider on successful submission. Caller
    /// pre-serializes; the runtime stays serde-format-agnostic.
    /// Consumed by the submit pipeline; ignored at the unproven-tx
    /// build stage.
    pub persistent_state: Option<(PrivateStateId, Vec<u8>)>,
    /// Optional dust-fee balancing. When `Some`, a dust-balancing
    /// intent is merged into the deploy tx at the preimage stage,
    /// before [`crate::providers::ProofProvider::prove_tx`] runs.
    /// That lets `prove_tx` prove both the deploy AND the dust spend
    /// in one pass, and keeps `balance_tx` a pure seal. `None` skips
    /// balancing entirely — used by offline tests where the ledger
    /// acceptance check is lenient about fees.
    pub fee_balancing: Option<FeeBalancingConfig>,
    /// Restrict the deploy's on-chain operations table to this subset
    /// of circuits. `None` registers every circuit the constructor's
    /// `register_operations` lists (the default — a complete deploy).
    ///
    /// `Some(subset)` registers only the named circuits, leaving the
    /// rest absent from the deployed contract. The omitted circuits can
    /// then be installed after deploy with
    /// [`submit_insert_verifier_key_tx`](crate::submit_insert_verifier_key_tx)
    /// — this is the mechanism that lets a contract whose full verifier-
    /// key set would blow the ledger's per-transaction byte limit deploy
    /// across several transactions
    /// ([`deploy_contract_incremental`](crate::deploy_contract_incremental)).
    ///
    /// Every id MUST appear in the IR's `register_operations`; an unknown
    /// circuit is a [`ContractRuntimeError::Provider`] error. The ledger
    /// state (constructor output) is unaffected — only the operations
    /// table is filtered.
    pub register_circuits: Option<Vec<CircuitId>>,
}

// =====================================================================
// Public API
// =====================================================================

/// Full-providers entry point. Extracts coin- + encryption-public keys
/// from `providers.wallet` and delegates to
/// [`create_unproven_deploy_tx_from_keys`]. Port of TS
/// `createUnprovenDeployTx`.
pub async fn create_unproven_deploy_tx<W, R, C>(
    rng: &mut R,
    executable: &IrExecutable<W>,
    providers: &C,
    options: DeployOptions,
) -> Result<UnsubmittedDeployTxData>
where
    W: Witnesses + 'static,
    R: Rng + CryptoRng,
    C: HasWallet + HasZkConfig + ?Sized,
{
    let coin_pk = providers.wallet().coin_public_key();
    let enc_pk = providers.wallet().encryption_public_key();
    create_unproven_deploy_tx_from_keys(
        rng,
        executable,
        providers.zk_config(),
        coin_pk,
        enc_pk,
        options,
    )
    .await
}

/// Lower-level entry point. Given a zk-config provider + the caller's
/// coin-/encryption-public keys, run the constructor and assemble an
/// unproven deploy transaction. Port of TS
/// `createUnprovenDeployTxFromVerifierKeys`.
///
/// The `zk_config` parameter is currently **unused** at this slice —
/// the Rust [`ContractExecutable::initialize`] trait already bakes the
/// verifier key lookup into the executable itself (via
/// [`ContractExecutable::embedded_verifier_key`] or by the executable's
/// own knowledge of its circuit set). The parameter is kept in the
/// signature to preserve the TS call-site shape and to give a future
/// "load VKs from `zk_config` + populate `ContractOperation`" slice a
/// natural home.
pub async fn create_unproven_deploy_tx_from_keys<W, R, Z: ZkConfigProvider + ?Sized>(
    rng: &mut R,
    executable: &IrExecutable<W>,
    _zk_config: &Z,
    coin_public_key: CoinPublicKey,
    _encryption_public_key: EncPublicKey,
    options: DeployOptions,
) -> Result<UnsubmittedDeployTxData>
where
    W: Witnesses + 'static,
    R: Rng + CryptoRng,
{
    // (0) Resolve the signing key — caller-supplied or freshly
    // sampled from `rng` when `None`. The resolved key flows back
    // out on the returned `UnsubmittedDeployTxData` so the submit
    // pipeline can persist it under the deployed contract address.
    let signing_key = options.signing_key.clone().unwrap_or_else(|| {
        let mut bytes = [0u8; 32];
        rng.fill_bytes(&mut bytes);
        moonproof_ledger::signatures::schnorr_signing_key(&bytes)
            .expect("32 random bytes parse into a SigningKey")
    });

    // (1) Run the constructor. This drives the real onchain-runtime
    // VM via the executable's hand-written op sequence (or, once
    // codegen lands, a generated equivalent).
    let ctor_ctx = ConstructorContext {
        initial_private_state: options.initial_private_state,
        initial_zswap_local_state: crate::utils::zswap_utils::CompactZswapLocalState::empty(
            coin_public_key,
        ),
        coin_public_key,
        signing_key: signing_key.clone(),
        time: Some(options.current_time),
    };
    let mut init = executable
        .initialize(ctor_ctx, options.constructor_args)
        .await?;

    // Install the deployer as the contract's maintenance authority.
    // The executable's `initialize` returns a state seeded with
    // `ContractMaintenanceAuthority::default()` (empty committee) —
    // matching the upstream onchain-state default. We override here
    // so the on-chain contract has a usable authority from block 0;
    // without this, every maintenance tx would fail
    // "caller's verifying key is not in the on-chain committee".
    //
    // This is the canonical path: the executable owns the data /
    // operations / VK shape, the deploy flow owns the per-deployer
    // authority binding. Same split TS uses (`partialContractState`
    // + `assembleContract` in `createUnprovenLedgerDeployTx`).
    init.initial_contract_state.maintenance_authority =
        moonproof_ledger::onchain_runtime::state::ContractMaintenanceAuthority {
            committee: vec![moonproof_ledger::signatures::maintenance_verifying_key(
                &signing_key,
            )],
            threshold: 1,
            counter: 0,
        };

    // (1b) Optionally restrict the operations table to a subset of
    // circuits. `initialize` registered one ContractOperation per
    // circuit in `register_operations`; here we drop the ones the
    // caller didn't ask for, so the deploy tx only carries the subset's
    // verifier keys. The omitted circuits are installed later via
    // maintenance `VerifierKeyInsert` txs — the mechanism that lets a
    // contract too large to deploy in one transaction land across
    // several. The ledger state (`data`) is untouched; only the
    // operations registry shrinks.
    if let Some(subset) = options.register_circuits.as_ref() {
        let full = &init.initial_contract_state.operations;
        let mut pruned = StorageHashMap::new();
        for id in subset {
            let entry: EntryPointBuf = id.as_str().as_bytes().into();
            let op = full
                .get(&entry)
                .ok_or_else(|| ContractRuntimeError::Provider {
                    provider: "create_unproven_deploy_tx",
                    message: format!(
                        "register_circuits names circuit '{}', which is not in the contract's \
                     register_operations — only declared circuits can be deployed",
                        id.as_str(),
                    ),
                })?;
            pruned = pruned.insert(entry, (*op).clone());
        }
        init.initial_contract_state.operations = pruned;
    }

    // (2) Build the ContractDeploy + derive the on-chain address.
    let (deploy, contract_address, initial_contract_state) =
        build_contract_deploy(rng, init.initial_contract_state)?;

    // (3) Assemble the Intent + Transaction. The ledger's
    // `test_utilities::test_intents` helper produces the exact
    // `StorageHashMap<u16, Intent>` shape `Transaction::from_intents`
    // expects — single Intent at segment 1, empty offers, TTL at
    // `tblock + 1h`. That matches TS `Intent.new(ttlOneHour())` at
    // the call site in `createUnprovenLedgerDeployTx`, so we reuse
    // the helper directly. The `tblock` argument is the "now"
    // timestamp; `test_intents` adds 1h internally to derive the
    // TTL.
    let intents = crate::utils::ledger_utils::one_intent_at_segment_one(
        rng,
        Vec::new(),
        Vec::new(),
        vec![deploy],
        options.current_time,
    );
    // Silence unused import — `ttl_one_hour` is the public-facing
    // helper for callers who want the same 1-hour TTL; we use
    // `test_intents` internally but export `ttl_one_hour` from
    // `utils::ledger_utils` for call sites that build their own
    // Intent directly.
    let _ = ttl_one_hour;
    let network_id = options.network_id.clone();
    let tx: moonproof_ledger::ledger::structure::Transaction<
        moonproof_ledger::signatures::Signature,
        moonproof_ledger::ledger::structure::ProofPreimageMarker,
        moonproof_ledger::transient_crypto::commitment::PedersenRandomness,
        InMemoryDB,
    > = moonproof_ledger::ledger::structure::Transaction::from_intents(network_id.clone(), intents);

    // (3b) Optional dust-fee balancing — merged at preimage stage so
    // the downstream `ProofProvider::prove_tx` proves both the
    // deploy intent and the dust spend in one pass. Callers that skip
    // this (e.g. the offline `deploy_pipeline_offline` test) pass
    // `fee_balancing = None` and accept that the resulting tx won't
    // reach InBlock on a live harness without dust fees.
    let tx = if let Some(ref config) = options.fee_balancing {
        apply_fee_balancing(rng, tx, config, &network_id)?
    } else {
        tx
    };

    // (4) Wrap the typed transaction. Bytes form is computed lazily
    // on demand (and cached) — internal phase boundaries no longer
    // serialize between hops.
    let unproven_tx = crate::tx_phase::UnprovenTx::new(tx);

    // (5) Build new-coins list — for the counter and other non-zswap
    // contracts this is empty. When the contract mints / produces
    // shielded outputs, the caller threads those through
    // `zswap_state_to_new_coins` once that utility lands its full
    // implementation.
    let new_coins = Vec::new();

    Ok(UnsubmittedDeployTxData {
        public: UnsubmittedDeployTxPublicData {
            contract_address,
            initial_contract_state,
        },
        private: UnsubmittedDeployTxPrivateData {
            signing_key,
            initial_private_state: init.initial_private_state,
            initial_zswap_local_state: init.initial_zswap_local_state,
            unproven_tx: Some(unproven_tx),
            new_coins,
        },
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::providers::fs_zk_config::FileSystemZkConfigProvider;
    use crate::test_helpers::{counter_fixture_root, counter_ir_executable};
    use moonproof_runtime_ir::RuntimeValue as Value;
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    fn fixture_options() -> DeployOptions {
        DeployOptions {
            constructor_args: Value::Null,
            initial_private_state: Value::Null,
            signing_key: Some(
                moonproof_ledger::signatures::schnorr_signing_key(&[0x33u8; 32]).unwrap(),
            ),
            additional_coin_enc_public_key_mappings: None,
            current_time: Timestamp::from_secs(0),
            network_id: "local-test".to_owned(),
            persistent_state: None,
            fee_balancing: None,
            register_circuits: None,
        }
    }

    fn fixture_zk_cfg_arc() -> Arc<dyn ZkConfigProvider> {
        Arc::new(FileSystemZkConfigProvider::new(counter_fixture_root()))
    }

    /// ports: `unproven-deploy-tx.test.ts::createUnprovenDeployTxFromVerifierKeys::should create unproven deploy tx from verifier keys without private state`
    #[tokio::test]
    async fn builds_unsubmitted_deploy_tx_for_counter() {
        let mut rng = StdRng::seed_from_u64(0x00C0_FFEE);
        let c = counter_ir_executable().await;
        let zk = fixture_zk_cfg_arc();
        let data = create_unproven_deploy_tx_from_keys(
            &mut rng,
            &c,
            &zk,
            crate::types::CoinPublicKey([0u8; 32]),
            crate::types::EncPublicKey([0u8; 32]),
            fixture_options(),
        )
        .await
        .expect("deploy tx build must succeed");

        assert_ne!(data.public.contract_address.0 .0, [0u8; 32]);
        let bytes = data
            .private
            .unproven_tx
            .as_ref()
            .expect("create_unproven_deploy_tx populates unproven_tx")
            .to_tagged_bytes()
            .expect("serialize unproven tx");
        assert_ne!(bytes, [] as [u8; 0]);
        assert!(bytes.len() > 32);
        assert_eq!(
            data.private.new_coins,
            [] as [moonproof_ledger::coin_structure::coin::Info; 0]
        );
    }

    #[tokio::test]
    async fn serialized_tx_roundtrips_through_tagged_deserialize() {
        let mut rng = StdRng::seed_from_u64(0xDEAD);
        let c = counter_ir_executable().await;
        let zk = fixture_zk_cfg_arc();
        let data = create_unproven_deploy_tx_from_keys(
            &mut rng,
            &c,
            &zk,
            crate::types::CoinPublicKey([0u8; 32]),
            crate::types::EncPublicKey([0u8; 32]),
            fixture_options(),
        )
        .await
        .unwrap();

        let bytes = data
            .private
            .unproven_tx
            .as_ref()
            .expect("create_unproven_deploy_tx populates unproven_tx")
            .to_tagged_bytes()
            .unwrap();
        let _tx: moonproof_ledger::ledger::structure::Transaction<
            moonproof_ledger::signatures::Signature,
            moonproof_ledger::ledger::structure::ProofPreimageMarker,
            moonproof_ledger::transient_crypto::commitment::PedersenRandomness,
            InMemoryDB,
        > = moonproof_ledger::serialize::tagged_deserialize(&mut bytes.as_slice())
            .expect("unproven tx bytes must round-trip through tagged_deserialize");
    }

    #[tokio::test]
    async fn deserialized_tx_passes_well_formedness_check() {
        use moonproof_ledger::ledger::structure::LedgerState;
        use moonproof_ledger::ledger::verify::WellFormedStrictness;

        let mut rng = StdRng::seed_from_u64(42);
        let c = counter_ir_executable().await;
        let zk = fixture_zk_cfg_arc();
        let data = create_unproven_deploy_tx_from_keys(
            &mut rng,
            &c,
            &zk,
            crate::types::CoinPublicKey([0u8; 32]),
            crate::types::EncPublicKey([0u8; 32]),
            fixture_options(),
        )
        .await
        .unwrap();

        let bytes = data
            .private
            .unproven_tx
            .as_ref()
            .expect("create_unproven_deploy_tx populates unproven_tx")
            .to_tagged_bytes()
            .unwrap();
        let tx: moonproof_ledger::ledger::structure::Transaction<
            moonproof_ledger::signatures::Signature,
            moonproof_ledger::ledger::structure::ProofPreimageMarker,
            moonproof_ledger::transient_crypto::commitment::PedersenRandomness,
            InMemoryDB,
        > = moonproof_ledger::serialize::tagged_deserialize(&mut bytes.as_slice()).unwrap();

        let ledger_state: LedgerState<InMemoryDB> = LedgerState::new("local-test");
        let mut strictness = WellFormedStrictness::default();
        strictness.enforce_balancing = false;
        tx.well_formed(&ledger_state, strictness, Timestamp::from_secs(0))
            .expect("deserialized unproven deploy tx must pass well-formedness");
    }

    #[tokio::test]
    async fn signing_key_is_preserved_into_private_payload() {
        use moonproof_ledger::serialize::Serializable;

        let mut rng = StdRng::seed_from_u64(1);
        let c = counter_ir_executable().await;
        let zk = fixture_zk_cfg_arc();
        let expected_sk = moonproof_ledger::signatures::schnorr_signing_key(&[0xAAu8; 32]).unwrap();
        let opts = DeployOptions {
            constructor_args: Value::Null,
            initial_private_state: Value::Null,
            signing_key: Some(expected_sk.clone()),
            additional_coin_enc_public_key_mappings: None,
            current_time: Timestamp::from_secs(0),
            network_id: "local-test".to_owned(),
            persistent_state: None,
            fee_balancing: None,
            register_circuits: None,
        };
        let data = create_unproven_deploy_tx_from_keys(
            &mut rng,
            &c,
            &zk,
            crate::types::CoinPublicKey([0u8; 32]),
            crate::types::EncPublicKey([0u8; 32]),
            opts,
        )
        .await
        .unwrap();

        let mut expected_bytes = Vec::new();
        let mut got_bytes = Vec::new();
        expected_sk.serialize(&mut expected_bytes).unwrap();
        data.private.signing_key.serialize(&mut got_bytes).unwrap();
        assert_eq!(expected_bytes, got_bytes);
    }

    /// `register_circuits: None` keeps the default: every circuit the
    /// constructor registers lands in the deployed operations table.
    /// The counter fixture declares exactly one provable circuit.
    #[tokio::test]
    async fn register_circuits_none_registers_every_operation() {
        let mut rng = StdRng::seed_from_u64(0x5A);
        let c = counter_ir_executable().await;
        let zk = fixture_zk_cfg_arc();
        let data = create_unproven_deploy_tx_from_keys(
            &mut rng,
            &c,
            &zk,
            crate::types::CoinPublicKey([0u8; 32]),
            crate::types::EncPublicKey([0u8; 32]),
            fixture_options(),
        )
        .await
        .unwrap();
        assert_eq!(data.public.initial_contract_state.operations.size(), 1);
        let entry: EntryPointBuf = "increment".as_bytes().into();
        assert!(data
            .public
            .initial_contract_state
            .operations
            .get(&entry)
            .is_some());
    }

    /// An empty subset deploys a contract with zero operations — and it
    /// must still be well-formed. This is the floor of the incremental-
    /// deploy strategy: deploy bare ledger + authority, then install
    /// every circuit via maintenance txs.
    #[tokio::test]
    async fn register_circuits_empty_subset_deploys_zero_operations_and_is_well_formed() {
        use moonproof_ledger::ledger::structure::LedgerState;
        use moonproof_ledger::ledger::verify::WellFormedStrictness;

        let mut rng = StdRng::seed_from_u64(0x5B);
        let c = counter_ir_executable().await;
        let zk = fixture_zk_cfg_arc();
        let mut opts = fixture_options();
        opts.register_circuits = Some(Vec::new());
        let data = create_unproven_deploy_tx_from_keys(
            &mut rng,
            &c,
            &zk,
            crate::types::CoinPublicKey([0u8; 32]),
            crate::types::EncPublicKey([0u8; 32]),
            opts,
        )
        .await
        .unwrap();
        assert_eq!(data.public.initial_contract_state.operations.size(), 0);

        let bytes = data
            .private
            .unproven_tx
            .as_ref()
            .unwrap()
            .to_tagged_bytes()
            .unwrap();
        let tx: moonproof_ledger::ledger::structure::Transaction<
            moonproof_ledger::signatures::Signature,
            moonproof_ledger::ledger::structure::ProofPreimageMarker,
            moonproof_ledger::transient_crypto::commitment::PedersenRandomness,
            InMemoryDB,
        > = moonproof_ledger::serialize::tagged_deserialize(&mut bytes.as_slice()).unwrap();
        let ledger_state: LedgerState<InMemoryDB> = LedgerState::new("local-test");
        let mut strictness = WellFormedStrictness::default();
        strictness.enforce_balancing = false;
        tx.well_formed(&ledger_state, strictness, Timestamp::from_secs(0))
            .expect("zero-operation subset deploy must be well-formed");
    }

    /// A subset naming a circuit the contract doesn't declare is a
    /// caller error, surfaced before the tx is built.
    #[tokio::test]
    async fn register_circuits_unknown_circuit_errors() {
        let mut rng = StdRng::seed_from_u64(0x5C);
        let c = counter_ir_executable().await;
        let zk = fixture_zk_cfg_arc();
        let mut opts = fixture_options();
        opts.register_circuits = Some(vec![CircuitId::new("does_not_exist")]);
        let err = create_unproven_deploy_tx_from_keys(
            &mut rng,
            &c,
            &zk,
            crate::types::CoinPublicKey([0u8; 32]),
            crate::types::EncPublicKey([0u8; 32]),
            opts,
        )
        .await
        .unwrap_err();
        assert!(format!("{err}").contains("does_not_exist"), "{err}");
    }
}