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
//! Port of
//! `@midnight-ntwrk/midnight-js-contracts/src/submit-call-tx.ts`.
//!
//! Build, submit, and finalize a contract-call transaction.
//!
//! # Failure semantics (matches TS)
//!
//! Non-`SucceedEntirely` status yields
//! [`ContractsError::CallTxFailed`] and **no private state is
//! persisted**. Matches TS's `CallTxFailedError(finalizedTxData,
//! circuitId)`.
//!
//! # Private-state persistence
//!
//! On success, the next private state is persisted to the
//! private-state provider iff the caller passed both a
//! `private_state_id` AND a `serialize_next_private_state` closure.
//! Keeping serialization caller-supplied keeps the runtime agnostic
//! to serde-vs-bincode-vs-postcard — same rationale as
//! [`crate::submit_deploy_tx`].

use std::sync::Arc;

use rand::{CryptoRng, Rng};

use crate::error::{ContractRuntimeError, ContractsError, Result};
use crate::providers::{PrivateStateProvider, Providers};
use crate::submit_tx::{submit_tx, SubmitTxOptions};
use crate::transaction::{DeferredSubmission, TransactionContextImpl};
use crate::tx_model::{FinalizedCallTxData, SubmittedCallTx};
use crate::tx_phase::UnprovenTx;
use crate::types::PrivateStateId;
use crate::unproven_call_tx::{
    create_unproven_call_tx, create_unproven_call_tx_in_scope, BuildCallOptions,
};
use moonproof_runtime::ir::witnesses::Witnesses;
use moonproof_runtime::ir_executable::IrExecutable;
use moonproof_runtime_ir::RuntimeValue;

/// Serializer closure type — takes a reference to the circuit's
/// next-private-state (always [`RuntimeValue`] at the host layer) and
/// produces the bytes the provider stores. Boxed so
/// [`BuildCallOptions`] stays `Send` without imposing generic closure
/// types on every call site.
pub type PrivateStateSerializer = Box<dyn Fn(&RuntimeValue) -> Result<Vec<u8>> + Send + Sync>;

/// Pre-submit hook — called with the unproven, unbalanced transaction
/// bytes after [`create_unproven_call_tx`] returns and before the
/// submit pipeline (`prove_tx` → `balance_tx` → `submit`). Returns
/// the (possibly modified) unproven bytes that are passed to
/// `prove_tx`.
///
/// The canonical use case is the wallet-side shielded balancer
/// (`moonproof_wallet::shielded::balance_contract_call_tx`), which
/// reads the imbalance from the contract-emitted offer, picks coins,
/// and merges a balancing offer.
pub type PreSubmitTxHook = Box<dyn FnOnce(UnprovenTx) -> Result<UnprovenTx> + Send>;

/// Result of [`submit_call_tx`] when the call was deferred into a
/// scoped transaction.
///
/// Mirrors TS `CallResult<C, PCK>`: when a call runs inside
/// `withContractScopedTransaction`'s closure, it does not
/// individually finalize — instead the scope batches it and submits
/// all calls together on closure exit. The Rust version returns the
/// circuit-execution result without `FinalizedTxData` (since no tx
/// was submitted yet).
#[derive(Debug, Clone)]
pub struct CallTxOutcome {
    /// Finalized call data. `Some` for unscoped calls (the call hit
    /// the chain and we have the finalized record); `None` for
    /// scoped calls (the call was merged into the scope's queue and
    /// the caller will get the finalized record from
    /// [`crate::with_contract_scoped_transaction`]'s outer return).
    pub finalized: Option<FinalizedCallTxData>,
    /// The unsubmitted call data — populated for both code paths so
    /// callers in the scoped-call path can read the typed `result`
    /// before the scope's outer submit fires.
    pub unsubmitted: crate::tx_model::UnsubmittedCallTxData,
}

/// Build, submit, and finalize a contract call transaction. Returns
/// the full [`FinalizedCallTxData`] on `SucceedEntirely`. Port of TS
/// `submitCallTx`.
///
/// When `tx_ctx` is `Some`, the call is **deferred** into the scoped
/// transaction context: the unproven call data is merged via
/// [`TransactionContextImpl::merge_unsubmitted_call_tx_data`] and the
/// returned [`CallTxOutcome`] has `finalized = None`. The actual
/// submission happens when the surrounding
/// [`crate::with_contract_scoped_transaction`] closure returns.
///
/// When `tx_ctx` is `None`, behaviour is unchanged: the call is
/// proven, balanced, submitted, and finalized in one go, then
/// returned with `finalized = Some(...)`.
pub async fn submit_call_tx<W, R, C>(
    rng: &mut R,
    executable: &IrExecutable<W>,
    providers: &C,
    mut options: BuildCallOptions,
    tx_ctx: Option<&Arc<TransactionContextImpl>>,
) -> Result<CallTxOutcome>
where
    W: Witnesses + 'static,
    R: Rng + CryptoRng,
    C: Providers + ?Sized,
{
    // Pull the submit-stage extensions aside before consuming the
    // build options into create_unproven_call_tx — that helper only
    // looks at the unproven-build subset.
    let serializer = options.serialize_next_private_state.take();
    let pre_submit = options.pre_submit.take();
    let circuit_id = options.circuit_id.clone();
    let private_state_id = options.private_state_id.clone();

    // Scoped path — build against the scope's states and defer
    // submission into it. The fee is balanced once, over the merged
    // transaction, when the scope submits.
    if let Some(ctx) = tx_ctx {
        let deferred = DeferredSubmission {
            fee_balancing: options.fee_balancing.take(),
            network_id: options.network_id.clone(),
            serialize_next_private_state: serializer,
        };
        let unproven =
            create_unproven_call_tx_in_scope(rng, executable, providers, options, Some(ctx))
                .await?;
        ctx.merge_unsubmitted_call_tx_data(circuit_id, unproven.clone(), private_state_id);
        ctx.defer_submission(deferred);
        return Ok(CallTxOutcome {
            finalized: None,
            unsubmitted: unproven,
        });
    }

    let unproven = create_unproven_call_tx(rng, executable, providers, options).await?;

    // Run the pre-submit hook (e.g. wallet-side shielded balancing)
    // before prove.
    let tx_for_submit = if let Some(hook) = pre_submit {
        hook(unproven.tx.unproven_tx.clone())?
    } else {
        unproven.tx.unproven_tx.clone()
    };

    // Unscoped path — full submit-and-finalize pipeline.
    let submit_opts = SubmitTxOptions::for_call(tx_for_submit, circuit_id.clone());
    let finalized = submit_tx(providers, submit_opts).await?;
    if !finalized.status.is_success() {
        return Err(ContractRuntimeError::Contracts(
            ContractsError::call_tx_failed(finalized, vec![circuit_id]),
        ));
    }

    // Persist next-private-state on success — iff the caller opted in
    // via the serializer closure AND the call targeted a specific id.
    if let (Some(psi), Some(serializer)) = (private_state_id.as_ref(), serializer.as_ref()) {
        let bytes = serializer(&unproven.result.private.next_private_state)?;
        providers.private_state().set(psi, bytes).await?;
    }

    let finalized_data = FinalizedCallTxData {
        result: unproven.result.clone(),
        tx: unproven.tx.clone(),
        finalized,
    };
    Ok(CallTxOutcome {
        finalized: Some(finalized_data),
        unsubmitted: unproven,
    })
}

/// Like [`submit_call_tx`] but returns immediately after submission,
/// with the chain-assigned transaction id and the unsubmitted-call-tx
/// payload. The caller is responsible for watching for finalization
/// and persisting private state.
pub async fn submit_call_tx_async<W, R, C>(
    rng: &mut R,
    executable: &IrExecutable<W>,
    providers: &C,
    options: BuildCallOptions,
) -> Result<SubmittedCallTx>
where
    W: Witnesses + 'static,
    R: Rng + CryptoRng,
    C: Providers + ?Sized,
{
    let circuit_id = options.circuit_id.clone();
    let unproven = create_unproven_call_tx(rng, executable, providers, options).await?;
    let submit_opts = SubmitTxOptions::for_call(unproven.tx.unproven_tx.clone(), circuit_id);
    let tx_id = crate::submit_tx::submit_tx_async(providers, submit_opts).await?;
    Ok(SubmittedCallTx {
        tx_id,
        call_tx_data: unproven,
    })
}

/// Convenience alias so [`SubmitCallTxOptions`] fields that hold a
/// [`PrivateStateId`] + serializer can be named in call-site
/// constructors without pulling the whole type signature.
pub type CallPersistence = (PrivateStateId, PrivateStateSerializer);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::providers::public_data::ZSwapAndContractState;
    use crate::test_helpers::{
        counter_ir_executable, dummy_address, scripted_providers_with_real_prover,
    };
    use crate::types::{CircuitId, TxStatus};
    use moonproof_runtime_ir::RuntimeValue as Value;
    use rand::SeedableRng;

    #[test]
    fn options_compile_for_stateless_executable() {
        let _opts: BuildCallOptions = BuildCallOptions {
            circuit_id: CircuitId::new("increment"),
            network_id: "local-test".into(),
            ..BuildCallOptions::default()
        };
    }

    #[test]
    fn options_compile_with_serializer_closure() {
        let _opts: BuildCallOptions = BuildCallOptions {
            circuit_id: CircuitId::new("increment"),
            private_state_id: Some(PrivateStateId::new("counter")),
            network_id: "local-test".into(),
            serialize_next_private_state: Some(Box::new(|_v: &Value| Ok(vec![]))),
            ..BuildCallOptions::default()
        };
    }

    async fn counter_initial_state() -> moonproof_ledger::onchain_runtime::state::ContractState<
        moonproof_ledger::storage::db::InMemoryDB,
    > {
        let executable = counter_ir_executable().await;
        let ctor = moonproof_runtime::executable::ConstructorContext {
            initial_private_state: moonproof_runtime_ir::RuntimeValue::Null,
            initial_zswap_local_state: crate::utils::zswap_utils::CompactZswapLocalState::empty(
                crate::types::CoinPublicKey([0u8; 32]),
            ),
            coin_public_key: crate::types::CoinPublicKey([0u8; 32]),
            signing_key: moonproof_ledger::signatures::schnorr_signing_key(&[0x10u8; 32]).unwrap(),
            time: None,
        };
        executable
            .initialize(ctor, moonproof_runtime_ir::RuntimeValue::Null)
            .await
            .unwrap()
            .initial_contract_state
    }

    fn counter_call_options() -> BuildCallOptions {
        BuildCallOptions {
            contract_address: dummy_address(),
            circuit_id: CircuitId::new("increment"),
            initial_private_state: Some(Value::Null),
            network_id: "local-test".into(),
            ..BuildCallOptions::default()
        }
    }

    /// ports: `submit-call-tx.test.ts::should successfully submit call transaction`
    #[tokio::test]
    #[ignore = "proves a circuit-bearing call tx in process; needs SRS params"]
    async fn happy_path_returns_finalized_call_tx_data() {
        let state = counter_initial_state().await;
        let bundle = ZSwapAndContractState {
            zswap_chain_state_bytes: Vec::new(),
            contract_state: state.clone(),
            ledger_parameters_bytes: crate::test_helpers::initial_ledger_parameters_bytes(),
        };
        let (providers, _) = scripted_providers_with_real_prover(
            None,
            Some(state),
            Some(bundle),
            TxStatus::SucceedEntirely,
        );
        let executable = counter_ir_executable().await;
        let mut rng = rand::rngs::StdRng::from_seed([0xCAu8; 32]);
        let outcome = Box::pin(submit_call_tx(
            &mut rng,
            &executable,
            &providers,
            counter_call_options(),
            None,
        ))
        .await
        .unwrap();
        let finalized = outcome
            .finalized
            .expect("unscoped call must produce finalized data");
        assert_eq!(finalized.finalized.status, TxStatus::SucceedEntirely);
    }

    /// ports: `submit-call-tx.test.ts::should throw CallTxFailedError on FailEntirely`
    #[tokio::test]
    #[ignore = "proves a circuit-bearing call tx in process; needs SRS params"]
    async fn fail_entirely_returns_call_tx_failed_with_circuit_id() {
        let state = counter_initial_state().await;
        let bundle = ZSwapAndContractState {
            zswap_chain_state_bytes: Vec::new(),
            contract_state: state.clone(),
            ledger_parameters_bytes: crate::test_helpers::initial_ledger_parameters_bytes(),
        };
        let (providers, _) = scripted_providers_with_real_prover(
            None,
            Some(state),
            Some(bundle),
            TxStatus::FailEntirely,
        );
        let executable = counter_ir_executable().await;
        let mut rng = rand::rngs::StdRng::from_seed([0xCBu8; 32]);
        let err = Box::pin(submit_call_tx(
            &mut rng,
            &executable,
            &providers,
            counter_call_options(),
            None,
        ))
        .await
        .unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("CallTxFailedError"), "{msg}");
        assert!(msg.contains("increment"), "{msg}");
    }

    /// ports: `submit-call-tx.test.ts::FailFallible scenario`
    #[tokio::test]
    #[ignore = "proves a circuit-bearing call tx in process; needs SRS params"]
    async fn fail_fallible_returns_call_tx_failed_preserving_status() {
        let state = counter_initial_state().await;
        let bundle = ZSwapAndContractState {
            zswap_chain_state_bytes: Vec::new(),
            contract_state: state.clone(),
            ledger_parameters_bytes: crate::test_helpers::initial_ledger_parameters_bytes(),
        };
        let (providers, _) = scripted_providers_with_real_prover(
            None,
            Some(state),
            Some(bundle),
            TxStatus::FailFallible,
        );
        let executable = counter_ir_executable().await;
        let mut rng = rand::rngs::StdRng::from_seed([0xCCu8; 32]);
        let err = Box::pin(submit_call_tx(
            &mut rng,
            &executable,
            &providers,
            counter_call_options(),
            None,
        ))
        .await
        .unwrap_err();
        match err {
            crate::error::ContractRuntimeError::Contracts(
                crate::error::ContractsError::CallTxFailed {
                    finalized_tx_data,
                    circuit_ids,
                },
            ) => {
                assert_eq!(finalized_tx_data.status, TxStatus::FailFallible);
                assert_eq!(circuit_ids, vec![CircuitId::new("increment")]);
            }
            other => panic!("expected CallTxFailed, got {other:?}"),
        }
    }

    /// ports: `submit-call-tx.test.ts::scoped call deferral`
    #[tokio::test]
    async fn scoped_call_defers_into_transaction_context() {
        use crate::transaction::{ScopedTransactionOptions, TransactionContextImpl};
        use std::sync::Arc as StdArc;

        let state = counter_initial_state().await;
        let bundle = ZSwapAndContractState {
            zswap_chain_state_bytes: Vec::new(),
            contract_state: state.clone(),
            ledger_parameters_bytes: crate::test_helpers::initial_ledger_parameters_bytes(),
        };
        let (providers, _) = scripted_providers_with_real_prover(
            None,
            Some(state),
            Some(bundle),
            TxStatus::FailEntirely,
        );
        let providers_arc = StdArc::new(providers);
        let ctx = StdArc::new(TransactionContextImpl::new(
            providers_arc.clone(),
            ScopedTransactionOptions::default(),
        ));
        let executable = counter_ir_executable().await;
        let mut rng = rand::rngs::StdRng::from_seed([0xCDu8; 32]);
        let outcome = Box::pin(submit_call_tx(
            &mut rng,
            &executable,
            &providers_arc,
            counter_call_options(),
            Some(&ctx),
        ))
        .await
        .unwrap();
        assert!(
            outcome.finalized.is_none(),
            "scoped call must defer submission"
        );
        assert_eq!(ctx.merged_call_count(), 1);
        assert_eq!(
            ctx.accumulated_circuit_ids(),
            vec![CircuitId::new("increment")]
        );
    }
}