moonproof-runtime 0.2.1

Wasm-friendly Compact contract runtime core — IR walker, IR-driven circuit executor, contract state, runtime values
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
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
//! [`IrExecutable`] — the runtime-ir-driven off-chain executor.
//!
//! Loads a parsed `contract.mpir` ([`MoonIr`]) plus a host-supplied
//! [`Witnesses`] callback table, and exposes inherent methods for
//! `initialize` (run the constructor) and `execute_circuit` (run a
//! provable circuit body) by walking the IR's Statement / Expression
//! tree at call time.
//!
//! Arguments are `serde_json::Value`. The IR's argument descriptors
//! tell the executor how to encode each `Value` into the
//! `AlignedValue` shape the on-chain VM expects. Callers never build
//! `AlignedValue`s by hand.

use std::sync::{Arc, OnceLock};

use moonproof_ledger::base_crypto::hash::HashOutput;
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::onchain_runtime::ops::Op;
use moonproof_ledger::onchain_runtime::result_mode::ResultModeGather;
use moonproof_ledger::onchain_runtime::state::{
    ContractMaintenanceAuthority, ContractOperation, ContractState, EntryPointBuf, StateValue,
};
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
use moonproof_runtime_ir::ir::{Argument, MoonIr};
use moonproof_runtime_ir::RuntimeValue as Value;

use rand::rngs::StdRng;
use rand::{CryptoRng, Rng, SeedableRng};

use crate::cross_contract::{CallTreeOutcome, CallTreeResult, CallTreeRun, CrossContractSession};
use crate::error::{ContractRuntimeError, Result as RuntimeResult};
use crate::executable::{
    CircuitCallContext, ConstructorContext, ExecuteCircuitResult, InitializeResult,
};
use crate::ir::bytecode::BytecodeVm;
use crate::ir::descriptor::encode_literal;
use crate::ir::error::{IrDriverError, Result};
use crate::ir::index::IrIndex;
use crate::ir::interp::{
    empty_contract_state, empty_effects, encode_input, encode_input_with_index,
    encode_output_with_index, run_statement, InterpState, VarMap, VmSession,
};
use crate::ir::state_value::build_state_value;
use crate::ir::vm_decode::{
    analyze_ops, decode_op, CompiledLedgerQuery, CompiledQueryBody, EvalScope, QueryFlags,
};
use crate::ir::vm_val::VmVal;
use crate::ir::witnesses::Witnesses;
use crate::zswap_local::CompactZswapLocalState;

/// Parsed-once schema for one ledger field. Re-export of the IR's
/// typed [`Storage`](moonproof_runtime_ir::ir::Storage) — kept as a
/// public alias under the historical `LedgerFieldSchema` name so
/// generated code referring to
/// `moonproof_runtime::ir_executable::LedgerFieldSchema` keeps
/// resolving without an emitter rebuild.
pub use moonproof_runtime_ir::ir::Storage as LedgerFieldSchema;

type CachedOperationsMap = StorageHashMap<EntryPointBuf, ContractOperation, InMemoryDB>;

/// Off-chain executor backed by a parsed contract.mpir.
pub struct IrExecutable<W: Witnesses + 'static> {
    ir: Arc<MoonIr>,
    index: Arc<IrIndex>,
    witnesses: Arc<W>,
    /// Lazily-cloned ledger field schemas for FFI/NAPI/WASM callers that
    /// request an owned `Arc<Vec<LedgerFieldSchema>>`. Direct Rust callers
    /// of [`Self::ledger_schema`] read directly from `ir.ledger` with zero
    /// upfront cloning in [`Self::new`].
    ledger_schemas: Arc<OnceLock<Arc<Vec<LedgerFieldSchema>>>>,
    /// Optional per-circuit verifier keys to bake into the
    /// `ContractState`'s operations table during `initialize`. When
    /// present, the resulting deploy carries VKs that the ledger's
    /// `well_formed` check accepts; without them, the operations
    /// register with `None` (the deploy still succeeds, but a real
    /// ledger rejects it because declared operations need a VK).
    verifier_keys: Arc<std::collections::HashMap<String, crate::types::VerifierKey>>,
    /// Cached `ContractState::operations` MPT built once for the current
    /// `verifier_keys` map; invalidated when verifier keys are updated.
    cached_operations: Arc<OnceLock<std::result::Result<CachedOperationsMap, String>>>,
    /// Cached skeleton `StateValue` from `ir.constructor.initial_state`,
    /// built lazily on first `initialize`.
    skeleton_state: Arc<OnceLock<std::result::Result<StateValue<InMemoryDB>, String>>>,
    /// Pre-registered coin commitments threaded into every
    /// `execute_circuit` call's `QueryContext.call_context.com_indices`.
    /// Required for circuits using `update-with-coin-check`
    /// op-classes (e.g. `Cell.writeCoin`).
    coin_commitments: Arc<Vec<(moonproof_ledger::coin_structure::coin::Commitment, u64)>>,
    /// Optional human-readable contract name for execution trace output.
    contract_name: Option<String>,
    /// Default execution trace verbosity for [`Self::execute_circuit`] and
    /// [`Self::execute_call_tree`].
    trace_level: crate::trace::TraceLevel,
    /// Lazily-built IR coverage site index. Never populated unless coverage
    /// instrumentation is requested.
    coverage_map: Arc<OnceLock<Arc<crate::coverage::IrCoverageMap>>>,
}

impl<W: Witnesses + 'static> std::fmt::Debug for IrExecutable<W> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IrExecutable")
            .field("schema_version", &self.ir.schema_version)
            .field("compiler_version", &self.ir.compiler_version)
            .field("circuits", &self.ir.circuits.len())
            .field("witnesses", &self.ir.witnesses.len())
            .finish_non_exhaustive()
    }
}

impl<W: Witnesses + 'static> Clone for IrExecutable<W> {
    fn clone(&self) -> Self {
        Self {
            ir: self.ir.clone(),
            index: self.index.clone(),
            witnesses: self.witnesses.clone(),
            ledger_schemas: self.ledger_schemas.clone(),
            verifier_keys: self.verifier_keys.clone(),
            cached_operations: self.cached_operations.clone(),
            skeleton_state: self.skeleton_state.clone(),
            coin_commitments: self.coin_commitments.clone(),
            contract_name: self.contract_name.clone(),
            trace_level: self.trace_level,
            coverage_map: self.coverage_map.clone(),
        }
    }
}

impl<W: Witnesses + 'static> IrExecutable<W> {
    /// Build an executable from a parsed IR + witnesses callback.
    #[must_use]
    pub fn new(ir: Arc<MoonIr>, witnesses: Arc<W>) -> Self {
        let index = Arc::new(IrIndex::build(&ir));
        Self {
            ir,
            index,
            witnesses,
            ledger_schemas: Arc::new(OnceLock::new()),
            verifier_keys: Arc::new(std::collections::HashMap::new()),
            cached_operations: Arc::new(OnceLock::new()),
            skeleton_state: Arc::new(OnceLock::new()),
            coin_commitments: Arc::new(Vec::new()),
            contract_name: None,
            trace_level: crate::trace::TraceLevel::Off,
            coverage_map: Arc::new(OnceLock::new()),
        }
    }

    /// Lazily build and return the IR coverage site map for this executable.
    #[must_use]
    pub fn coverage_map(&self) -> Arc<crate::coverage::IrCoverageMap> {
        self.coverage_map
            .get_or_init(|| Arc::new(crate::coverage::IrCoverageMap::build(&self.ir)))
            .clone()
    }

    /// Read-only access to a ledger field schema, indexed parallel to
    /// `ir().ledger`, directly borrowing from the underlying `MoonIr`.
    #[must_use]
    pub fn ledger_schema(&self, index: usize) -> Option<&LedgerFieldSchema> {
        self.ir.ledger.get(index).map(|f| &f.storage)
    }

    /// Shared handle to the parsed-once ledger schemas. FFI bindings
    /// hand this out as an opaque Object so emitted code can pass it
    /// to `ContractStateHandle::from_bytes_with_schemas` without
    /// re-parsing per call.
    #[must_use]
    pub fn ledger_schemas_arc(&self) -> Arc<Vec<LedgerFieldSchema>> {
        self.ledger_schemas
            .get_or_init(|| Arc::new(self.ir.ledger.iter().map(|f| f.storage.clone()).collect()))
            .clone()
    }

    /// Convenience: load an IR file from disk and build the executable.
    pub fn from_path(path: impl AsRef<std::path::Path>, witnesses: Arc<W>) -> Result<Self> {
        let ir = moonproof_runtime_ir::from_path(path)?;
        Ok(Self::new(Arc::new(ir), witnesses))
    }

    /// Parse an IR CBOR byte slice (typically
    /// `include_bytes!("contract.mpir")`) and build the executable.
    /// Avoids disk IO at runtime.
    pub fn from_cbor_slice(bytes: &[u8], witnesses: Arc<W>) -> Result<Self> {
        let ir = moonproof_runtime_ir::from_cbor_slice(bytes)?;
        Ok(Self::new(Arc::new(ir), witnesses))
    }

    /// Read-only access to the underlying IR (useful for callers that
    /// want to introspect circuit signatures, ledger schema, etc.).
    #[must_use]
    pub fn ir(&self) -> &MoonIr {
        &self.ir
    }

    #[cfg(test)]
    #[must_use]
    pub(crate) fn index(&self) -> &IrIndex {
        &self.index
    }

    /// Attach verifier keys to be embedded into the
    /// `ContractOperation` table during `initialize`. Map is keyed by
    /// circuit name (matching the IR's `circuits[].name` and the
    /// `register-operations` list). Required for the deploy to pass
    /// `Transaction::well_formed`.
    #[must_use]
    pub fn with_verifier_keys(
        mut self,
        keys: std::collections::HashMap<String, crate::types::VerifierKey>,
    ) -> Self {
        self.verifier_keys = Arc::new(keys);
        self.cached_operations = Arc::new(OnceLock::new());
        self
    }

    /// In-place setter — use when the caller holds `&mut` to an
    /// already-Arc'd executable (e.g. via [`std::sync::Arc::make_mut`]).
    pub fn set_verifier_keys(
        &mut self,
        keys: std::collections::HashMap<String, crate::types::VerifierKey>,
    ) {
        self.verifier_keys = Arc::new(keys);
        self.cached_operations = Arc::new(OnceLock::new());
    }

    /// Attach a single verifier key keyed by circuit name. Convenience
    /// wrapper over [`with_verifier_keys`](Self::with_verifier_keys).
    #[must_use]
    pub fn with_verifier_key(
        mut self,
        circuit_name: impl Into<String>,
        vk: crate::types::VerifierKey,
    ) -> Self {
        Arc::make_mut(&mut self.verifier_keys).insert(circuit_name.into(), vk);
        self.cached_operations = Arc::new(OnceLock::new());
        self
    }

    /// Attach pre-registered coin commitments. Each tuple is
    /// `(coin_commitment, merkle_tree_index)`. Required for circuits
    /// using `update-with-coin-check` op-classes (e.g.
    /// `Cell.writeCoin`).
    #[must_use]
    pub fn with_coin_commitments(
        mut self,
        commitments: Vec<(moonproof_ledger::coin_structure::coin::Commitment, u64)>,
    ) -> Self {
        self.coin_commitments = Arc::new(commitments);
        self
    }

    /// Attach a human-readable contract name used when rendering execution
    /// traces (falls back to a short contract address hex when omitted).
    #[must_use]
    pub fn with_contract_name(mut self, name: impl Into<String>) -> Self {
        self.contract_name = Some(name.into());
        self
    }

    /// Configure the default [`crate::trace::TraceLevel`] for circuit
    /// executions on this executable.
    #[must_use]
    pub fn with_trace_level(mut self, level: crate::trace::TraceLevel) -> Self {
        self.trace_level = level;
        self
    }

    /// Circuit ids the IR marks as exported AND provable.
    #[must_use]
    pub fn provable_circuit_ids(&self) -> Vec<crate::types::CircuitId> {
        self.ir
            .circuits
            .iter()
            .filter(|c| c.proof && c.exported)
            .map(|c| crate::types::CircuitId::new(c.name.clone()))
            .collect()
    }

    /// Verifier key for a circuit, if attached via
    /// [`with_verifier_keys`](Self::with_verifier_keys).
    #[must_use]
    pub fn embedded_verifier_key(
        &self,
        circuit_id: &crate::types::CircuitId,
    ) -> Option<crate::types::VerifierKey> {
        self.verifier_keys.get(circuit_id.as_str()).cloned()
    }

    fn skeleton_state(&self) -> RuntimeResult<StateValue<InMemoryDB>> {
        let res = self.skeleton_state.get_or_init(|| {
            build_state_value(&self.ir.constructor.initial_state).map_err(|e| e.to_string())
        });
        match res {
            Ok(sv) => Ok(sv.clone()),
            Err(msg) => Err(driver_to_runtime_err(IrDriverError::InvalidIr(msg.clone()))),
        }
    }

    fn cached_operations(&self) -> RuntimeResult<CachedOperationsMap> {
        let res = self.cached_operations.get_or_init(|| {
            let mut operations = StorageHashMap::new();
            for op_name in &self.ir.constructor.register_operations {
                let entry: EntryPointBuf = op_name.as_bytes().into();
                let op = match self.verifier_keys.get(op_name) {
                    Some(vk) => {
                        let parsed: moonproof_ledger::transient_crypto::proofs::VerifierKey =
                            moonproof_ledger::serialize::tagged_deserialize(&mut vk.as_bytes())
                                .map_err(|e| {
                                    format!(
                                        "verifier key for '{op_name}' failed to tagged_deserialize: {e}"
                                    )
                                })?;
                        moonproof_ledger::contract_operation(Some(parsed))
                    }
                    None => moonproof_ledger::contract_operation(None),
                };
                operations = operations.insert(entry, op);
            }
            Ok(operations)
        });
        match res {
            Ok(ops) => Ok(ops.clone()),
            Err(msg) => Err(driver_to_runtime_err(IrDriverError::InvalidIr(msg.clone()))),
        }
    }

    /// Run the contract's constructor. `args` is a JSON Value matching
    /// the IR's constructor argument signature: a single value for a
    /// 1-arg constructor, an Array for positional, or an Object keyed
    /// by argument name for named.
    #[expect(
        clippy::unused_async,
        clippy::unused_async_trait_impl,
        reason = "public async API that callers and generated bindings await; a plain fn returning a ready future would run the body eagerly at call time"
    )]
    pub async fn initialize(
        &self,
        ctx: ConstructorContext,
        args: Value,
    ) -> RuntimeResult<InitializeResult> {
        self.initialize_inner(ctx, &args, true)
    }

    #[cfg(test)]
    pub(crate) fn initialize_ast_only(
        &self,
        ctx: ConstructorContext,
        args: &Value,
    ) -> RuntimeResult<InitializeResult> {
        self.initialize_inner(ctx, args, false)
    }

    fn initialize_inner(
        &self,
        ctx: ConstructorContext,
        args: &Value,
        use_bytecode: bool,
    ) -> RuntimeResult<InitializeResult> {
        // Reuse the cached skeleton StateValue and registered operations MPT
        // (rebuilt only when verifier keys change).
        let skeleton_data = self.skeleton_state()?;
        let operations = self.cached_operations()?;
        let dummy_address = ContractAddress(HashOutput([0u8; 32]));
        let constructor_time = match ctx.time {
            Some(time) => time,
            None => web_time::SystemTime::now()
                .duration_since(web_time::UNIX_EPOCH)
                .map(|d| Timestamp::from_secs(d.as_secs()))
                .map_err(|e| {
                    driver_to_runtime_err(IrDriverError::VmOp(format!(
                        "system clock is before the UNIX epoch: {e}"
                    )))
                })?,
        };

        let body = &self.ir.constructor.body;
        let body_is_noop = matches!(body, moonproof_runtime_ir::ir::Statement::Noop);
        let compiled_ctor = if use_bytecode && !body_is_noop {
            self.index.compiled_constructor(&self.ir)
        } else {
            None
        };

        let init_ops_need_args = self.init_ops_need_args();
        let args_map = if init_ops_need_args || (!body_is_noop && compiled_ctor.is_none()) {
            Some(
                bind_args(&self.ir.constructor.arguments, args, "constructor")
                    .map_err(driver_to_runtime_err)?,
            )
        } else {
            None
        };
        let args_vm = if let Some(compiled) = compiled_ctor {
            Some((
                compiled,
                bind_args_vm(&self.ir.constructor.arguments, args, "constructor")
                    .map_err(driver_to_runtime_err)?,
            ))
        } else {
            if args_map.is_none() {
                let _ = bind_args_vm(&self.ir.constructor.arguments, args, "constructor")
                    .map_err(driver_to_runtime_err)?;
            }
            None
        };

        let mut vm_session = VmSession::from_state_value(skeleton_data.clone());
        let empty_args = VarMap::default();
        self.run_init_ops_on_session(
            &mut vm_session,
            &skeleton_data,
            args_map.as_ref().unwrap_or(&empty_args),
            dummy_address,
            constructor_time,
        )?;

        let (final_state, private_state, zswap_state) = self.run_constructor_body(
            vm_session,
            skeleton_data,
            dummy_address,
            constructor_time,
            ctx.initial_private_state,
            CompactZswapLocalState::empty(ctx.coin_public_key),
            args_vm,
            args_map,
        )?;

        let contract_state = ContractState::<InMemoryDB>::new(
            final_state,
            operations,
            ContractMaintenanceAuthority::default(),
        );

        Ok(InitializeResult {
            initial_contract_state: contract_state,
            initial_private_state: private_state,
            initial_zswap_local_state: zswap_state,
        })
    }

    #[allow(clippy::too_many_arguments)]
    fn run_constructor_body(
        &self,
        vm_session: VmSession,
        skeleton_data: StateValue<InMemoryDB>,
        dummy_address: ContractAddress,
        constructor_time: Timestamp,
        private_state: Value,
        zswap_state: CompactZswapLocalState,
        args_vm: Option<(&crate::ir::bytecode::CompiledCircuit, Vec<VmVal>)>,
        args_map: Option<VarMap>,
    ) -> RuntimeResult<(StateValue<InMemoryDB>, Value, CompactZswapLocalState)> {
        let body = &self.ir.constructor.body;
        if matches!(body, moonproof_runtime_ir::ir::Statement::Noop) {
            return Ok((vm_session.into_state_value(), private_state, zswap_state));
        }
        if let Some((compiled, ctor_args_vm)) = args_vm {
            let mut vm = BytecodeVm::new(
                &self.ir,
                &self.index,
                empty_contract_state(),
                dummy_address,
                private_state,
                0,
                self.witnesses.clone() as Arc<dyn crate::witnesses::Witnesses>,
                Vec::new(),
                zswap_state,
                constructor_time,
                None,
                None,
                Some(vm_session),
            );
            vm.run_root(compiled, ctor_args_vm)
                .map_err(driver_to_runtime_err)?;
            let final_state = vm
                .vm_session
                .take()
                .map_or(skeleton_data, VmSession::into_state_value);
            return Ok((final_state, vm.private_state, vm.next_zswap_local_state));
        }
        let mut state = InterpState {
            ir: &self.ir,
            index: Some(&self.index),
            contract_state: empty_contract_state(),
            contract_address: dummy_address,
            private_state,
            locals: VarMap::default(),
            args: args_map.unwrap_or_default(),
            public_transcript: Vec::new(),
            private_transcript_outputs: Vec::new(),
            popeq_read_results: Vec::new(),
            witnesses: self.witnesses.clone() as Arc<dyn crate::witnesses::Witnesses>,
            coin_commitments: Vec::new(),
            next_zswap_local_state: zswap_state,
            emitted_events: Vec::new(),
            tblock: constructor_time,
            caller: None,
            call_tree: None,
            effects: empty_effects(),
            vm_session: Some(vm_session),
            contract_label: String::new(),
            circuit_name: String::new(),
            trace: None,
            trace_level: crate::trace::TraceLevel::Off,
            trace_depth: 0,
            coverage: None,
        };
        run_statement(&mut state, body).map_err(driver_to_runtime_err)?;
        let final_state = state
            .vm_session
            .take()
            .map_or(skeleton_data, VmSession::into_state_value);
        Ok((
            final_state,
            state.private_state,
            state.next_zswap_local_state,
        ))
    }

    fn init_ops_need_args(&self) -> bool {
        self.ir.constructor.init_ops.iter().any(|expr| {
            let moonproof_runtime_ir::ir::Expression::AdtOp(inv) = expr else {
                return true;
            };
            match self.index.compiled_query(&self.ir, &inv.vm_ops) {
                Some(q) => !matches!(q.body, CompiledQueryBody::Static(_)),
                None => true,
            }
        })
    }

    fn run_init_ops_on_session(
        &self,
        session: &mut VmSession,
        skeleton_data: &StateValue<InMemoryDB>,
        args_map: &VarMap,
        address: ContractAddress,
        time: Timestamp,
    ) -> RuntimeResult<()> {
        if self.ir.constructor.init_ops.is_empty() {
            return Ok(());
        }
        let empty_locals = VarMap::default();
        let scope = EvalScope {
            ir: &self.ir,
            locals: &empty_locals,
            args: args_map,
        };
        let total_ops: usize = self
            .ir
            .constructor
            .init_ops
            .iter()
            .map(|e| match e {
                moonproof_runtime_ir::ir::Expression::AdtOp(inv) => inv.vm_ops.len(),
                _ => 0,
            })
            .sum();
        let mut batched_ops: Vec<Op<ResultModeGather, InMemoryDB>> = Vec::with_capacity(total_ops);
        let mut combined_flags = QueryFlags::READ_ONLY_STATE;
        let mut has_control_flow = false;
        for invocation in &self.ir.constructor.init_ops {
            let invocation = match invocation {
                moonproof_runtime_ir::ir::Expression::AdtOp(inv) => inv,
                other => {
                    return Err(driver_to_runtime_err(IrDriverError::InvalidIr(format!(
                        "init-ops entry not an adt-op: {other:?}"
                    ))));
                }
            };
            let start = batched_ops.len();
            if let Some(compiled) = self.index.compiled_query(&self.ir, &invocation.vm_ops) {
                combined_flags = combined_flags.union(compiled.flags);
                match &compiled.body {
                    CompiledQueryBody::Static(ops) => batched_ops.extend_from_slice(ops),
                    CompiledQueryBody::Dynamic(compiled_ops) => {
                        for op in compiled_ops {
                            batched_ops
                                .push(op.materialize(&scope).map_err(driver_to_runtime_err)?);
                        }
                    }
                }
            } else {
                for instr in &invocation.vm_ops {
                    batched_ops.push(decode_op(instr, &scope).map_err(driver_to_runtime_err)?);
                }
                combined_flags = combined_flags.union(analyze_ops(&batched_ops[start..]));
            }
            if !has_control_flow
                && batched_ops[start..]
                    .iter()
                    .any(|op| matches!(op, Op::Branch { .. } | Op::Jmp { .. }))
            {
                has_control_flow = true;
            }
        }
        // Execute all init-ops in a single VM program when none use relative
        // control-flow (`Branch`/`Jmp`). If any init-op contains `Branch`/`Jmp`
        // (whose skip offsets are scoped to a single op sequence) or the
        // batched run errors, fall back to sequential execution on a clean
        // session so the exact failing init-op is reported.
        if !has_control_flow {
            if combined_flags.reads_context {
                session.ensure_context(&empty_contract_state(), address, time, &[], None);
            }
            if session
                .run_ops(&batched_ops, combined_flags, || "init-ops batch".to_owned())
                .is_ok()
            {
                return Ok(());
            }
            *session = VmSession::from_state_value(skeleton_data.clone());
        }
        self.run_init_ops_sequential(session, &scope, address, time)
    }

    fn run_init_ops_sequential(
        &self,
        session: &mut VmSession,
        scope: &EvalScope<'_>,
        address: ContractAddress,
        time: Timestamp,
    ) -> RuntimeResult<()> {
        for invocation in &self.ir.constructor.init_ops {
            let moonproof_runtime_ir::ir::Expression::AdtOp(invocation) = invocation else {
                continue;
            };
            let (ops, flags): (Vec<Op<ResultModeGather, InMemoryDB>>, QueryFlags) =
                if let Some(compiled) = self.index.compiled_query(&self.ir, &invocation.vm_ops) {
                    let ops = match &compiled.body {
                        CompiledQueryBody::Static(ops) => ops.clone(),
                        CompiledQueryBody::Dynamic(compiled_ops) => {
                            CompiledLedgerQuery::materialize_dynamic(compiled_ops, scope)
                                .map_err(driver_to_runtime_err)?
                        }
                    };
                    (ops, compiled.flags)
                } else {
                    let ops = invocation
                        .vm_ops
                        .iter()
                        .map(|i| decode_op(i, scope))
                        .collect::<std::result::Result<Vec<_>, IrDriverError>>()
                        .map_err(driver_to_runtime_err)?;
                    let flags = analyze_ops(&ops);
                    (ops, flags)
                };
            if flags.reads_context {
                session.ensure_context(&empty_contract_state(), address, time, &[], None);
            }
            session
                .run_ops(&ops, flags, || {
                    format!(
                        "init-op '{}.{}' failed",
                        invocation.adt, invocation.operation
                    )
                })
                .map_err(driver_to_runtime_err)?;
        }
        Ok(())
    }

    /// Run a provable circuit. `args` is a JSON Value matching the
    /// circuit's argument signature: a single value for 1-arg, an
    /// Array for positional, or an Object keyed by argument name for
    /// named.
    ///
    /// A circuit that calls another contract fails here; run it with
    /// [`execute_call_tree`](Self::execute_call_tree).
    #[expect(
        clippy::unused_async,
        clippy::unused_async_trait_impl,
        reason = "public async API that callers and generated bindings await; a plain fn returning a ready future would run the body eagerly at call time"
    )]
    pub async fn execute_circuit(
        &self,
        circuit_name: &str,
        ctx: CircuitCallContext,
        args: Value,
    ) -> RuntimeResult<ExecuteCircuitResult> {
        let mut local_trace = self
            .trace_level
            .is_enabled()
            .then(crate::trace::ExecutionTrace::new);
        let mut res = self
            .run_circuit(
                circuit_name,
                ctx,
                &args,
                self.witnesses.clone() as Arc<dyn Witnesses>,
                None,
                self.trace_level,
                local_trace.as_mut(),
                None,
            )
            .map_err(driver_to_runtime_err)?;
        res.trace = local_trace;
        Ok(res)
    }

    /// Like [`Self::execute_circuit`], recording into a caller-supplied
    /// [`crate::trace::ExecutionTrace`] so partial traces remain available
    /// even when execution reverts.
    #[expect(
        clippy::unused_async,
        clippy::unused_async_trait_impl,
        reason = "public async API matching execute_circuit"
    )]
    pub async fn execute_circuit_traced(
        &self,
        circuit_name: &str,
        ctx: CircuitCallContext,
        args: Value,
        trace_level: crate::trace::TraceLevel,
        trace: Option<&mut crate::trace::ExecutionTrace>,
    ) -> RuntimeResult<ExecuteCircuitResult> {
        self.run_circuit(
            circuit_name,
            ctx,
            &args,
            self.witnesses.clone() as Arc<dyn Witnesses>,
            None,
            trace_level,
            trace,
            None,
        )
        .map_err(driver_to_runtime_err)
    }

    /// Like [`Self::execute_circuit_traced`], also recording into an optional
    /// [`crate::coverage::IrCoverageCollector`]. Both `trace` and `coverage`
    /// capture partial execution up to and including an assertion revert.
    #[allow(clippy::too_many_arguments)]
    #[expect(
        clippy::unused_async,
        clippy::unused_async_trait_impl,
        reason = "public async API matching execute_circuit"
    )]
    pub async fn execute_circuit_instrumented(
        &self,
        circuit_name: &str,
        ctx: CircuitCallContext,
        args: Value,
        trace_level: crate::trace::TraceLevel,
        trace: Option<&mut crate::trace::ExecutionTrace>,
        coverage: Option<&mut crate::coverage::IrCoverageCollector>,
    ) -> RuntimeResult<ExecuteCircuitResult> {
        self.run_circuit(
            circuit_name,
            ctx,
            &args,
            self.witnesses.clone() as Arc<dyn Witnesses>,
            None,
            trace_level,
            trace,
            coverage,
        )
        .map_err(driver_to_runtime_err)
    }

    /// Run a provable circuit together with every cross-contract call
    /// it makes.
    ///
    /// The callees' code and deployed state come from `session`. A run
    /// that reaches an address `session` has no binding for returns
    /// [`CallTreeOutcome::CalleeRequired`]; bind it with
    /// [`CrossContractSession::bind_callee`] and call this again with
    /// the same `ctx` and `args`. Witness results observed by an earlier
    /// run are replayed rather than asked for again.
    pub async fn execute_call_tree<R: Rng + CryptoRng>(
        &self,
        rng: &mut R,
        circuit_name: &str,
        ctx: CircuitCallContext,
        args: Value,
        session: &mut CrossContractSession,
    ) -> RuntimeResult<CallTreeOutcome> {
        let mut local_trace = self
            .trace_level
            .is_enabled()
            .then(crate::trace::ExecutionTrace::new);
        let outcome = self
            .execute_call_tree_traced(
                rng,
                circuit_name,
                ctx,
                args,
                session,
                self.trace_level,
                local_trace.as_mut(),
            )
            .await?;
        match outcome {
            CallTreeOutcome::Executed(mut tree) => {
                tree.root.trace = local_trace;
                Ok(CallTreeOutcome::Executed(tree))
            }
            other @ CallTreeOutcome::CalleeRequired(_) => Ok(other),
        }
    }

    /// Like [`Self::execute_call_tree`], recording into a caller-supplied
    /// [`crate::trace::ExecutionTrace`] so partial call trees remain
    /// available even when a root or callee circuit reverts.
    #[allow(clippy::too_many_arguments)]
    pub async fn execute_call_tree_traced<R: Rng + CryptoRng>(
        &self,
        rng: &mut R,
        circuit_name: &str,
        ctx: CircuitCallContext,
        args: Value,
        session: &mut CrossContractSession,
        trace_level: crate::trace::TraceLevel,
        trace: Option<&mut crate::trace::ExecutionTrace>,
    ) -> RuntimeResult<CallTreeOutcome> {
        self.execute_call_tree_instrumented(
            rng,
            circuit_name,
            ctx,
            args,
            session,
            trace_level,
            trace,
            None,
        )
        .await
    }

    /// Like [`Self::execute_call_tree_traced`], also recording into an
    /// optional [`crate::coverage::IrCoverageCollector`].
    #[allow(clippy::too_many_arguments)]
    #[expect(
        clippy::unused_async,
        clippy::unused_async_trait_impl,
        reason = "public async API matching execute_call_tree"
    )]
    pub async fn execute_call_tree_instrumented<R: Rng + CryptoRng>(
        &self,
        rng: &mut R,
        circuit_name: &str,
        ctx: CircuitCallContext,
        args: Value,
        session: &mut CrossContractSession,
        trace_level: crate::trace::TraceLevel,
        mut trace: Option<&mut crate::trace::ExecutionTrace>,
        mut coverage: Option<&mut crate::coverage::IrCoverageCollector>,
    ) -> RuntimeResult<CallTreeOutcome> {
        let seed = StdRng::from_rng(rng).map_err(|e| {
            driver_to_runtime_err(IrDriverError::CrossContract(format!(
                "seeding the call tree's randomness: {e}"
            )))
        })?;
        let (mut run, witnesses) =
            session.start_run(self.witnesses.clone() as Arc<dyn Witnesses>, seed);
        run.active.push(ctx.contract_address);
        if let Some(t) = trace.as_deref_mut() {
            t.clear();
        }
        if let Some(c) = coverage.as_deref_mut() {
            c.clear();
        }
        let outcome = self.run_circuit(
            circuit_name,
            ctx,
            &args,
            witnesses.clone() as Arc<dyn Witnesses>,
            Some(&mut run),
            trace_level,
            trace,
            coverage,
        );
        session
            .finish_run(&witnesses)
            .map_err(driver_to_runtime_err)?;
        if let Some(address) = run.required {
            return Ok(CallTreeOutcome::CalleeRequired(address));
        }
        let root = outcome.map_err(driver_to_runtime_err)?;
        Ok(CallTreeOutcome::Executed(Box::new(CallTreeResult {
            root,
            callees: run.calls,
        })))
    }

    #[cfg(test)]
    pub(crate) fn execute_call_tree_ast_only<R: Rng + CryptoRng>(
        &self,
        rng: &mut R,
        circuit_name: &str,
        ctx: CircuitCallContext,
        args: &Value,
        session: &mut CrossContractSession,
    ) -> RuntimeResult<CallTreeOutcome> {
        let seed = StdRng::from_rng(rng).map_err(|e| {
            driver_to_runtime_err(IrDriverError::CrossContract(format!(
                "seeding the call tree's randomness: {e}"
            )))
        })?;
        let (mut run, witnesses) =
            session.start_run(self.witnesses.clone() as Arc<dyn Witnesses>, seed);
        run.active.push(ctx.contract_address);
        let outcome = self.run_circuit_inner(
            circuit_name,
            ctx,
            args,
            witnesses.clone() as Arc<dyn Witnesses>,
            Some(&mut run),
            crate::trace::TraceLevel::Off,
            None,
            None,
            false,
        );
        session
            .finish_run(&witnesses)
            .map_err(driver_to_runtime_err)?;
        if let Some(address) = run.required {
            return Ok(CallTreeOutcome::CalleeRequired(address));
        }
        let root = outcome.map_err(driver_to_runtime_err)?;
        Ok(CallTreeOutcome::Executed(Box::new(CallTreeResult {
            root,
            callees: run.calls,
        })))
    }

    #[cfg(test)]
    pub(crate) fn run_circuit_ast_only(
        &self,
        circuit_name: &str,
        ctx: CircuitCallContext,
        args: &Value,
        call_tree: Option<&mut CallTreeRun>,
    ) -> Result<ExecuteCircuitResult> {
        self.run_circuit_inner(
            circuit_name,
            ctx,
            args,
            self.witnesses.clone() as Arc<dyn Witnesses>,
            call_tree,
            crate::trace::TraceLevel::Off,
            None,
            None,
            false,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn run_circuit(
        &self,
        circuit_name: &str,
        ctx: CircuitCallContext,
        args: &Value,
        witnesses: Arc<dyn Witnesses>,
        call_tree: Option<&mut CallTreeRun>,
        trace_level: crate::trace::TraceLevel,
        trace: Option<&mut crate::trace::ExecutionTrace>,
        coverage: Option<&mut crate::coverage::IrCoverageCollector>,
    ) -> Result<ExecuteCircuitResult> {
        self.run_circuit_inner(
            circuit_name,
            ctx,
            args,
            witnesses,
            call_tree,
            trace_level,
            trace,
            coverage,
            true,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn run_circuit_inner(
        &self,
        circuit_name: &str,
        ctx: CircuitCallContext,
        args: &Value,
        witnesses: Arc<dyn Witnesses>,
        call_tree: Option<&mut CallTreeRun>,
        trace_level: crate::trace::TraceLevel,
        mut trace: Option<&mut crate::trace::ExecutionTrace>,
        coverage: Option<&mut crate::coverage::IrCoverageCollector>,
        use_bytecode: bool,
    ) -> Result<ExecuteCircuitResult> {
        let circuit_idx = self
            .index
            .first_circuit_index(&self.ir, circuit_name)
            .ok_or_else(|| IrDriverError::UnknownCircuit(circuit_name.to_string()))?;
        let circuit = &self.ir.circuits[circuit_idx];

        if use_bytecode && trace_level == crate::trace::TraceLevel::Off && coverage.is_none() {
            if let Some(compiled) = self.index.compiled_circuit(&self.ir, circuit_idx) {
                return self
                    .run_circuit_bytecode(circuit, compiled, ctx, args, witnesses, call_tree);
            }
        }

        let args_map = bind_args(&circuit.arguments, args, &circuit.name)?;
        let tracing_active = trace_level.is_enabled() && trace.is_some();
        let (contract_label, circuit_label, active_trace) = if tracing_active {
            let contract_label = self
                .contract_name
                .clone()
                .unwrap_or_else(|| crate::trace::short_address(&ctx.contract_address));
            let circuit_label = circuit.name.clone();
            if let Some(t) = trace.as_deref_mut() {
                t.push(crate::trace::TraceEvent::CircuitEnter {
                    contract: contract_label.clone(),
                    circuit: circuit_label.clone(),
                    args: args.clone(),
                    depth: 0,
                });
            }
            (contract_label, circuit_label, trace)
        } else {
            (String::new(), String::new(), None)
        };

        let effects = empty_effects();
        let transcript_cap = self.index.estimated_transcript_ops(&self.ir, circuit);
        let coin_commitments = if self.coin_commitments.is_empty() {
            Vec::new()
        } else {
            (*self.coin_commitments).clone()
        };

        let mut state = InterpState {
            ir: &self.ir,
            index: Some(&self.index),
            // `ctx` is owned here, so move the state in rather than
            // clone it — the caller already handed us ownership.
            contract_state: ctx.contract_state,
            contract_address: ctx.contract_address,
            private_state: ctx.private_state,
            locals: VarMap::default(),
            args: args_map,
            public_transcript: Vec::with_capacity(transcript_cap),
            private_transcript_outputs: Vec::new(),
            popeq_read_results: Vec::new(),
            witnesses,
            coin_commitments,
            next_zswap_local_state: CompactZswapLocalState::empty(ctx.coin_public_key),
            emitted_events: Vec::new(),
            tblock: ctx.tblock,
            caller: None,
            call_tree,
            effects,
            vm_session: None,
            contract_label,
            circuit_name: circuit_label,
            trace: active_trace,
            trace_level,
            trace_depth: 0,
            coverage,
        };

        if let Some(cov) = state.coverage.as_deref_mut() {
            cov.record_circuit(circuit);
        }
        let result_value = run_statement(&mut state, &circuit.body)?;
        state.try_sync_from_query_context()?;

        if let Some(t) = state.trace.as_deref_mut() {
            t.push(crate::trace::TraceEvent::CircuitExit {
                contract: std::mem::take(&mut state.contract_label),
                circuit: std::mem::take(&mut state.circuit_name),
                result: result_value.clone(),
                depth: 0,
            });
        }

        let input_av = encode_input_with_index(&self.ir, Some(&self.index), circuit, &state.args)?;
        let output_av =
            encode_output_with_index(&self.ir, Some(&self.index), circuit, &result_value)?;

        Ok(ExecuteCircuitResult {
            next_contract_state: state.contract_state,
            next_private_state: state.private_state,
            next_zswap_local_state: state.next_zswap_local_state,
            emitted_events: state.emitted_events,
            input: input_av,
            output: output_av,
            result: result_value,
            public_transcript: state.public_transcript,
            private_transcript_outputs: state.private_transcript_outputs,
            popeq_read_results: state.popeq_read_results,
            effects: state.effects,
            trace: None,
        })
    }

    fn run_circuit_bytecode(
        &self,
        circuit: &moonproof_runtime_ir::ir::CircuitBody,
        compiled: &crate::ir::bytecode::CompiledCircuit,
        ctx: CircuitCallContext,
        args: &Value,
        witnesses: Arc<dyn Witnesses>,
        call_tree: Option<&mut CallTreeRun>,
    ) -> Result<ExecuteCircuitResult> {
        let args_vm = bind_args_vm(&circuit.arguments, args, &circuit.name)?;
        let transcript_cap = self.index.estimated_transcript_ops(&self.ir, circuit);
        let coin_commitments = if self.coin_commitments.is_empty() {
            Vec::new()
        } else {
            (*self.coin_commitments).clone()
        };

        let mut vm = BytecodeVm::new(
            &self.ir,
            &self.index,
            ctx.contract_state,
            ctx.contract_address,
            ctx.private_state,
            transcript_cap,
            witnesses,
            coin_commitments,
            CompactZswapLocalState::empty(ctx.coin_public_key),
            ctx.tblock,
            None,
            call_tree,
            None,
        );

        let result_vm = vm.run_root(compiled, args_vm)?;
        vm.sync_vm_session()?;

        let io_plan = self.index.circuit_io_plan(&self.ir, circuit);
        let input_av = if let Some(plan) = io_plan.and_then(|io| io.input.as_ref()) {
            plan.encode_vm_vals(&circuit.name, &vm.regs[..circuit.arguments.len()])?
        } else {
            let args_map = bind_args(&circuit.arguments, args, &circuit.name)?;
            encode_input(circuit, &args_map)?
        };
        let output_av = if matches!(
            &circuit.result_type,
            moonproof_runtime_ir::ir::TypeDescriptor::Tuple { types } if types.is_empty()
        ) {
            moonproof_ledger::base_crypto::fab::AlignedValue::concat(std::iter::empty::<
                &moonproof_ledger::base_crypto::fab::AlignedValue,
            >())
        } else if let Some(plan) = io_plan.and_then(|io| io.output.as_ref()) {
            plan.encode_vm_val(&result_vm)?
        } else {
            encode_literal(&circuit.result_type, &result_vm.to_runtime_value())?
        };
        let result_value = result_vm.into_runtime_value();

        Ok(ExecuteCircuitResult {
            next_contract_state: vm.contract_state,
            next_private_state: vm.private_state,
            next_zswap_local_state: vm.next_zswap_local_state,
            emitted_events: vm.emitted_events,
            input: input_av,
            output: output_av,
            result: result_value,
            public_transcript: vm.public_transcript,
            private_transcript_outputs: vm.private_transcript_outputs,
            popeq_read_results: vm.popeq_read_results,
            effects: vm.effects,
            trace: None,
        })
    }
}

/// Bind a JSON `args` Value directly into positional [`VmVal`] register slots
/// without allocating a `VarMap` or cloning argument names.
fn bind_args_vm(defs: &[Argument], args: &Value, context: &str) -> Result<Vec<VmVal>> {
    if defs.is_empty() {
        return Ok(Vec::new());
    }
    if defs.len() == 1 {
        return Ok(vec![VmVal::from_runtime_value(args)]);
    }
    let mut out = Vec::with_capacity(defs.len());
    match args {
        Value::Array(arr) => {
            if arr.len() != defs.len() {
                return Err(IrDriverError::ArgCount {
                    context: format!("{context} (positional)"),
                    expected: defs.len(),
                    got: arr.len(),
                });
            }
            for v in arr {
                out.push(VmVal::from_runtime_value(v));
            }
        }
        Value::Object(map) => {
            for arg in defs {
                let v = map.get(&arg.name).ok_or_else(|| IrDriverError::ArgCount {
                    context: format!("{context} arg '{}'", arg.name),
                    expected: defs.len(),
                    got: map.len(),
                })?;
                out.push(VmVal::from_runtime_value(v));
            }
        }
        _ => {
            return Err(IrDriverError::TypeMismatch(format!(
                "{context} expects {} args (use Array or Object); got {args}",
                defs.len()
            )));
        }
    }
    Ok(out)
}

/// Bind a JSON `args` Value to a `name → Value` map, validating
/// against the IR's argument descriptors. Accepts:
///
/// - Single value when `defs.len() == 1`
/// - Array (positional) when `arr.len() == defs.len()`
/// - Object keyed by argument name
fn bind_args(defs: &[Argument], args: &Value, context: &str) -> Result<VarMap> {
    let mut out = VarMap::with_capacity_and_hasher(defs.len(), rustc_hash::FxBuildHasher);
    if defs.is_empty() {
        return Ok(out);
    }
    if defs.len() == 1 {
        out.insert(defs[0].name.clone(), args.clone());
        return Ok(out);
    }
    match args {
        Value::Array(arr) => {
            if arr.len() != defs.len() {
                return Err(IrDriverError::ArgCount {
                    context: format!("{context} (positional)"),
                    expected: defs.len(),
                    got: arr.len(),
                });
            }
            for (def, v) in defs.iter().zip(arr.iter()) {
                out.insert(def.name.clone(), v.clone());
            }
        }
        Value::Object(map) => {
            for arg in defs {
                let v = map
                    .get(&arg.name)
                    .cloned()
                    .ok_or_else(|| IrDriverError::ArgCount {
                        context: format!("{context} arg '{}'", arg.name),
                        expected: defs.len(),
                        got: map.len(),
                    })?;
                out.insert(arg.name.clone(), v);
            }
        }
        _ => {
            return Err(IrDriverError::TypeMismatch(format!(
                "{context} expects {} args (use Array or Object); got {args}",
                defs.len()
            )));
        }
    }
    Ok(out)
}

fn driver_to_runtime_err(e: IrDriverError) -> ContractRuntimeError {
    match e {
        IrDriverError::AssertionFailed(message) => ContractRuntimeError::AssertionFailed(message),
        other => ContractRuntimeError::Provider {
            provider: "runtime-ir-driver",
            message: other.to_string(),
        },
    }
}