moonproof-contracts 0.2.2

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
//! Worked example: deploy the mint contract against a local-dev
//! harness, call its `mint` circuit, and print the resulting contract
//! address + tx ids.
//!
//! This is the canonical "I want to use moonproof to deploy + call a
//! Compact contract" demo — distilled from
//! [`crates/runtime/tests/mint_then_shielded_transfer_reaches_in_block.rs`]
//! to a single binary.
//!
//! # Usage
//!
//! ```bash
//! # The harness must be up — see moonproof dev start.
//! moonproof dev status
//! cargo run -p moonproof-runtime --example mint_deploy
//!
//! # Or against a custom harness URL set:
//! INDEXER_HTTP=http://localhost:8088/api/v4/graphql \
//!   NODE_WS=ws://localhost:9944 \
//!   cargo run -p moonproof-runtime --example mint_deploy
//! ```
//!
//! # What it prints
//!
//! On success:
//! ```text
//! mint contract deployed: address=<hex>, tx_id=<hash>, block=<height>
//! mint call landed: tx_id=<hash>, block=<height>
//! ```
//!
//! On failure: a structured `ContractRuntimeError` with the
//! diagnostic.
//!
//! # Why this exists
//!
//! Downstream Rust crates that want to use moonproof's runtime can
//! copy this file as a template. Every piece on display here —
//! provider construction, IR loading, witness wiring, fee balancing,
//! deploy + call — is the same surface a real app would write. There
//! is no hidden helper crate to depend on.
//!
//! # The IR-driven executor
//!
//! Contract execution goes through [`IrExecutable<W>`]: a single
//! generic executor that interprets the `contract.mpir` emitted by
//! the patched compactc fork. Args are `serde_json::Value` — the IR's
//! own argument descriptors handle the typing. There is no
//! per-contract typed-args struct, no `*_circuit_id()` helper, no
//! `*Executable` newtype.
//!
//! For contracts with witnesses (mint, vault, registry, etc.),
//! implement the [`Witnesses`] trait once and pass `Arc<YourWitnesses>`
//! into [`IrExecutable::from_path`]. The runtime invokes
//! `witnesses.invoke(name, args, private_state)` whenever the IR's
//! body calls a witness function.

macro_rules! rv {
    ($($t:tt)*) => { ::moonproof_runtime_ir::RuntimeValue::from(::serde_json::json!($($t)*)) };
}

use std::env;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration as StdDuration;

use anyhow::Context;
use futures::StreamExt;
use moonproof_ledger::base_crypto::time::{Duration, Timestamp};
use moonproof_ledger::ledger::dust::DustSecretKey;
use moonproof_ledger::serialize::Serializable;
use moonproof_ledger::zswap::keys::SecretKeys as ZswapSecretKeys;
use moonproof_runtime_ir::RuntimeValue as Value;
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use url::Url;

use moonproof_contracts::contract::{deploy_contract, DeployOptions};
use moonproof_contracts::fee_balancing::FeeBalancingConfig;
use moonproof_contracts::providers::{
    ErasedProviders, FacadeWalletProvider, FileSystemZkConfigProvider,
    InMemoryPrivateStateProvider, InProcessProofProvider, IndexerPublicDataProvider,
    NodeClientMidnightProvider, ZkConfigProvider,
};
use moonproof_contracts::tx_interfaces::CallOptions;
use moonproof_contracts::TxStatus;
use moonproof_indexer_client::{
    subscribe_dust_ledger_events, subscribe_unshielded_transactions, UnshieldedTxRaw,
};
use moonproof_node_client::{Config as NodeClientConfig, PolkadotNodeClient};
use moonproof_prover::{EngineProvingProvider, ProverEngine};
use moonproof_runtime::state::contract_address_to_hex;
use moonproof_runtime::types::{CircuitId, CoinPublicKey, EncPublicKey};
use moonproof_runtime::{IrDriverError, IrExecutable, Witnesses};
use moonproof_wallet::abstractions::NetworkId;
use moonproof_wallet::shielded::ShieldedState;
use moonproof_wallet::{
    fetch_chain_parameters, fold_dust_events, fold_unshielded_ticks, DustState, FacadeState,
    UnshieldedState, Wallet,
};

/// Mint contract's witness table. The mint stdlib helper invokes
/// `createZswapOutput(coin, recipient)` once per emitted shielded
/// coin; the runtime's witness bridge converts the typed args back
/// into a `CompactZswapOutput` entry on the host-side
/// `next_zswap_local_state.outputs` (so the call-tx pipeline can
/// attach a `guaranteed_coins` offer to the resulting transaction).
///
/// The host-side observed value is unit (`Value::Array(empty)`); the
/// useful work happens in the bridge. The witness callback is also
/// where a contract that mutates private state would rotate the
/// state across the call.
#[derive(Debug, Default)]
struct MintWitnesses;

impl Witnesses for MintWitnesses {
    fn invoke(
        &self,
        witness_name: &str,
        _args: &Value,
        private_state: &Value,
    ) -> Result<moonproof_runtime::witnesses::WitnessResult, IrDriverError> {
        match witness_name {
            "createZswapOutput" => Ok(moonproof_runtime::witnesses::WitnessResult {
                observed: Value::Array(Vec::new()),
                next_private_state: private_state.clone(),
            }),
            other => Err(IrDriverError::Witness(format!(
                "unexpected witness '{other}' for mint contract"
            ))),
        }
    }
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
    let indexer_http = env::var("INDEXER_HTTP")
        .unwrap_or_else(|_| "http://127.0.0.1:8088/api/v4/graphql".to_owned());
    let node_ws = env::var("NODE_WS").unwrap_or_else(|_| "ws://127.0.0.1:9944".to_owned());
    eprintln!("=> harness: indexer={indexer_http}, node={node_ws}");

    // Genesis wallet (`0x00..01` 32-byte seed) — has 250M NIGHT
    // pre-minted on local-dev. Real apps would derive their own
    // wallet via `Wallet::from_hex_seed` or build a wallet
    // from a BIP44 mnemonic.
    let sender =
        Wallet::genesis(NetworkId::Undeployed).context("derive genesis wallet from hex seed")?;
    eprintln!("=> wallet: {}", sender.bech32_address);

    // -----------------------------------------------------------------
    // Step 1: Sync facade state — needed for dust-fee balancing.
    // -----------------------------------------------------------------
    let dust_sk = sender.dust_secret_key();
    let zswap_keys = sender.zswap_secret_keys();
    let (block_ts, fee_balancing) =
        initial_fee_balancing(&indexer_http, &sender, &dust_sk, &zswap_keys).await?;

    // -----------------------------------------------------------------
    // Step 2: Build the ContractProviders bundle.
    //
    // The wallet provider needs the wallet's real shielded keys so
    // that the freshly minted output's ciphertext is encrypted to a
    // public key the wallet can decrypt later (otherwise the indexer
    // would never surface the coin via `shieldedTransactions`).
    // -----------------------------------------------------------------
    let (providers, zk_config, wallet_coin_key) =
        build_providers(&indexer_http, &node_ws, &zswap_keys).await?;

    // -----------------------------------------------------------------
    // Step 3: Build the IR-driven executable for the mint contract.
    //
    // Loads `contract.mpir` from the vendored fixture, attaches the
    // verifier key compactc emitted alongside it (required for
    // `Transaction::well_formed` to accept the deploy), and binds the
    // mint contract's witness table.
    // -----------------------------------------------------------------
    let mint = load_mint(zk_config.as_ref()).await?;

    // -----------------------------------------------------------------
    // Step 4: Deploy the mint contract.
    // -----------------------------------------------------------------
    let mut rng = StdRng::seed_from_u64(rand::thread_rng().r#gen());
    eprintln!("=> submitting deploy tx (this may take a few minutes — proving)");
    let deployed = Box::pin(deploy_contract(
        &mut rng,
        mint.clone(),
        providers.clone(),
        DeployOptions {
            constructor_args: Value::Null,
            initial_private_state: Value::Null,
            signing_key: None,
            additional_coin_enc_public_key_mappings: None,
            current_time: block_ts,
            network_id: "undeployed".to_owned(),
            persistent_state: None,
            fee_balancing: Some(fee_balancing),
            register_circuits: None,
        },
    ))
    .await
    .context("deploy_contract")?;

    if !matches!(
        deployed.finalized_deploy_tx().status,
        TxStatus::SucceedEntirely
    ) {
        anyhow::bail!(
            "deploy did not succeed — status: {:?}",
            deployed.finalized_deploy_tx().status
        );
    }

    println!(
        "mint contract deployed: address={}, tx_id={}, block={}",
        contract_address_to_hex(deployed.contract_address()),
        deployed.finalized_deploy_tx().tx_id,
        deployed.finalized_deploy_tx().block_height,
    );

    // -----------------------------------------------------------------
    // Step 5: Call the mint circuit. Args are JSON shaped per the IR's
    // argument descriptors:
    //   - `domainSep: Bytes<32>`           → hex string
    //   - `value: Uint<64>`                → number
    //   - `nonce: Bytes<32>`               → hex string
    //   - `recipient: ZswapCoinPublicKey`  → struct `{bytes: hex}`
    // -----------------------------------------------------------------
    let (block_ts2, fee_balancing2) =
        post_deploy_fee_balancing(&indexer_http, &sender, &dust_sk, &zswap_keys).await?;

    let mint_args = rv!({
        "domainSep": "01".repeat(32),
        "value": 1_000_000u64,
        "nonce": format!("{:02x}", rand::thread_rng().r#gen::<u8>()).repeat(32),
        // Mint to the wallet's own coin public key — the resulting
        // ciphertext decrypts with the wallet's enc_secret_key.
        "recipient": { "bytes": hex::encode(wallet_coin_key.0) },
    });

    eprintln!("=> submitting mint call");
    let call_result = Box::pin(deployed.calls().call(
        &mut rng,
        &CircuitId::new("mint"),
        mint_args,
        CallOptions {
            current_time: block_ts2,
            network_id: "undeployed".to_owned(),
            fee_balancing: Some(fee_balancing2),
            initial_private_state: Some(Value::Null),
            ..CallOptions::default()
        },
    ))
    .await
    .context("call_tx.call mint")?;

    if !matches!(call_result.finalized.status, TxStatus::SucceedEntirely) {
        anyhow::bail!(
            "mint call did not succeed — status: {:?}",
            call_result.finalized.status
        );
    }

    println!(
        "mint call landed: tx_id={}, block={}",
        call_result.finalized.tx_id, call_result.finalized.block_height,
    );
    Ok(())
}

async fn initial_fee_balancing(
    indexer_http: &str,
    sender: &Wallet,
    dust_sk: &DustSecretKey,
    zswap_keys: &ZswapSecretKeys,
) -> anyhow::Result<(Timestamp, FeeBalancingConfig)> {
    let params = fetch_chain_parameters(indexer_http)
        .await
        .context("fetch chain parameters")?;
    let block_ts = Timestamp::from_secs(params.chain_time_secs);

    let facade = FacadeState::new(
        ShieldedState::init_empty(zswap_keys, NetworkId::Undeployed),
        UnshieldedState::empty(),
        DustState::init_empty(
            params.ledger_parameters.dust,
            dust_sk,
            NetworkId::Undeployed,
        ),
        NetworkId::Undeployed,
    );
    let unshielded_ticks = drain_unshielded(indexer_http, &sender.bech32_address).await;
    let facade = fold_unshielded_ticks(facade, sender.owner_bytes(), unshielded_ticks)
        .context("fold unshielded ticks")?;
    if facade.unshielded.available_len() == 0 {
        anyhow::bail!("genesis wallet has no NIGHT UTXOs — is the harness seeded?");
    }
    let dust_blobs = drain_dust(indexer_http).await;
    let (facade, _) =
        fold_dust_events(facade, dust_sk, &dust_blobs, block_ts).context("fold dust events")?;
    eprintln!(
        "=> synced: {} NIGHT UTXOs, {} dust events",
        facade.unshielded.available_len(),
        dust_blobs.len()
    );

    let ttl = block_ts + Duration::from_secs(3_600);
    let fee_balancing = FeeBalancingConfig::new(
        facade.dust,
        dust_sk.clone(),
        block_ts,
        ttl,
        params.ledger_parameters.clone(),
    );
    Ok((block_ts, fee_balancing))
}

async fn build_providers(
    indexer_http: &str,
    node_ws: &str,
    zswap_keys: &ZswapSecretKeys,
) -> anyhow::Result<(
    Arc<ErasedProviders>,
    Arc<FileSystemZkConfigProvider>,
    CoinPublicKey,
)> {
    let private_state = Arc::new(InMemoryPrivateStateProvider::new());
    let public_data = Arc::new(
        IndexerPublicDataProvider::new(indexer_http).context("build IndexerPublicDataProvider")?,
    );
    let zk_config = Arc::new(FileSystemZkConfigProvider::new(mint_fixture_root()));
    let prover_engine =
        Arc::new(ProverEngine::from_env().context("init ProverEngine (MIDNIGHT_PP)")?);
    let proof = Arc::new(
        InProcessProofProvider::new(EngineProvingProvider::new(prover_engine))
            .with_zk_config(zk_config.clone()),
    );

    let mut epk_bytes = Vec::with_capacity(32);
    zswap_keys
        .enc_public_key()
        .serialize(&mut epk_bytes)
        .context("serialize encryption public key")?;
    let wallet_coin_key = CoinPublicKey(zswap_keys.coin_public_key().0 .0);
    let wallet_enc_key = EncPublicKey(
        epk_bytes
            .try_into()
            .map_err(|_| anyhow::anyhow!("encryption public key did not serialize to 32 bytes"))?,
    );
    let wallet = Arc::new(FacadeWalletProvider::new(wallet_coin_key, wallet_enc_key));

    let node_client = Arc::new(
        PolkadotNodeClient::connect(NodeClientConfig::new(
            Url::parse(node_ws).context("invalid node ws url")?,
        ))
        .await
        .context("connect to node")?,
    );
    let midnight = Arc::new(NodeClientMidnightProvider::new(node_client));

    let providers = Arc::new(
        ErasedProviders::builder()
            .private_state(private_state.clone())
            .public_data(public_data.clone())
            .zk_config(zk_config.clone())
            .proof(proof.clone())
            .wallet(wallet.clone())
            .midnight(midnight.clone())
            .build(),
    );
    Ok((providers, zk_config, wallet_coin_key))
}

async fn load_mint(
    zk_config: &FileSystemZkConfigProvider,
) -> anyhow::Result<Arc<IrExecutable<MintWitnesses>>> {
    let mint_vk = zk_config
        .get_verifier_key(&CircuitId::new("mint"))
        .await
        .context("load mint.verifier from fixture")?;
    let mint = Arc::new(
        IrExecutable::from_path(mint_ir_path(), Arc::new(MintWitnesses))
            .context("load mint contract.mpir")?
            .with_verifier_key("mint", mint_vk),
    );
    Ok(mint)
}

async fn post_deploy_fee_balancing(
    indexer_http: &str,
    sender: &Wallet,
    dust_sk: &DustSecretKey,
    zswap_keys: &ZswapSecretKeys,
) -> anyhow::Result<(Timestamp, FeeBalancingConfig)> {
    let params2 = fetch_chain_parameters(indexer_http)
        .await
        .context("fetch chain parameters post-deploy")?;
    let block_ts2 = Timestamp::from_secs(params2.chain_time_secs);

    let facade2 = FacadeState::new(
        ShieldedState::init_empty(zswap_keys, NetworkId::Undeployed),
        UnshieldedState::empty(),
        DustState::init_empty(
            params2.ledger_parameters.dust,
            dust_sk,
            NetworkId::Undeployed,
        ),
        NetworkId::Undeployed,
    );
    let unshielded_ticks2 = drain_unshielded(indexer_http, &sender.bech32_address).await;
    let facade2 = fold_unshielded_ticks(facade2, sender.owner_bytes(), unshielded_ticks2)
        .context("fold unshielded ticks post-deploy")?;
    let dust_blobs2 = drain_dust(indexer_http).await;
    let (facade2, _) = fold_dust_events(facade2, dust_sk, &dust_blobs2, block_ts2)
        .context("fold dust events post-deploy")?;
    let ttl2 = block_ts2 + Duration::from_secs(3_600);
    let fee_balancing2 = FeeBalancingConfig::new(
        facade2.dust,
        dust_sk.clone(),
        block_ts2,
        ttl2,
        params2.ledger_parameters.clone(),
    );
    Ok((block_ts2, fee_balancing2))
}

fn mint_fixture_root() -> PathBuf {
    // The vendored mint fixture lives under
    // `crates/test-fixtures/contracts/mint/`. Resolved relative to
    // CARGO_MANIFEST_DIR so the example works regardless of where the
    // user runs it from.
    let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    p.pop();
    p.pop();
    p.push("crates/test-fixtures/contracts/mint");
    p
}

fn mint_ir_path() -> PathBuf {
    let mut p = mint_fixture_root();
    p.push("contract.mpir");
    p
}

const UNSHIELDED_SYNC_TIMEOUT_SECS: u64 = 60;
const DUST_EVENT_TIMEOUT_SECS: u64 = 60;

async fn drain_unshielded(indexer_url: &str, bech32_address: &str) -> Vec<UnshieldedTxRaw> {
    let Ok(mut stream) = subscribe_unshielded_transactions(indexer_url, bech32_address, None).await
    else {
        return Vec::new();
    };
    let mut collected = Vec::new();
    let mut last_applied: i64 = 0;
    let mut highest_seen: i64 = 0;
    let deadline =
        tokio::time::Instant::now() + StdDuration::from_secs(UNSHIELDED_SYNC_TIMEOUT_SECS);
    while tokio::time::Instant::now() < deadline {
        let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
        match tokio::time::timeout(remaining, stream.next()).await {
            Err(_) | Ok(None | Some(Err(_))) => break,
            Ok(Some(Ok(tick))) => {
                if tick.is_progress() {
                    if let Some(h) = tick.highest_transaction_id {
                        highest_seen = highest_seen.max(h);
                    }
                    collected.push(tick);
                    if last_applied >= highest_seen {
                        break;
                    }
                    continue;
                }
                if let Some(id) = tick.transaction_id {
                    last_applied = last_applied.max(id);
                }
                collected.push(tick);
            }
        }
    }
    collected
}

async fn drain_dust(indexer_url: &str) -> Vec<String> {
    let Ok(mut stream) = subscribe_dust_ledger_events(indexer_url, Some(0)).await else {
        return Vec::new();
    };
    let mut out = Vec::new();
    let deadline = tokio::time::Instant::now() + StdDuration::from_secs(DUST_EVENT_TIMEOUT_SECS);
    let mut max_id: i64 = -1;
    while tokio::time::Instant::now() < deadline {
        let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
        match tokio::time::timeout(remaining, stream.next()).await {
            Err(_) | Ok(None | Some(Err(_))) => break,
            Ok(Some(Ok(ev))) => {
                if ev.id > max_id {
                    out.push(ev.raw.clone());
                    max_id = ev.id;
                }
                if ev.max_id <= ev.id {
                    break;
                }
            }
        }
    }
    out
}