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
//! End-to-end test: drive the **midnight-ledger** `micro-dao` contract
//! through the IR driver. Source:
//! `midnight-ledger/3ad9d45/ledger/tests/micro-dao.compact` (committed
//! under `crates/runtime-ir/tests/fixtures/micro_dao.compact`).
//!
//! micro-dao is a DAO voting contract with 7 exported circuits,
//! witnesses for every private-state operation, and ledger fields of
//! type `Counter`, `Set<Bytes<32>>`, `MerkleTree<10, Bytes<32>>`,
//! `HistoricMerkleTree<10, Bytes<32>>`, `Maybe<...>`, and
//! `QualifiedShieldedCoinInfo`.

use std::collections::BTreeMap;
use std::sync::Arc;

use moonproof_ledger::base_crypto::hash::HashOutput;
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::ledger::structure::INITIAL_PARAMETERS;
use moonproof_ledger::signatures::SigningKey;
use moonproof_runtime::executable::{CircuitCallContext, ConstructorContext, InitializeResult};
use moonproof_runtime::types::CoinPublicKey;
use moonproof_runtime::CompactZswapLocalState;
use moonproof_runtime::{IrDriverError, IrExecutable, Witnesses};
use moonproof_runtime_ir::RuntimeValue as Value;

#[derive(Debug, Default)]
struct MicroDaoWitnesses;

impl Witnesses for MicroDaoWitnesses {
    fn invoke(
        &self,
        name: &str,
        _args: &Value,
        ps: &Value,
    ) -> Result<moonproof_runtime::witnesses::WitnessResult, IrDriverError> {
        let observed = match name {
            "localSecretKey" => Value::Bytes(vec![0u8; 32]),
            "localState" => Value::String("initial".to_string()),
            "localAdvanceState" | "localRecordVote" | "createZswapOutput" | "createZswapInput" => {
                Value::Array(Vec::new())
            }
            "localVoteCast" => {
                let mut obj = BTreeMap::new();
                obj.insert("is_some".to_string(), Value::Bool(false));
                obj.insert("value".to_string(), Value::Bool(false));
                Value::Object(obj)
            }
            "localPathOfPk" | "localPathOfCm" => {
                let mut obj = BTreeMap::new();
                obj.insert("is_some".to_string(), Value::Bool(false));
                let mut inner = BTreeMap::new();
                inner.insert("leaf".to_string(), Value::Bytes(vec![0u8; 32]));
                let path: Vec<Value> = (0..10)
                    .map(|_| {
                        let mut step = BTreeMap::new();
                        step.insert("sibling".to_string(), Value::Bytes(vec![0u8; 32]));
                        step.insert("goes_left".to_string(), Value::Bool(false));
                        Value::Object(step)
                    })
                    .collect();
                inner.insert("path".to_string(), Value::Array(path));
                obj.insert("value".to_string(), Value::Object(inner));
                Value::Object(obj)
            }
            other => {
                return Err(IrDriverError::Witness(format!(
                    "unexpected witness '{other}' for micro-dao"
                )));
            }
        };
        Ok(moonproof_runtime::witnesses::WitnessResult {
            observed,
            next_private_state: ps.clone(),
        })
    }
}

/// Witnesses bound to a specific known secret key so we can set up
/// the contract such that the organizer assertions pass.
#[derive(Debug)]
struct AuthorizedWitnesses {
    secret_key: [u8; 32],
}

impl Witnesses for AuthorizedWitnesses {
    fn invoke(
        &self,
        name: &str,
        _args: &Value,
        ps: &Value,
    ) -> Result<moonproof_runtime::witnesses::WitnessResult, IrDriverError> {
        let observed = match name {
            "localSecretKey" => Value::Bytes(self.secret_key.to_vec()),
            "localState" => Value::String("initial".to_string()),
            "localAdvanceState" | "localRecordVote" => Value::Array(Vec::new()),
            other => {
                return Err(IrDriverError::Witness(format!(
                    "witness '{other}' not provided"
                )));
            }
        };
        Ok(moonproof_runtime::witnesses::WitnessResult {
            observed,
            next_private_state: ps.clone(),
        })
    }
}

/// Witnesses that satisfy cashOut's auth chain: localSecretKey is a
/// known SK (matches the organizer the test patches in).
#[derive(Debug)]
struct CashOutWitnesses {
    secret_key: [u8; 32],
}

impl Witnesses for CashOutWitnesses {
    fn invoke(
        &self,
        name: &str,
        _args: &Value,
        ps: &Value,
    ) -> Result<moonproof_runtime::witnesses::WitnessResult, IrDriverError> {
        let observed = match name {
            "localSecretKey" => Value::Bytes(self.secret_key.to_vec()),
            "createZswapOutput" | "createZswapInput" | "localAdvanceState" | "localRecordVote" => {
                Value::Array(Vec::new())
            }
            "localState" => Value::String("initial".to_string()),
            other => {
                return Err(IrDriverError::Witness(format!(
                    "unexpected witness '{other}' for cashOut chain"
                )));
            }
        };
        Ok(moonproof_runtime::witnesses::WitnessResult {
            observed,
            next_private_state: ps.clone(),
        })
    }
}

/// Build the `setTopic(newTopic: Opaque<"string">, newBeneficiary: ZswapCoinPublicKey)` args.
fn set_topic_args(topic: &str, beneficiary_pk: [u8; 32]) -> Value {
    let mut beneficiary = BTreeMap::new();
    beneficiary.insert("bytes".to_string(), Value::Bytes(beneficiary_pk.to_vec()));
    let mut obj = BTreeMap::new();
    obj.insert("newTopic".to_string(), Value::String(topic.to_string()));
    obj.insert("newBeneficiary".to_string(), Value::Object(beneficiary));
    Value::Object(obj)
}

/// Build a `ShieldedCoinInfo { nonce: Bytes<32>, color: Bytes<32>, value: Uint<...> }`.
fn shielded_coin_info(nonce: [u8; 32], color: [u8; 32], value: u64) -> Value {
    let mut obj = BTreeMap::new();
    obj.insert("nonce".to_string(), Value::Bytes(nonce.to_vec()));
    obj.insert("color".to_string(), Value::Bytes(color.to_vec()));
    obj.insert("value".to_string(), Value::Int(i128::from(value)));
    Value::Object(obj)
}

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

fn dummy_signing_key() -> SigningKey {
    moonproof_ledger::signatures::schnorr_signing_key(&[0x42u8; 32]).expect("32 bytes parse")
}

fn dummy_coin_public_key() -> CoinPublicKey {
    CoinPublicKey([0u8; 32])
}

fn dummy_contract_address() -> ContractAddress {
    ContractAddress(HashOutput([0x77u8; 32]))
}

fn ctor_ctx() -> ConstructorContext {
    ConstructorContext {
        initial_private_state: Value::Null,
        initial_zswap_local_state: CompactZswapLocalState::empty(dummy_coin_public_key()),
        coin_public_key: dummy_coin_public_key(),
        signing_key: dummy_signing_key(),
        time: None,
    }
}

fn fresh_call_ctx(
    state: moonproof_ledger::onchain_runtime::state::ContractState<
        moonproof_ledger::storage::db::InMemoryDB,
    >,
) -> CircuitCallContext {
    CircuitCallContext {
        contract_address: dummy_contract_address(),
        contract_state: state,
        private_state: Value::Null,
        ledger_parameters: INITIAL_PARAMETERS.clone(),
        coin_public_key: dummy_coin_public_key(),
        tblock: Timestamp::from_secs(0),
    }
}

async fn loaded() -> (IrExecutable<MicroDaoWitnesses>, InitializeResult) {
    let exec =
        IrExecutable::from_path(ir_path(), Arc::new(MicroDaoWitnesses)).expect("micro_dao loads");
    let init = exec
        .initialize(ctor_ctx(), Value::Null)
        .await
        .expect("initialize");
    (exec, init)
}

/// Outcome of driving a circuit through the IR. Three possibilities:
/// 1. `Cleanly` — circuit ran end-to-end and returned a result.
/// 2. `ContractAssert(msg)` — a `Expression::Assert` inside the
///    contract fired (e.g. authority check failed). Driver behaviour
///    is correct.
/// 3. `VmFault(msg)` — the VM rejected an op (e.g. type mismatch).
///    Distinct from `Unimplemented` driver gaps.
enum CircuitOutcome {
    Cleanly,
    ContractAssert(String),
    VmFault(String),
}

impl std::fmt::Display for CircuitOutcome {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Cleanly => f.write_str("ran cleanly"),
            Self::ContractAssert(msg) => write!(f, "contract assert: {msg}"),
            Self::VmFault(msg) => write!(f, "VM fault: {msg}"),
        }
    }
}

async fn drive_circuit(
    exec: &IrExecutable<MicroDaoWitnesses>,
    init: &InitializeResult,
    name: &str,
    args: Value,
) -> CircuitOutcome {
    let result = exec
        .execute_circuit(
            name,
            fresh_call_ctx(init.initial_contract_state.clone()),
            args,
        )
        .await;
    match result {
        Ok(_) => CircuitOutcome::Cleanly,
        Err(e) => {
            let msg = format!("{e}");
            assert!(
                !msg.contains("unimplemented IR construct"),
                "{name} hit a driver gap: {msg}"
            );
            if msg.contains("assert failed") {
                CircuitOutcome::ContractAssert(msg)
            } else {
                CircuitOutcome::VmFault(msg)
            }
        }
    }
}

/// Compute `publicKey(sk) = persistentCommit<Bytes<13>>("lares:udao:pk", sk)`
/// using the same crypto primitives the IR driver would invoke. This
/// gives us an organizer value that matches what the contract's own
/// `publicKey()` helper would compute for the given secret key.
fn micro_dao_public_key(sk: [u8; 32]) -> [u8; 32] {
    use moonproof_ledger::base_crypto::fab::{
        AlignedValue, Alignment, AlignmentAtom, Value as FabValue, ValueAtom,
    };
    use moonproof_ledger::base_crypto::hash::{persistent_commit, HashOutput as Ho};
    use moonproof_ledger::transient_crypto::fab::ValueReprAlignedValue;
    let value_av = AlignedValue::new(
        FabValue(vec![ValueAtom(b"lares:udao:pk".to_vec())]),
        Alignment::singleton(AlignmentAtom::Bytes { length: 13 }),
    )
    .expect("Bytes<13>");
    let Ho(out) = persistent_commit(&ValueReprAlignedValue(value_av), Ho(sk));
    out
}

/// Patch the `organizer: Bytes<32>` ledger slot (index 0) in the
/// contract state to a specific 32-byte value. Equivalent to running
/// `organizer = disclose(pk)` at the VM level, but bypasses the
/// constructor (which doesn't take an organizer arg).
fn patch_organizer(
    state: &mut moonproof_ledger::onchain_runtime::state::ContractState<
        moonproof_ledger::storage::db::InMemoryDB,
    >,
    pk: [u8; 32],
) {
    use moonproof_ledger::base_crypto::fab::AlignedValue;
    use moonproof_ledger::onchain_runtime::context::QueryContext;
    use moonproof_ledger::onchain_runtime::cost_model::INITIAL_COST_MODEL;
    use moonproof_ledger::onchain_runtime::ops::Op;
    use moonproof_ledger::onchain_runtime::result_mode::ResultModeGather;
    use moonproof_ledger::onchain_runtime::state::{AlignedValueChecked, StateValue};
    use moonproof_ledger::storage::arena::Sp;
    use moonproof_ledger::storage::db::InMemoryDB;

    // organizer is at index 0 in the contract's ledger array. Patch
    // pattern: push key, push new-value-cell, ins n=1.
    let ops: Vec<Op<ResultModeGather, InMemoryDB>> = vec![
        Op::Push {
            storage: false,
            value: StateValue::Cell(Sp::new(AlignedValueChecked::from(0u8))),
        },
        Op::Push {
            storage: true,
            value: StateValue::Cell(Sp::new(
                AlignedValueChecked::try_from(AlignedValue::from(pk))
                    .expect("bytes atoms are always canonical"),
            )),
        },
        Op::Ins {
            cached: false,
            n: 1.try_into().unwrap(),
        },
    ];
    let qctx = QueryContext::new(state.data.clone(), dummy_contract_address());
    let result = qctx
        .query::<ResultModeGather>(&ops, None, &INITIAL_COST_MODEL)
        .expect("organizer patch ops succeed");
    state.data = result.context.state;
}

/// Compute the coin commitment for a `(coin, contract_address)` pair
/// the same way `CoinInfo::commitment(&Recipient::Contract(addr))`
/// does upstream — used to register coin commitments in
/// `IrExecutable`'s `coin_commitments` so `update-with-coin-check`
/// op-classes can resolve their merkle-tree-index lookups.
fn micro_dao_coin_commitment(
    nonce: [u8; 32],
    color: [u8; 32],
    value: u128,
    contract_addr: ContractAddress,
) -> moonproof_ledger::coin_structure::coin::Commitment {
    use moonproof_ledger::coin_structure::coin::{Info, Nonce, ShieldedTokenType};
    let info = Info {
        nonce: Nonce(HashOutput(nonce)),
        type_: ShieldedTokenType(HashOutput(color)),
        value,
    };
    info.commitment(&moonproof_ledger::coin_structure::transfer::Recipient::Contract(contract_addr))
}

#[tokio::test]
async fn ir_micro_dao_loads_and_lists_circuits() {
    let exec =
        IrExecutable::from_path(ir_path(), Arc::new(MicroDaoWitnesses)).expect("micro_dao loads");
    let names: Vec<String> = exec.ir().circuits.iter().map(|c| c.name.clone()).collect();
    for name in &[
        "voteCommit",
        "voteReveal",
        "advance",
        "setTopic",
        "buyIn",
        "cashOut",
    ] {
        assert!(
            names.contains(&(*name).to_string()),
            "expected '{name}' in circuits {names:?}"
        );
    }
}

/// Run the full constructor pipeline: builds initial-state skeleton
/// for 11 ledger fields, runs `resetToDefault` for each, registers 7
/// provable circuit operations.
#[tokio::test]
async fn ir_micro_dao_initialize_succeeds() {
    let (_exec, init) = loaded().await;
    let mut bytes = Vec::new();
    moonproof_ledger::serialize::tagged_serialize(&init.initial_contract_state, &mut bytes)
        .unwrap();
    assert_ne!(bytes, Vec::<u8>::new());
}

// ===== Walks-full-IR smoke tests ====================================
// These tests drive each exported circuit from a fresh deploy without
// any state setup. Most will fire a contract-level assert (auth check
// fails because witnesses return placeholders) — that's fine; the
// load-bearing claim is that the IR walks the body to that point
// without hitting an `Unimplemented` driver gap.

#[tokio::test]
async fn ir_micro_dao_advance_walks_full_ir() {
    let (exec, init) = loaded().await;
    let outcome = drive_circuit(&exec, &init, "advance", Value::Null).await;
    eprintln!("advance: {outcome}");
}

#[tokio::test]
async fn ir_micro_dao_set_topic_walks_full_ir() {
    let (exec, init) = loaded().await;
    let args = set_topic_args("hello", [0x88u8; 32]);
    let outcome = drive_circuit(&exec, &init, "setTopic", args).await;
    eprintln!("setTopic: {outcome}");
}

#[tokio::test]
async fn ir_micro_dao_vote_commit_walks_full_ir() {
    let (exec, init) = loaded().await;
    let outcome = drive_circuit(&exec, &init, "voteCommit", Value::Bool(true)).await;
    eprintln!("voteCommit: {outcome}");
}

#[tokio::test]
async fn ir_micro_dao_vote_reveal_walks_full_ir() {
    let (exec, init) = loaded().await;
    let outcome = drive_circuit(&exec, &init, "voteReveal", Value::Null).await;
    eprintln!("voteReveal: {outcome}");
}

#[tokio::test]
async fn ir_micro_dao_buy_in_walks_full_ir() {
    let (exec, init) = loaded().await;
    let coin = shielded_coin_info([0xAAu8; 32], [0xBBu8; 32], 100_000);
    let outcome = drive_circuit(&exec, &init, "buyIn", coin).await;
    eprintln!("buyIn: {outcome}");
}

#[tokio::test]
async fn ir_micro_dao_cash_out_walks_full_ir() {
    let (exec, init) = loaded().await;
    let outcome = drive_circuit(&exec, &init, "cashOut", Value::Null).await;
    eprintln!("cashOut: {outcome}");
}

// ===== Single-step success: setTopic with matching authority ========

/// **End-to-end success path**: set up the contract with a known
/// organizer, call `setTopic` with matching auth, and assert the
/// circuit completes WITHOUT firing a contract-level assert.
///
/// This is the load-bearing claim that "the IR driver matches the JS
/// path": not just rejecting equivalently, but ACCEPTING equivalently.
#[tokio::test]
async fn ir_micro_dao_set_topic_succeeds_with_correct_authority() {
    let known_sk = [0xABu8; 32];
    let organizer_pk = micro_dao_public_key(known_sk);

    let exec = IrExecutable::from_path(
        ir_path(),
        Arc::new(AuthorizedWitnesses {
            secret_key: known_sk,
        }),
    )
    .expect("micro-dao IR loads");
    let mut init = exec
        .initialize(ctor_ctx(), Value::Null)
        .await
        .expect("initialize");

    patch_organizer(&mut init.initial_contract_state, organizer_pk);

    let result = exec
        .execute_circuit(
            "setTopic",
            fresh_call_ctx(init.initial_contract_state),
            set_topic_args("hello-dao", [0x88u8; 32]),
        )
        .await
        .expect("setTopic with valid auth should succeed");

    assert!(
        !result.public_transcript.is_empty(),
        "setTopic must emit a non-empty public transcript"
    );
    assert!(
        result.result.is_null() || matches!(&result.result, Value::Array(a) if a.is_empty()),
        "setTopic returns unit"
    );
}

// ===== Multi-step chains ============================================

/// **Multi-step end-to-end success path**: deploy → patch organizer →
/// setTopic (setup→commit) → advance (commit→reveal). Proves the IR
/// driver correctly threads state across multiple successful circuit
/// calls. Shape-differs gate on each step.
#[tokio::test]
async fn ir_micro_dao_set_topic_then_advance_chain_succeeds() {
    let known_sk = [0xCDu8; 32];
    let organizer_pk = micro_dao_public_key(known_sk);

    let exec = IrExecutable::from_path(
        ir_path(),
        Arc::new(AuthorizedWitnesses {
            secret_key: known_sk,
        }),
    )
    .expect("micro-dao loads");
    let init = exec.initialize(ctor_ctx(), Value::Null).await.unwrap();

    let mut state = init.initial_contract_state.clone();
    patch_organizer(&mut state, organizer_pk);

    // Snapshot the (patched) pre-circuit state so we can assert
    // setTopic actually moved the bytes — separately from the patch.
    let mut pre_set_topic = Vec::new();
    moonproof_ledger::serialize::tagged_serialize(&state, &mut pre_set_topic).unwrap();

    // Step 1: setTopic — transitions setup → commit.
    let after_set_topic = exec
        .execute_circuit(
            "setTopic",
            fresh_call_ctx(state),
            set_topic_args("topic", [0x88u8; 32]),
        )
        .await
        .expect("setTopic step 1 succeeds (setup → commit)");

    let mut post_set_topic = Vec::new();
    moonproof_ledger::serialize::tagged_serialize(
        &after_set_topic.next_contract_state,
        &mut post_set_topic,
    )
    .unwrap();
    assert_ne!(
        pre_set_topic, post_set_topic,
        "setTopic must advance the on-chain state"
    );
    assert!(
        post_set_topic.len() >= pre_set_topic.len() / 2,
        "post-setTopic state shrank suspiciously"
    );

    // Step 2: advance — commit → reveal.
    let after_advance = exec
        .execute_circuit(
            "advance",
            fresh_call_ctx(after_set_topic.next_contract_state),
            Value::Null,
        )
        .await
        .expect("advance step 2 (commit → reveal) succeeds");

    let mut post_advance = Vec::new();
    moonproof_ledger::serialize::tagged_serialize(
        &after_advance.next_contract_state,
        &mut post_advance,
    )
    .unwrap();
    assert_ne!(
        post_set_topic, post_advance,
        "advance must transition state from commit to reveal"
    );
    assert_ne!(after_advance.public_transcript, []);
}

/// **3-step state-machine traversal**: setTopic (setup→commit) →
/// advance (commit→reveal) → advance (reveal→final). Once in final,
/// the contract's `if (state == final && yes < no)` block is
/// evaluated; both yes and no are 0 so `0 < 0` is false → state stays
/// final, no reset. Proves the IR driver correctly handles the
/// branching logic and the full state machine.
#[tokio::test]
async fn ir_micro_dao_full_state_transition_chain_succeeds() {
    let known_sk = [0xEFu8; 32];
    let organizer_pk = micro_dao_public_key(known_sk);

    let exec = IrExecutable::from_path(
        ir_path(),
        Arc::new(AuthorizedWitnesses {
            secret_key: known_sk,
        }),
    )
    .expect("loads");
    let init = exec.initialize(ctor_ctx(), Value::Null).await.unwrap();
    let mut state = init.initial_contract_state.clone();
    patch_organizer(&mut state, organizer_pk);

    // setTopic: setup → commit
    let after_set_topic = exec
        .execute_circuit(
            "setTopic",
            fresh_call_ctx(state),
            set_topic_args("chain-test", [0x88u8; 32]),
        )
        .await
        .expect("setTopic step 1 succeeds (setup → commit)");

    // advance: commit → reveal
    let after_advance_1 = exec
        .execute_circuit(
            "advance",
            fresh_call_ctx(after_set_topic.next_contract_state),
            Value::Null,
        )
        .await
        .expect("advance step 2 succeeds (commit → reveal)");

    // advance: reveal → final. Triggers the `if state==final && yes<no`
    // branch evaluation (both 0 → false → no reset).
    let after_advance_2 = exec
        .execute_circuit(
            "advance",
            fresh_call_ctx(after_advance_1.next_contract_state),
            Value::Null,
        )
        .await
        .expect("advance step 3 succeeds (reveal → final, no reset)");

    assert_ne!(after_advance_2.public_transcript, []);
    let mut bytes = Vec::new();
    moonproof_ledger::serialize::tagged_serialize(&after_advance_2.next_contract_state, &mut bytes)
        .unwrap();
    assert!(bytes.len() > 100);
}

/// **End-to-end success path for cashOut**: chain setTopic → advance →
/// advance → cashOut. The chain transitions setup → commit → reveal →
/// final, and cashOut runs at final-state with `beneficiary == ownPublicKey`.
///
/// `pot` is the default-zero `QualifiedShieldedCoinInfo` at this point
/// (no buyIn has been called). `sendShielded(pot, ...)` walks
/// `update-with-coin-check` — we register the pot's commitment so the
/// lookup resolves.
#[tokio::test]
async fn ir_micro_dao_cash_out_succeeds_end_to_end() {
    use moonproof_ledger::coin_structure::coin::{Info, Nonce, ShieldedTokenType};
    use moonproof_ledger::coin_structure::transfer::Recipient;
    let known_sk = [0xC0u8; 32];
    let organizer_pk = micro_dao_public_key(known_sk);
    let beneficiary_pk = [0xBEu8; 32];
    let _contract_addr = dummy_contract_address();

    // Compute the commitment of the default-zero pot against
    // `Recipient::User(beneficiary_pk)` so cashOut's `sendShielded` can
    // find it.
    let pot_coin_info = Info {
        nonce: Nonce(HashOutput([0u8; 32])),
        type_: ShieldedTokenType(HashOutput([0u8; 32])),
        value: 0,
    };
    let pot_recipient = Recipient::User(moonproof_ledger::coin_structure::coin::PublicKey(
        HashOutput(beneficiary_pk),
    ));
    let pot_commitment = pot_coin_info.commitment(&pot_recipient);

    let witnesses = Arc::new(CashOutWitnesses {
        secret_key: known_sk,
    });
    let exec = IrExecutable::from_path(ir_path(), witnesses)
        .expect("loads")
        .with_coin_commitments(vec![(pot_commitment, 0u64)]);

    let init = exec.initialize(ctor_ctx(), Value::Null).await.unwrap();

    let mut state = init.initial_contract_state.clone();
    patch_organizer(&mut state, organizer_pk);

    // Step 1: setTopic with beneficiary = beneficiary_pk.
    let r1 = exec
        .execute_circuit(
            "setTopic",
            fresh_call_ctx(state),
            set_topic_args("cashout-test", beneficiary_pk),
        )
        .await
        .expect("setTopic with valid auth + beneficiary succeeds");

    // Step 2: advance × 2 (commit → reveal → final).
    let mut current = r1.next_contract_state;
    for step in 1..=2 {
        let r = exec
            .execute_circuit("advance", fresh_call_ctx(current), Value::Null)
            .await
            .unwrap_or_else(|e| panic!("advance step {step} failed: {e}"));
        current = r.next_contract_state;
    }

    // Step 3: cashOut. State should now be final, beneficiary=beneficiary_pk,
    // and the beneficiary is the caller, so ownPublicKey=beneficiary_pk and
    // the assert passes.
    let mut cash_out_ctx = fresh_call_ctx(current);
    cash_out_ctx.coin_public_key = CoinPublicKey(beneficiary_pk);
    let result = exec
        .execute_circuit("cashOut", cash_out_ctx, Value::Null)
        .await
        .expect(
            "cashOut at final state with matching beneficiary must run end-to-end \
             through sendShielded + state reset",
        );
    eprintln!(
        "cashOut ran end-to-end: {} public-transcript ops, {} private-transcript outputs",
        result.public_transcript.len(),
        result.private_transcript_outputs.len()
    );
    assert_ne!(result.public_transcript, []);
}

/// Drive `buyIn(coin)` to success.
///
/// Setup:
/// - `coin.value == 100000` and `coin.color == nativeToken()` (32 zeros)
///   to satisfy the contract's value/color assert.
/// - Pre-register the coin's commitment in `IrExecutable`'s
///   `coin_commitments` so the `Cell.writeCoin` op-class
///   (`update-with-coin-check`) can resolve its merkle-tree-index
///   lookup.
#[tokio::test]
async fn ir_micro_dao_buy_in_succeeds_with_native_token_coin() {
    let contract_addr = dummy_contract_address();
    let nonce = [0xAAu8; 32];
    let color = [0u8; 32];
    let value: u64 = 100_000;

    // Register the coin's commitment so writeCoin can find it.
    let commitment = micro_dao_coin_commitment(nonce, color, u128::from(value), contract_addr);

    let exec = IrExecutable::from_path(ir_path(), Arc::new(MicroDaoWitnesses))
        .expect("loads")
        .with_coin_commitments(vec![(commitment, 0u64)]);
    let init = exec.initialize(ctor_ctx(), Value::Null).await.unwrap();

    let coin = shielded_coin_info(nonce, color, value);

    let outcome = exec
        .execute_circuit("buyIn", fresh_call_ctx(init.initial_contract_state), coin)
        .await;
    match outcome {
        Ok(r) => {
            // **End-to-end success!** With `update-with-coin-check`
            // properly resolving via `IrExecutable::with_coin_commitments`,
            // the writeCoin op finds the registered commitment in
            // `context.com_indices` and runs to completion. The IR
            // walks the entire buyIn body: assert → receiveShielded
            // → if(!potHasCoin) branch → pot.writeCoin → potHasCoin
            // = true → localSecretKey + publicKey → eligibleVoters
            // .insert(pk).
            eprintln!(
                "buyIn ran end-to-end: {} public-transcript ops, {} private-transcript outputs",
                r.public_transcript.len(),
                r.private_transcript_outputs.len()
            );
            assert_ne!(r.public_transcript, []);
        }
        Err(e) => {
            let m = format!("{e}");
            assert!(
                !m.contains("unimplemented IR construct"),
                "buyIn hit a driver gap: {m}"
            );
            panic!("buyIn unexpectedly hit a non-driver fault: {m}");
        }
    }
}