moonproof-contracts 0.2.1

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
//! Deploy a contract whose full verifier-key set is too large for one
//! transaction, by splitting the work across several transactions.
//!
//! A transaction must fit the ledger's byte limit and, priced by the
//! ledger's cost model against the current `LedgerParameters`, a share
//! of the block limits: the node gives one normal transaction at most
//! [`NORMAL_TRANSACTION_SHARE_PPM`] of each. A contract's deploy embeds
//! one verifier key per circuit in its `ContractState.operations`
//! table and writes all of them to state, so a contract with enough
//! circuits — or large enough keys — produces a deploy the node
//! refuses, long before its bytes approach the byte limit.
//!
//! The Contract Maintenance Authority makes the circuit set mutable
//! after deploy: [`submit_insert_verifier_keys_tx`](crate::submit_insert_verifier_keys_tx)
//! installs verifier keys for circuits that did not exist at deploy
//! time. So a too-large contract can be deployed in passes:
//!
//! 1. **Deploy pass** — deploy the ledger state (the constructor runs
//!    once, fixing the ledger schema) plus the subset of circuits whose
//!    keys fit alongside it in one transaction
//!    ([`DeployOptions::register_circuits`](crate::DeployOptions::register_circuits)).
//! 2. **Maintenance passes** — install the remaining circuits, one
//!    batch (one transaction) at a time, each batch sized to fit.
//!
//! This module owns the two halves of that: [`plan_deploy`] decides the
//! batches (bin-packing against measured sizes and costs, each batch
//! then checked against the ledger's cost model), and
//! [`deploy_contract_incremental`] executes them.
//!
//! ## Constraints inherited from the maintenance mechanism
//!
//! - **The ledger schema is fixed at deploy.** Only the circuit set is
//!   mutable afterwards. Every ledger field the contract will ever use
//!   must be declared up front — splitting moves *circuits* across
//!   transactions, never *state*.
//! - **The maintenance authority key is the single point of control.**
//!   The deploy installs it; every maintenance pass signs with it. Lose
//!   it and the circuit set freezes permanently. The same key is reused
//!   across all passes here — the deploy persists it under the contract
//!   address and the maintenance passes read it back.

use std::sync::Arc;
use std::time::Duration;

use moonproof_utils::rt::Instant;

use moonproof_ledger::base_crypto::cost_model::{CostDuration, SyntheticCost};
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::ledger::structure::{LedgerParameters, SingleUpdate};
use moonproof_ledger::onchain_runtime::state::{
    ContractMaintenanceAuthority, ContractState, EntryPointBuf, StateValue,
};
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
use rand::{CryptoRng, Rng};

use moonproof_runtime::ir::witnesses::Witnesses;
use moonproof_runtime::ir_executable::IrExecutable;

use crate::contract::{deploy_contract, Contract};
use crate::error::{ContractRuntimeError, Result};
use crate::fee_balancing::FeeBalancingConfig;
use crate::maintenance::{build_unproven_maintenance_tx, MaintenanceTxOptions};
use crate::providers::{ErasedProviders, HasWallet, HasZkConfig, Providers, PublicDataProvider};
use crate::submit_insert_vk_tx::{
    submit_insert_verifier_keys_tx, SubmitInsertVerifierKeysTxOptions,
};
use crate::types::{CircuitId, FinalizedTxData};
use crate::unproven_deploy_tx::{create_unproven_deploy_tx, DeployOptions};

mod plan;

pub use plan::{plan_incremental_deploy, CircuitWeight, CostVector, DeployPlan, PackBudget};

/// Default for the user's per-transaction byte cap: no cap beyond the
/// ledger's and the node's own limits, which [`TransactionBudget`]
/// always applies.
pub const DEFAULT_MAX_TX_BYTES: usize = usize::MAX;

/// The ledger's initial per-transaction byte limit
/// (`INITIAL_LIMITS.transaction_byte_limit`). The limit in force is the
/// current `LedgerParameters`', which [`TransactionBudget`] reads.
pub const LEDGER_TX_BYTE_LIMIT: usize = 1 << 20;

/// midnight-node's block weight: 2 s of reference time, in picoseconds
/// (`runtime/src/lib.rs`, `BlockWeights`).
const BLOCK_REF_TIME_PS: u64 = 2_000_000_000_000;

/// The normal dispatch class's share of a block, in parts per million
/// (`NORMAL_DISPATCH_RATIO`, 75%). Block length is capped the same way.
const NORMAL_DISPATCH_PPM: u64 = 750_000;

/// The share frame-system's `BlockWeights::with_sensible_defaults`
/// reserves for block initialization out of every extrinsic's maximum
/// (`avg_block_initialization(10%)`), in parts per million.
const BLOCK_INITIALIZATION_PPM: u64 = 100_000;

/// The weight the midnight pallet adds to every transaction
/// (`EXTRA_WEIGHT_TX_SIZE`, 2·10¹⁰ ps, 1% of the block), in parts per
/// million.
const TRANSACTION_SIZE_WEIGHT_PPM: u64 = 10_000;

/// frame-support's `ExtrinsicBaseWeight`, 108 157 ns, in picoseconds:
/// subtracted from every normal extrinsic's maximum.
const EXTRINSIC_BASE_WEIGHT_PS: u64 = 108_157_000;

/// The share of each block limit one normal transaction may use, in
/// parts per million. The node weighs a transaction as its largest
/// normalized cost dimension times the block weight
/// (`scale_normalized_cost`), plus the pallet's size weight, and
/// frame-system refuses an extrinsic whose weight exceeds the normal
/// class's maximum, 75% less the initialization reserve and the base
/// extrinsic weight (`CheckWeight::check_extrinsic_weight`).
pub const NORMAL_TRANSACTION_SHARE_PPM: u64 = NORMAL_DISPATCH_PPM
    - BLOCK_INITIALIZATION_PPM
    - TRANSACTION_SIZE_WEIGHT_PPM
    - (EXTRINSIC_BASE_WEIGHT_PS * 1_000_000).div_ceil(BLOCK_REF_TIME_PS);

/// The node's per-block length limit before the normal-class ratio
/// (`BlockLength::max_with_normal_ratio(1024 * 1024, ..)`).
const BLOCK_LENGTH_BYTES: u64 = 1024 * 1024;

/// What the extrinsic adds around the transaction bytes: its compact
/// length prefix (4), version byte (1), call index (2) and the
/// transaction argument's compact length prefix (4).
const EXTRINSIC_FRAMING_BYTES: u64 = 11;

/// The largest transaction one normal extrinsic can carry under the
/// node's block length limit.
const NODE_TRANSACTION_BYTE_LIMIT: u64 =
    BLOCK_LENGTH_BYTES * NORMAL_DISPATCH_PPM / 1_000_000 - EXTRINSIC_FRAMING_BYTES;

/// A transaction's size and modelled cost.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TxMeasure {
    /// The larger of the serialized unproven transaction and the
    /// ledger's estimate of the proven one.
    pub bytes: usize,
    /// The ledger's cost of the transaction, as the node prices it.
    pub cost: SyntheticCost,
}

/// The limits one transaction must fit, from the current
/// `LedgerParameters` and the node's share of a block.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TransactionBudget {
    pub max_bytes: usize,
    pub max_cost: SyntheticCost,
}

impl TransactionBudget {
    /// The budget under `params`, with an optional tighter byte cap.
    #[must_use]
    pub fn new(params: &LedgerParameters, max_tx_bytes: usize) -> Self {
        let byte_limit = params
            .limits
            .transaction_byte_limit
            .min(NODE_TRANSACTION_BYTE_LIMIT);
        let block = params.limits.block_limits;
        // `v * share / 10⁶`, split so the product cannot overflow.
        let scale = |v: u64| {
            v / 1_000_000 * NORMAL_TRANSACTION_SHARE_PPM
                + v % 1_000_000 * NORMAL_TRANSACTION_SHARE_PPM / 1_000_000
        };
        let scale_time =
            |d: CostDuration| CostDuration::from_picoseconds(scale(d.into_picoseconds()));
        Self {
            max_bytes: usize::try_from(byte_limit)
                .unwrap_or(usize::MAX)
                .min(max_tx_bytes),
            max_cost: SyntheticCost {
                read_time: scale_time(block.read_time),
                compute_time: scale_time(block.compute_time),
                block_usage: scale(block.block_usage),
                bytes_written: scale(block.bytes_written),
                bytes_churned: scale(block.bytes_churned),
            },
        }
    }

    /// Why `measure` does not fit, or `None` when it does.
    #[must_use]
    pub fn excess(&self, measure: &TxMeasure) -> Option<String> {
        if measure.bytes > self.max_bytes {
            return Some(format!(
                "{} bytes, over the per-transaction limit of {}",
                measure.bytes, self.max_bytes
            ));
        }
        cost_vector(&measure.cost)
            .first_excess(cost_vector(&self.max_cost))
            .map(|(dimension, used, cap)| {
                format!("{used} {dimension}, over the per-transaction limit of {cap}")
            })
    }
}

fn cost_vector(cost: &SyntheticCost) -> CostVector {
    CostVector {
        read_time_ps: cost.read_time.into_picoseconds(),
        compute_time_ps: cost.compute_time.into_picoseconds(),
        block_usage: cost.block_usage,
        bytes_written: cost.bytes_written,
        bytes_churned: cost.bytes_churned,
    }
}

/// Measure an unproven transaction as the node will price it.
///
/// # Errors
///
/// When the transaction does not serialize, or the cost model refuses
/// it outright (as the node would).
pub fn measure_tx(
    tx: &crate::tx_phase::UnprovenTx,
    params: &LedgerParameters,
) -> Result<TxMeasure> {
    let serialized = tx
        .to_tagged_bytes()
        .map_err(|e| ContractRuntimeError::Provider {
            provider: "measure_tx",
            message: format!("serializing a sizing transaction: {e}"),
        })?
        .len();
    let cost = tx
        .as_inner()
        .cost(params, true)
        .map_err(|e| ContractRuntimeError::Provider {
            provider: "measure_tx",
            message: format!("the ledger's cost model refuses the transaction: {e:?}"),
        })?;
    Ok(TxMeasure {
        bytes: serialized.max(usize::try_from(cost.block_usage).unwrap_or(usize::MAX)),
        cost,
    })
}

/// A circuit named in a plan, paired with its verifier key.
///
/// The orchestrator threads these from the zk-config provider into both
/// the planner (which only reads the key length) and the executors
/// (which install the key bytes).
#[derive(Clone)]
pub struct PlannedCircuit {
    pub id: CircuitId,
    pub vk: crate::types::VerifierKey,
}

/// Fresh dust fee-balancing inputs for one maintenance pass.
pub struct PassFee {
    pub fee_balancing: FeeBalancingConfig,
    /// Chain-tip timestamp for this pass's intent TTL.
    pub current_time: Timestamp,
}

/// Supplies fee-balancing inputs for each maintenance transaction.
///
/// Every pass spends dust, so the same `FeeBalancingConfig` cannot be
/// reused across passes — its `DustState` would double-spend. The
/// orchestrator calls [`PassFees::next_pass`] once before each
/// maintenance transaction; the implementor (the CLI) re-syncs the
/// wallet so each call returns unspent dust and a current chain tip.
#[moonproof_macros::async_trait]
pub trait PassFees: Send + Sync {
    async fn next_pass(&self) -> Result<PassFee>;
}

/// Inputs to [`deploy_contract_incremental`].
pub struct IncrementalDeployOptions<'a> {
    /// The deploy transaction's options. `register_circuits` is
    /// overwritten with the planner's deploy batch — set it to `None`.
    /// `fee_balancing` / `current_time` here apply to the deploy
    /// transaction only; maintenance passes get theirs from
    /// [`IncrementalDeployOptions::pass_fees`].
    pub deploy: DeployOptions,
    /// Every provable circuit and its verifier key. Drives both the
    /// plan (key sizes) and the maintenance inserts (key bytes).
    pub circuits: Vec<PlannedCircuit>,
    /// A byte cap tighter than the ledger's and the node's, which always
    /// apply. [`DEFAULT_MAX_TX_BYTES`] sets none.
    pub max_tx_bytes: usize,
    /// The parameters of the current block: the limits every
    /// transaction is planned against.
    pub ledger_parameters: LedgerParameters,
    /// Network id for the maintenance transactions (matches the
    /// deploy's network).
    pub network_id: String,
    /// Fee source for maintenance passes.
    pub pass_fees: &'a dyn PassFees,
    /// How long to wait for the indexer to reflect a landed transaction
    /// before the next pass (the maintenance counter must advance and
    /// inserted circuits must be visible). Defaults to 60s via
    /// [`IncrementalDeployOptions::new`].
    pub sync_timeout: Duration,
}

impl<'a> IncrementalDeployOptions<'a> {
    /// Build options with the default budget and a 60s indexer-sync
    /// timeout.
    #[must_use]
    pub fn new(
        deploy: DeployOptions,
        circuits: Vec<PlannedCircuit>,
        ledger_parameters: LedgerParameters,
        network_id: String,
        pass_fees: &'a dyn PassFees,
    ) -> Self {
        Self {
            deploy,
            circuits,
            max_tx_bytes: DEFAULT_MAX_TX_BYTES,
            ledger_parameters,
            network_id,
            pass_fees,
            sync_timeout: Duration::from_mins(1),
        }
    }
}

/// Result of one maintenance pass.
pub struct MaintenancePassResult {
    pub circuits: Vec<CircuitId>,
    pub tx: FinalizedTxData,
}

/// Outcome of an incremental deploy.
pub struct IncrementalDeployOutcome<W: Witnesses + 'static> {
    /// The deployed contract handle (from the deploy transaction).
    pub contract: Contract<W>,
    /// The plan that was executed.
    pub plan: DeployPlan,
    /// One entry per maintenance transaction, in order.
    pub maintenance_passes: Vec<MaintenancePassResult>,
}

const SYNC_POLL_INTERVAL: Duration = Duration::from_secs(2);

/// Deploy a contract across as many transactions as its verifier-key
/// set requires.
///
/// Plans the split ([`plan_incremental_deploy`]) from each circuit's
/// measured key size and the measured deploy / maintenance overheads,
/// deploys the ledger plus the deploy batch in one transaction, then
/// installs each remaining batch with a maintenance transaction —
/// waiting for the indexer to reflect each pass before the next so the
/// maintenance authority counter and circuit set are read fresh.
///
/// The deploy installs the maintenance authority signing key and
/// persists it under the contract address; every maintenance pass signs
/// with that same key (read back from the private-state provider).
///
/// # Errors
///
/// Propagates planning errors, the deploy error, any maintenance-pass
/// submission error, and a timeout if the indexer does not reflect a
/// landed pass within `sync_timeout`.
pub async fn deploy_contract_incremental<W, R>(
    rng: &mut R,
    executable: Arc<IrExecutable<W>>,
    providers: Arc<ErasedProviders>,
    options: IncrementalDeployOptions<'_>,
) -> Result<IncrementalDeployOutcome<W>>
where
    W: Witnesses + 'static,
    R: Rng + CryptoRng,
{
    let IncrementalDeployOptions {
        deploy: deploy_opts,
        circuits,
        max_tx_bytes,
        ledger_parameters,
        network_id,
        pass_fees,
        sync_timeout,
    } = options;

    let plan = plan_deploy(
        rng,
        executable.as_ref(),
        providers.as_ref(),
        &deploy_opts,
        &circuits,
        &TransactionBudget::new(&ledger_parameters, max_tx_bytes),
        &ledger_parameters,
    )
    .await?;

    // Index the verifier keys by circuit id for the maintenance passes.
    let vk_of = |id: &CircuitId| {
        circuits
            .iter()
            .find(|c| &c.id == id)
            .map(|c| c.vk.clone())
            .expect("planner only emits circuit ids drawn from `circuits`")
    };

    // (1) Deploy pass — ledger state + the deploy batch's verifier keys.
    let mut deploy_opts = deploy_opts;
    deploy_opts.register_circuits = Some(plan.deploy_batch.clone());
    let contract = Box::pin(deploy_contract(
        rng,
        executable.clone(),
        providers.clone(),
        deploy_opts,
    ))
    .await?;
    let address = *contract.contract_address();

    // Wait for the indexer to surface the freshly-deployed contract
    // before any maintenance query reads its (initially) empty state.
    if !plan.maintenance_batches.is_empty() {
        wait_for_contract_visible(providers.as_ref(), &address, sync_timeout).await?;
    }

    // (2) Maintenance passes — one transaction per remaining batch.
    let mut maintenance_passes = Vec::with_capacity(plan.maintenance_batches.len());
    for batch in &plan.maintenance_batches {
        // Skip circuits already on-chain so a re-run (after an
        // interruption or a partially-applied batch) is idempotent and
        // never trips the "circuit already defined" guard.
        let missing = filter_absent(providers.as_ref(), &address, batch).await?;
        if missing.is_empty() {
            continue;
        }

        let fee = pass_fees.next_pass().await?;
        let batch_circuits: Vec<(CircuitId, crate::types::VerifierKey)> =
            missing.iter().map(|id| (id.clone(), vk_of(id))).collect();

        let tx = submit_insert_verifier_keys_tx(
            rng,
            providers.as_ref(),
            SubmitInsertVerifierKeysTxOptions {
                contract_address: address,
                circuits: batch_circuits,
                current_time: fee.current_time,
                network_id: network_id.clone(),
                fee_balancing: Some(fee.fee_balancing),
            },
        )
        .await?;

        // Gate the next pass on the indexer reflecting this one — the
        // maintenance counter advances per applied update, and the next
        // submit reads it fresh.
        wait_for_circuits_present(providers.as_ref(), &address, &missing, sync_timeout).await?;

        maintenance_passes.push(MaintenancePassResult {
            circuits: missing,
            tx,
        });
    }

    Ok(IncrementalDeployOutcome {
        contract,
        plan,
        maintenance_passes,
    })
}

/// Plan an incremental deploy: measure each circuit's share of a deploy
/// and of a maintenance transaction, pack the circuits under `budget`,
/// then build every planned transaction and check it against `budget`
/// as the ledger prices it, splitting any batch that does not fit.
///
/// The measured transactions carry the deploy's fee balancing, when
/// `base` has it, so the dust spend each transaction gains at submit is
/// inside the budget too.
///
/// Exposed so callers can preview the split — e.g. `moonproof deploy`
/// uses it to report how many passes an `--incremental` deploy would
/// take.
///
/// # Errors
///
/// Propagates measurement (tx-build) errors and
/// [`plan_incremental_deploy`] errors; errors when even an empty deploy,
/// or a lone circuit's maintenance transaction, exceeds the budget.
pub async fn plan_deploy<W, C>(
    rng: &mut (impl Rng + CryptoRng),
    executable: &IrExecutable<W>,
    providers: &C,
    base: &DeployOptions,
    circuits: &[PlannedCircuit],
    budget: &TransactionBudget,
    params: &LedgerParameters,
) -> Result<DeployPlan>
where
    W: Witnesses + 'static,
    C: HasWallet + HasZkConfig + ?Sized,
{
    let deploy_overhead =
        measure_deploy_tx(rng, executable, providers, base, Some(Vec::new()), params).await?;
    if let Some(excess) = budget.excess(&deploy_overhead) {
        return Err(ContractRuntimeError::Provider {
            provider: "plan_deploy",
            message: format!("an empty deploy of this contract already needs {excess}"),
        });
    }
    let fee = base.fee_balancing.as_ref();
    let maintenance_overhead =
        measure_maintenance_tx(rng, &[], &base.network_id, base.current_time, fee, params)?;

    let mut weights = Vec::with_capacity(circuits.len());
    for circuit in circuits {
        let deploy = measure_deploy_tx(
            rng,
            executable,
            providers,
            base,
            Some(vec![circuit.id.clone()]),
            params,
        )
        .await?;
        let maintenance = measure_maintenance_tx(
            rng,
            std::slice::from_ref(circuit),
            &base.network_id,
            base.current_time,
            fee,
            params,
        )?;
        weights.push(CircuitWeight {
            id: circuit.id.clone(),
            vk_bytes: circuit.vk.as_bytes().len(),
            deploy_cost: cost_vector(&deploy.cost)
                .saturating_sub(cost_vector(&deploy_overhead.cost)),
            maintenance_cost: cost_vector(&maintenance.cost)
                .saturating_sub(cost_vector(&maintenance_overhead.cost)),
        });
    }
    let packed = plan_incremental_deploy(
        &weights,
        &PackBudget {
            max_tx_bytes: budget.max_bytes,
            deploy_overhead: deploy_overhead.bytes,
            maintenance_overhead: maintenance_overhead.bytes,
            max_cost: cost_vector(&budget.max_cost),
            deploy_overhead_cost: cost_vector(&deploy_overhead.cost),
            maintenance_overhead_cost: cost_vector(&maintenance_overhead.cost),
        },
    )?;

    // The packing adds measured per-circuit costs; the ledger prices the
    // whole transaction, so check each batch as built.
    let (deploy_batch, spilled) = verify_deploy_batch(
        rng,
        executable,
        providers,
        base,
        budget,
        params,
        packed.deploy_batch,
    )
    .await?;
    let mut pending: std::collections::VecDeque<Vec<CircuitId>> = packed.maintenance_batches.into();
    if !spilled.is_empty() {
        pending.push_back(spilled);
    }
    Ok(DeployPlan {
        deploy_batch,
        maintenance_batches: verify_maintenance_batches(
            rng, base, circuits, budget, params, pending,
        )?,
    })
}

/// Shrink the deploy batch, lightest circuit first, until the deploy
/// fits `budget` as the ledger prices it. Returns the batch kept and the
/// circuits moved out of it.
async fn verify_deploy_batch<W, C>(
    rng: &mut (impl Rng + CryptoRng),
    executable: &IrExecutable<W>,
    providers: &C,
    base: &DeployOptions,
    budget: &TransactionBudget,
    params: &LedgerParameters,
    mut batch: Vec<CircuitId>,
) -> Result<(Vec<CircuitId>, Vec<CircuitId>)>
where
    W: Witnesses + 'static,
    C: HasWallet + HasZkConfig + ?Sized,
{
    let mut spilled = Vec::new();
    while !batch.is_empty() {
        let measure = measure_deploy_tx(
            rng,
            executable,
            providers,
            base,
            Some(batch.clone()),
            params,
        )
        .await?;
        if budget.excess(&measure).is_none() {
            break;
        }
        spilled.extend(batch.pop());
    }
    Ok((batch, spilled))
}

/// Check each maintenance batch as built against `budget`, moving
/// circuits out of one that does not fit into a batch of their own.
fn verify_maintenance_batches(
    rng: &mut (impl Rng + CryptoRng),
    base: &DeployOptions,
    circuits: &[PlannedCircuit],
    budget: &TransactionBudget,
    params: &LedgerParameters,
    mut pending: std::collections::VecDeque<Vec<CircuitId>>,
) -> Result<Vec<Vec<CircuitId>>> {
    let by_id = |id: &CircuitId| {
        circuits
            .iter()
            .find(|c| &c.id == id)
            .cloned()
            .ok_or_else(|| ContractRuntimeError::Provider {
                provider: "plan_deploy",
                message: format!("the plan names unknown circuit '{}'", id.as_str()),
            })
    };
    let mut verified = Vec::new();
    while let Some(mut batch) = pending.pop_front() {
        let mut spilled = Vec::new();
        loop {
            let planned = batch.iter().map(&by_id).collect::<Result<Vec<_>>>()?;
            let measure = measure_maintenance_tx(
                rng,
                &planned,
                &base.network_id,
                base.current_time,
                base.fee_balancing.as_ref(),
                params,
            )?;
            match budget.excess(&measure) {
                None => break,
                Some(excess) if batch.len() == 1 => {
                    return Err(ContractRuntimeError::Provider {
                        provider: "plan_deploy",
                        message: format!(
                            "circuit '{}' alone needs {excess} in a maintenance transaction; \
                             this circuit cannot be deployed",
                            batch[0].as_str()
                        ),
                    });
                }
                Some(_) => spilled.extend(batch.pop()),
            }
        }
        verified.push(batch);
        if !spilled.is_empty() {
            pending.push_back(spilled);
        }
    }
    Ok(verified)
}

/// Build a deploy transaction for `register_circuits` (all circuits when
/// `None`) and measure it, with the fee balancing `base` carries.
///
/// With `Some(vec![])` this is the fixed deploy overhead (ledger state +
/// authority + intent + framing). With `None` it is a single-shot
/// deploy — what `moonproof deploy` checks against the
/// [`TransactionBudget`] before attempting one.
///
/// # Errors
///
/// Propagates tx-build, serialization and cost-model errors.
pub async fn measure_deploy_tx<W, C>(
    rng: &mut (impl Rng + CryptoRng),
    executable: &IrExecutable<W>,
    providers: &C,
    base: &DeployOptions,
    register_circuits: Option<Vec<CircuitId>>,
    params: &LedgerParameters,
) -> Result<TxMeasure>
where
    W: Witnesses + 'static,
    C: HasWallet + HasZkConfig + ?Sized,
{
    let sizing = DeployOptions {
        constructor_args: base.constructor_args.clone(),
        initial_private_state: base.initial_private_state.clone(),
        signing_key: None,
        additional_coin_enc_public_key_mappings: base
            .additional_coin_enc_public_key_mappings
            .clone(),
        current_time: base.current_time,
        network_id: base.network_id.clone(),
        persistent_state: None,
        fee_balancing: base.fee_balancing.clone(),
        register_circuits,
    };
    let unproven = create_unproven_deploy_tx(rng, executable, providers, sizing).await?;
    let tx =
        unproven
            .private
            .unproven_tx
            .as_ref()
            .ok_or_else(|| ContractRuntimeError::Provider {
                provider: "measure_deploy_tx",
                message: "sizing deploy tx was not populated".to_owned(),
            })?;
    measure_tx(tx, params)
}

pub(crate) fn build_sizing_maintenance_tx(
    rng: &mut (impl Rng + CryptoRng),
    circuits: &[PlannedCircuit],
    network_id: &str,
    current_time: Timestamp,
    fee_balancing: Option<&FeeBalancingConfig>,
) -> Result<crate::tx_phase::UnprovenTx> {
    // A throwaway authority whose committee accepts the signature — the
    // transaction's serialized size is independent of which key signs.
    let sizing_sk = moonproof_ledger::signatures::schnorr_signing_key(&[0x01u8; 32])
        .expect("32 bytes parse into a SigningKey");
    let sizing_state = ContractState::<InMemoryDB>::new(
        StateValue::Null,
        StorageHashMap::new(),
        ContractMaintenanceAuthority {
            committee: vec![moonproof_ledger::signatures::maintenance_verifying_key(
                &sizing_sk,
            )],
            threshold: 1,
            counter: 0,
        },
    );
    let mut updates = Vec::with_capacity(circuits.len());
    for circuit in circuits {
        let entry: EntryPointBuf = circuit.id.as_str().as_bytes().into();
        let ledger_vk: moonproof_ledger::transient_crypto::proofs::VerifierKey =
            moonproof_ledger::serialize::tagged_deserialize(&mut circuit.vk.as_bytes()).map_err(
                |e| ContractRuntimeError::Deserialize {
                    context: "measure_maintenance_tx::tagged_deserialize(VerifierKey)",
                    source: e,
                },
            )?;
        updates.push(SingleUpdate::VerifierKeyInsert(
            entry,
            moonproof_ledger::versioned_verifier_key(ledger_vk),
        ));
    }
    build_unproven_maintenance_tx(
        rng,
        MaintenanceTxOptions {
            contract_address: moonproof_ledger::coin_structure::contract::ContractAddress(
                moonproof_ledger::base_crypto::hash::HashOutput([0u8; 32]),
            ),
            on_chain_state: &sizing_state,
            signing_key: &sizing_sk,
            updates,
            current_time,
            network_id: network_id.to_owned(),
            fee_balancing: fee_balancing.cloned(),
        },
    )
}

/// Build a maintenance transaction installing `circuits` against a
/// synthetic state and measure it. The cost model prices a transaction
/// from the transaction alone, so the state it would apply to does not
/// change the measure.
fn measure_maintenance_tx(
    rng: &mut (impl Rng + CryptoRng),
    circuits: &[PlannedCircuit],
    network_id: &str,
    current_time: Timestamp,
    fee_balancing: Option<&FeeBalancingConfig>,
    params: &LedgerParameters,
) -> Result<TxMeasure> {
    let unproven =
        build_sizing_maintenance_tx(rng, circuits, network_id, current_time, fee_balancing)?;
    measure_tx(&unproven, params)
}

/// Return the circuits in `batch` that are NOT yet present in the
/// on-chain operations table. Used to make maintenance passes
/// idempotent across re-runs.
async fn filter_absent<C: Providers + ?Sized>(
    providers: &C,
    address: &moonproof_ledger::coin_structure::contract::ContractAddress,
    batch: &[CircuitId],
) -> Result<Vec<CircuitId>> {
    let state = providers
        .public_data()
        .query_contract_state(address, None)
        .await?;
    let Some(state) = state else {
        // No state visible yet — treat everything as absent; the submit
        // path will re-check and the pre-submit query will catch a truly
        // missing contract.
        return Ok(batch.to_vec());
    };
    Ok(batch
        .iter()
        .filter(|id| {
            let entry: EntryPointBuf = id.as_str().as_bytes().into();
            state.operations.get(&entry).is_none()
        })
        .cloned()
        .collect())
}

/// Poll the indexer until a contract state is visible at `address`.
async fn wait_for_contract_visible<C: Providers + ?Sized>(
    providers: &C,
    address: &moonproof_ledger::coin_structure::contract::ContractAddress,
    timeout: Duration,
) -> Result<()> {
    let start = Instant::now();
    loop {
        if providers
            .public_data()
            .query_contract_state(address, None)
            .await?
            .is_some()
        {
            return Ok(());
        }
        if start.elapsed() >= timeout {
            return Err(ContractRuntimeError::Provider {
                provider: "deploy_contract_incremental",
                message: format!(
                    "timed out after {:?} waiting for the indexer to surface deployed contract {}",
                    timeout,
                    moonproof_runtime::state::contract_address_to_hex(address),
                ),
            });
        }
        moonproof_utils::rt::sleep(SYNC_POLL_INTERVAL).await;
    }
}

/// Poll the indexer until every circuit in `batch` is present in the
/// on-chain operations table — confirming the prior maintenance pass
/// applied and the indexer caught up.
async fn wait_for_circuits_present<C: Providers + ?Sized>(
    providers: &C,
    address: &moonproof_ledger::coin_structure::contract::ContractAddress,
    batch: &[CircuitId],
    timeout: Duration,
) -> Result<()> {
    let start = Instant::now();
    loop {
        if let Some(state) = providers
            .public_data()
            .query_contract_state(address, None)
            .await?
        {
            let all_present = batch.iter().all(|id| {
                let entry: EntryPointBuf = id.as_str().as_bytes().into();
                state.operations.get(&entry).is_some()
            });
            if all_present {
                return Ok(());
            }
        }
        if start.elapsed() >= timeout {
            return Err(ContractRuntimeError::Provider {
                provider: "deploy_contract_incremental",
                message: format!(
                    "timed out after {:?} waiting for the indexer to reflect an inserted batch \
                     ({} circuit(s)) on contract {}",
                    timeout,
                    batch.len(),
                    moonproof_runtime::state::contract_address_to_hex(address),
                ),
            });
        }
        moonproof_utils::rt::sleep(SYNC_POLL_INTERVAL).await;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::providers::{FileSystemZkConfigProvider, ZkConfigProvider};
    use crate::test_helpers::scripted_providers;
    use crate::types::TxStatus;
    use moonproof_ledger::ledger::structure::INITIAL_PARAMETERS;
    use moonproof_runtime::NoWitnesses;
    use moonproof_runtime_ir::RuntimeValue;
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    const FOREIGN_CURVES: &str = "extracted_foreign_curves_provable";

    fn fixtures_dir() -> std::path::PathBuf {
        let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        p.pop();
        p.push("runtime-ir/tests/fixtures");
        p
    }

    /// The 13-circuit foreign-curves contract with compactc's verifier
    /// keys, which only ledger 9 reads.
    async fn foreign_curves() -> (IrExecutable<NoWitnesses>, Vec<PlannedCircuit>) {
        let base = IrExecutable::from_path(
            fixtures_dir().join(format!("{FOREIGN_CURVES}.cbor")),
            Arc::new(NoWitnesses),
        )
        .unwrap();
        let zk = FileSystemZkConfigProvider::new(fixtures_dir().join(FOREIGN_CURVES));
        let mut planned = Vec::new();
        let mut keys = std::collections::HashMap::new();
        for id in base.provable_circuit_ids() {
            let vk = zk.get_verifier_key(&id).await.unwrap();
            keys.insert(id.as_str().to_owned(), vk.clone());
            planned.push(PlannedCircuit { id, vk });
        }
        (base.with_verifier_keys(keys), planned)
    }

    fn deploy_options() -> DeployOptions {
        DeployOptions {
            constructor_args: RuntimeValue::Null,
            initial_private_state: RuntimeValue::Null,
            signing_key: None,
            additional_coin_enc_public_key_mappings: None,
            current_time: Timestamp::from_secs(1_700_000_000),
            network_id: "local-test".to_owned(),
            persistent_state: None,
            fee_balancing: None,
            register_circuits: None,
        }
    }

    #[test]
    fn a_normal_transaction_gets_the_node_share_of_each_block_limit() {
        // 75% normal class, less 10% initialization, 1% size weight and
        // the base extrinsic weight's 54.08 ppm, rounded up.
        assert_eq!(NORMAL_TRANSACTION_SHARE_PPM, 639_945);
        let budget = TransactionBudget::new(&INITIAL_PARAMETERS, DEFAULT_MAX_TX_BYTES);
        let block = INITIAL_PARAMETERS.limits.block_limits;
        assert_eq!(
            budget.max_cost.bytes_written,
            block.bytes_written * NORMAL_TRANSACTION_SHARE_PPM / 1_000_000
        );
        assert_eq!(
            budget.max_cost.compute_time.into_picoseconds(),
            block.compute_time.into_picoseconds() / 1_000_000 * NORMAL_TRANSACTION_SHARE_PPM
        );
        assert_eq!(budget.max_bytes, 786_421);
    }

    #[test]
    fn a_byte_cap_tighter_than_the_limits_wins() {
        let budget = TransactionBudget::new(&INITIAL_PARAMETERS, 12_000);
        assert_eq!(budget.max_bytes, 12_000);
    }

    #[test]
    fn excess_names_the_dimension_over_its_limit() {
        let budget = TransactionBudget::new(&INITIAL_PARAMETERS, DEFAULT_MAX_TX_BYTES);
        let within = TxMeasure {
            bytes: 1_000,
            cost: SyntheticCost::ZERO,
        };
        assert_eq!(budget.excess(&within), None);
        let writes_too_much = TxMeasure {
            bytes: 1_000,
            cost: SyntheticCost {
                bytes_written: budget.max_cost.bytes_written + 1,
                ..SyntheticCost::ZERO
            },
        };
        let excess = budget.excess(&writes_too_much).unwrap();
        assert!(excess.contains("bytes written"), "{excess}");
        let too_large = TxMeasure {
            bytes: budget.max_bytes + 1,
            cost: SyntheticCost::ZERO,
        };
        assert!(budget.excess(&too_large).unwrap().contains("bytes"));
    }

    /// The foreign-curves deploy is far under the byte limit yet writes
    /// more state than one transaction may: a plan by bytes alone ships
    /// it in one transaction the node refuses. The plan by cost splits
    /// it, and every transaction it plans fits as the ledger prices it.
    #[tokio::test]
    async fn the_foreign_curves_deploy_is_split_by_cost_not_bytes() {
        if !moonproof_ledger::HAS_ZKIR_V3 {
            return;
        }
        let (executable, planned) = foreign_curves().await;
        assert_eq!(planned.len(), 13);
        let (providers, _) = scripted_providers(None, None, TxStatus::SucceedEntirely);
        let base = deploy_options();
        let params = INITIAL_PARAMETERS;
        let budget = TransactionBudget::new(&params, DEFAULT_MAX_TX_BYTES);
        let mut rng = StdRng::seed_from_u64(0xF0_C0);

        let single_shot =
            measure_deploy_tx(&mut rng, &executable, &providers, &base, None, &params)
                .await
                .unwrap();
        assert!(single_shot.bytes < budget.max_bytes, "{single_shot:?}");
        let excess = budget
            .excess(&single_shot)
            .expect("the single-shot deploy must exceed the cost limits");
        assert!(excess.contains("bytes written"), "{excess}");

        let plan = plan_deploy(
            &mut rng,
            &executable,
            &providers,
            &base,
            &planned,
            &budget,
            &params,
        )
        .await
        .unwrap();
        assert!(!plan.is_single_shot(), "{plan:?}");
        assert_eq!(plan.total_circuits(), 13);

        let deploy = measure_deploy_tx(
            &mut rng,
            &executable,
            &providers,
            &base,
            Some(plan.deploy_batch.clone()),
            &params,
        )
        .await
        .unwrap();
        assert_eq!(
            budget.excess(&deploy),
            None,
            "deploy batch {:?}",
            plan.deploy_batch
        );
        for batch in &plan.maintenance_batches {
            let circuits: Vec<PlannedCircuit> = batch
                .iter()
                .map(|id| planned.iter().find(|c| &c.id == id).unwrap().clone())
                .collect();
            let measure = measure_maintenance_tx(
                &mut rng,
                &circuits,
                &base.network_id,
                base.current_time,
                None,
                &params,
            )
            .unwrap();
            assert_eq!(budget.excess(&measure), None, "maintenance batch {batch:?}");
        }
    }
}