Skip to main content

moonproof_contracts/
submit_call_tx.rs

1//! Port of
2//! `@midnight-ntwrk/midnight-js-contracts/src/submit-call-tx.ts`.
3//!
4//! Build, submit, and finalize a contract-call transaction.
5//!
6//! # Failure semantics (matches TS)
7//!
8//! Non-`SucceedEntirely` status yields
9//! [`ContractsError::CallTxFailed`] and **no private state is
10//! persisted**. Matches TS's `CallTxFailedError(finalizedTxData,
11//! circuitId)`.
12//!
13//! # Private-state persistence
14//!
15//! On success, the next private state is persisted to the
16//! private-state provider iff the caller passed both a
17//! `private_state_id` AND a `serialize_next_private_state` closure.
18//! Keeping serialization caller-supplied keeps the runtime agnostic
19//! to serde-vs-bincode-vs-postcard — same rationale as
20//! [`crate::submit_deploy_tx`].
21
22use std::sync::Arc;
23
24use rand::{CryptoRng, Rng};
25
26use crate::error::{ContractRuntimeError, ContractsError, Result};
27use crate::providers::{PrivateStateProvider, Providers};
28use crate::submit_tx::{submit_tx, SubmitTxOptions};
29use crate::transaction::{DeferredSubmission, TransactionContextImpl};
30use crate::tx_model::{FinalizedCallTxData, SubmittedCallTx};
31use crate::tx_phase::UnprovenTx;
32use crate::types::PrivateStateId;
33use crate::unproven_call_tx::{
34    create_unproven_call_tx, create_unproven_call_tx_in_scope, BuildCallOptions,
35};
36use moonproof_runtime::ir::witnesses::Witnesses;
37use moonproof_runtime::ir_executable::IrExecutable;
38use moonproof_runtime_ir::RuntimeValue;
39
40/// Serializer closure type — takes a reference to the circuit's
41/// next-private-state (always [`RuntimeValue`] at the host layer) and
42/// produces the bytes the provider stores. Boxed so
43/// [`BuildCallOptions`] stays `Send` without imposing generic closure
44/// types on every call site.
45pub type PrivateStateSerializer = Box<dyn Fn(&RuntimeValue) -> Result<Vec<u8>> + Send + Sync>;
46
47/// Pre-submit hook — called with the unproven, unbalanced transaction
48/// bytes after [`create_unproven_call_tx`] returns and before the
49/// submit pipeline (`prove_tx` → `balance_tx` → `submit`). Returns
50/// the (possibly modified) unproven bytes that are passed to
51/// `prove_tx`.
52///
53/// The canonical use case is the wallet-side shielded balancer
54/// (`moonproof_wallet::shielded::balance_contract_call_tx`), which
55/// reads the imbalance from the contract-emitted offer, picks coins,
56/// and merges a balancing offer.
57pub type PreSubmitTxHook = Box<dyn FnOnce(UnprovenTx) -> Result<UnprovenTx> + Send>;
58
59/// Result of [`submit_call_tx`] when the call was deferred into a
60/// scoped transaction.
61///
62/// Mirrors TS `CallResult<C, PCK>`: when a call runs inside
63/// `withContractScopedTransaction`'s closure, it does not
64/// individually finalize — instead the scope batches it and submits
65/// all calls together on closure exit. The Rust version returns the
66/// circuit-execution result without `FinalizedTxData` (since no tx
67/// was submitted yet).
68#[derive(Debug, Clone)]
69pub struct CallTxOutcome {
70    /// Finalized call data. `Some` for unscoped calls (the call hit
71    /// the chain and we have the finalized record); `None` for
72    /// scoped calls (the call was merged into the scope's queue and
73    /// the caller will get the finalized record from
74    /// [`crate::with_contract_scoped_transaction`]'s outer return).
75    pub finalized: Option<FinalizedCallTxData>,
76    /// The unsubmitted call data — populated for both code paths so
77    /// callers in the scoped-call path can read the typed `result`
78    /// before the scope's outer submit fires.
79    pub unsubmitted: crate::tx_model::UnsubmittedCallTxData,
80}
81
82/// Build, submit, and finalize a contract call transaction. Returns
83/// the full [`FinalizedCallTxData`] on `SucceedEntirely`. Port of TS
84/// `submitCallTx`.
85///
86/// When `tx_ctx` is `Some`, the call is **deferred** into the scoped
87/// transaction context: the unproven call data is merged via
88/// [`TransactionContextImpl::merge_unsubmitted_call_tx_data`] and the
89/// returned [`CallTxOutcome`] has `finalized = None`. The actual
90/// submission happens when the surrounding
91/// [`crate::with_contract_scoped_transaction`] closure returns.
92///
93/// When `tx_ctx` is `None`, behaviour is unchanged: the call is
94/// proven, balanced, submitted, and finalized in one go, then
95/// returned with `finalized = Some(...)`.
96pub async fn submit_call_tx<W, R, C>(
97    rng: &mut R,
98    executable: &IrExecutable<W>,
99    providers: &C,
100    mut options: BuildCallOptions,
101    tx_ctx: Option<&Arc<TransactionContextImpl>>,
102) -> Result<CallTxOutcome>
103where
104    W: Witnesses + 'static,
105    R: Rng + CryptoRng,
106    C: Providers + ?Sized,
107{
108    // Pull the submit-stage extensions aside before consuming the
109    // build options into create_unproven_call_tx — that helper only
110    // looks at the unproven-build subset.
111    let serializer = options.serialize_next_private_state.take();
112    let pre_submit = options.pre_submit.take();
113    let circuit_id = options.circuit_id.clone();
114    let private_state_id = options.private_state_id.clone();
115
116    // Scoped path — build against the scope's states and defer
117    // submission into it. The fee is balanced once, over the merged
118    // transaction, when the scope submits.
119    if let Some(ctx) = tx_ctx {
120        let deferred = DeferredSubmission {
121            fee_balancing: options.fee_balancing.take(),
122            network_id: options.network_id.clone(),
123            serialize_next_private_state: serializer,
124        };
125        let unproven =
126            create_unproven_call_tx_in_scope(rng, executable, providers, options, Some(ctx))
127                .await?;
128        ctx.merge_unsubmitted_call_tx_data(circuit_id, unproven.clone(), private_state_id);
129        ctx.defer_submission(deferred);
130        return Ok(CallTxOutcome {
131            finalized: None,
132            unsubmitted: unproven,
133        });
134    }
135
136    let unproven = create_unproven_call_tx(rng, executable, providers, options).await?;
137
138    // Run the pre-submit hook (e.g. wallet-side shielded balancing)
139    // before prove.
140    let tx_for_submit = if let Some(hook) = pre_submit {
141        hook(unproven.tx.unproven_tx.clone())?
142    } else {
143        unproven.tx.unproven_tx.clone()
144    };
145
146    // Unscoped path — full submit-and-finalize pipeline.
147    let submit_opts = SubmitTxOptions::for_call(tx_for_submit, circuit_id.clone());
148    let finalized = submit_tx(providers, submit_opts).await?;
149    if !finalized.status.is_success() {
150        return Err(ContractRuntimeError::Contracts(
151            ContractsError::call_tx_failed(finalized, vec![circuit_id]),
152        ));
153    }
154
155    // Persist next-private-state on success — iff the caller opted in
156    // via the serializer closure AND the call targeted a specific id.
157    if let (Some(psi), Some(serializer)) = (private_state_id.as_ref(), serializer.as_ref()) {
158        let bytes = serializer(&unproven.result.private.next_private_state)?;
159        providers.private_state().set(psi, bytes).await?;
160    }
161
162    let finalized_data = FinalizedCallTxData {
163        result: unproven.result.clone(),
164        tx: unproven.tx.clone(),
165        finalized,
166    };
167    Ok(CallTxOutcome {
168        finalized: Some(finalized_data),
169        unsubmitted: unproven,
170    })
171}
172
173/// Like [`submit_call_tx`] but returns immediately after submission,
174/// with the chain-assigned transaction id and the unsubmitted-call-tx
175/// payload. The caller is responsible for watching for finalization
176/// and persisting private state.
177pub async fn submit_call_tx_async<W, R, C>(
178    rng: &mut R,
179    executable: &IrExecutable<W>,
180    providers: &C,
181    options: BuildCallOptions,
182) -> Result<SubmittedCallTx>
183where
184    W: Witnesses + 'static,
185    R: Rng + CryptoRng,
186    C: Providers + ?Sized,
187{
188    let circuit_id = options.circuit_id.clone();
189    let unproven = create_unproven_call_tx(rng, executable, providers, options).await?;
190    let submit_opts = SubmitTxOptions::for_call(unproven.tx.unproven_tx.clone(), circuit_id);
191    let tx_id = crate::submit_tx::submit_tx_async(providers, submit_opts).await?;
192    Ok(SubmittedCallTx {
193        tx_id,
194        call_tx_data: unproven,
195    })
196}
197
198/// Convenience alias so [`SubmitCallTxOptions`] fields that hold a
199/// [`PrivateStateId`] + serializer can be named in call-site
200/// constructors without pulling the whole type signature.
201pub type CallPersistence = (PrivateStateId, PrivateStateSerializer);
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206    use crate::providers::public_data::ZSwapAndContractState;
207    use crate::test_helpers::{
208        counter_ir_executable, dummy_address, scripted_providers_with_real_prover,
209    };
210    use crate::types::{CircuitId, TxStatus};
211    use moonproof_runtime_ir::RuntimeValue as Value;
212    use rand::SeedableRng;
213
214    #[test]
215    fn options_compile_for_stateless_executable() {
216        let _opts: BuildCallOptions = BuildCallOptions {
217            circuit_id: CircuitId::new("increment"),
218            network_id: "local-test".into(),
219            ..BuildCallOptions::default()
220        };
221    }
222
223    #[test]
224    fn options_compile_with_serializer_closure() {
225        let _opts: BuildCallOptions = BuildCallOptions {
226            circuit_id: CircuitId::new("increment"),
227            private_state_id: Some(PrivateStateId::new("counter")),
228            network_id: "local-test".into(),
229            serialize_next_private_state: Some(Box::new(|_v: &Value| Ok(vec![]))),
230            ..BuildCallOptions::default()
231        };
232    }
233
234    async fn counter_initial_state() -> moonproof_ledger::onchain_runtime::state::ContractState<
235        moonproof_ledger::storage::db::InMemoryDB,
236    > {
237        let executable = counter_ir_executable().await;
238        let ctor = moonproof_runtime::executable::ConstructorContext {
239            initial_private_state: moonproof_runtime_ir::RuntimeValue::Null,
240            initial_zswap_local_state: crate::utils::zswap_utils::CompactZswapLocalState::empty(
241                crate::types::CoinPublicKey([0u8; 32]),
242            ),
243            coin_public_key: crate::types::CoinPublicKey([0u8; 32]),
244            signing_key: moonproof_ledger::signatures::schnorr_signing_key(&[0x10u8; 32]).unwrap(),
245            time: None,
246        };
247        executable
248            .initialize(ctor, moonproof_runtime_ir::RuntimeValue::Null)
249            .await
250            .unwrap()
251            .initial_contract_state
252    }
253
254    fn counter_call_options() -> BuildCallOptions {
255        BuildCallOptions {
256            contract_address: dummy_address(),
257            circuit_id: CircuitId::new("increment"),
258            initial_private_state: Some(Value::Null),
259            network_id: "local-test".into(),
260            ..BuildCallOptions::default()
261        }
262    }
263
264    /// ports: `submit-call-tx.test.ts::should successfully submit call transaction`
265    #[tokio::test]
266    #[ignore = "proves a circuit-bearing call tx in process; needs SRS params"]
267    async fn happy_path_returns_finalized_call_tx_data() {
268        let state = counter_initial_state().await;
269        let bundle = ZSwapAndContractState {
270            zswap_chain_state_bytes: Vec::new(),
271            contract_state: state.clone(),
272            ledger_parameters_bytes: crate::test_helpers::initial_ledger_parameters_bytes(),
273        };
274        let (providers, _) = scripted_providers_with_real_prover(
275            None,
276            Some(state),
277            Some(bundle),
278            TxStatus::SucceedEntirely,
279        );
280        let executable = counter_ir_executable().await;
281        let mut rng = rand::rngs::StdRng::from_seed([0xCAu8; 32]);
282        let outcome = Box::pin(submit_call_tx(
283            &mut rng,
284            &executable,
285            &providers,
286            counter_call_options(),
287            None,
288        ))
289        .await
290        .unwrap();
291        let finalized = outcome
292            .finalized
293            .expect("unscoped call must produce finalized data");
294        assert_eq!(finalized.finalized.status, TxStatus::SucceedEntirely);
295    }
296
297    /// ports: `submit-call-tx.test.ts::should throw CallTxFailedError on FailEntirely`
298    #[tokio::test]
299    #[ignore = "proves a circuit-bearing call tx in process; needs SRS params"]
300    async fn fail_entirely_returns_call_tx_failed_with_circuit_id() {
301        let state = counter_initial_state().await;
302        let bundle = ZSwapAndContractState {
303            zswap_chain_state_bytes: Vec::new(),
304            contract_state: state.clone(),
305            ledger_parameters_bytes: crate::test_helpers::initial_ledger_parameters_bytes(),
306        };
307        let (providers, _) = scripted_providers_with_real_prover(
308            None,
309            Some(state),
310            Some(bundle),
311            TxStatus::FailEntirely,
312        );
313        let executable = counter_ir_executable().await;
314        let mut rng = rand::rngs::StdRng::from_seed([0xCBu8; 32]);
315        let err = Box::pin(submit_call_tx(
316            &mut rng,
317            &executable,
318            &providers,
319            counter_call_options(),
320            None,
321        ))
322        .await
323        .unwrap_err();
324        let msg = format!("{err}");
325        assert!(msg.contains("CallTxFailedError"), "{msg}");
326        assert!(msg.contains("increment"), "{msg}");
327    }
328
329    /// ports: `submit-call-tx.test.ts::FailFallible scenario`
330    #[tokio::test]
331    #[ignore = "proves a circuit-bearing call tx in process; needs SRS params"]
332    async fn fail_fallible_returns_call_tx_failed_preserving_status() {
333        let state = counter_initial_state().await;
334        let bundle = ZSwapAndContractState {
335            zswap_chain_state_bytes: Vec::new(),
336            contract_state: state.clone(),
337            ledger_parameters_bytes: crate::test_helpers::initial_ledger_parameters_bytes(),
338        };
339        let (providers, _) = scripted_providers_with_real_prover(
340            None,
341            Some(state),
342            Some(bundle),
343            TxStatus::FailFallible,
344        );
345        let executable = counter_ir_executable().await;
346        let mut rng = rand::rngs::StdRng::from_seed([0xCCu8; 32]);
347        let err = Box::pin(submit_call_tx(
348            &mut rng,
349            &executable,
350            &providers,
351            counter_call_options(),
352            None,
353        ))
354        .await
355        .unwrap_err();
356        match err {
357            crate::error::ContractRuntimeError::Contracts(
358                crate::error::ContractsError::CallTxFailed {
359                    finalized_tx_data,
360                    circuit_ids,
361                },
362            ) => {
363                assert_eq!(finalized_tx_data.status, TxStatus::FailFallible);
364                assert_eq!(circuit_ids, vec![CircuitId::new("increment")]);
365            }
366            other => panic!("expected CallTxFailed, got {other:?}"),
367        }
368    }
369
370    /// ports: `submit-call-tx.test.ts::scoped call deferral`
371    #[tokio::test]
372    async fn scoped_call_defers_into_transaction_context() {
373        use crate::transaction::{ScopedTransactionOptions, TransactionContextImpl};
374        use std::sync::Arc as StdArc;
375
376        let state = counter_initial_state().await;
377        let bundle = ZSwapAndContractState {
378            zswap_chain_state_bytes: Vec::new(),
379            contract_state: state.clone(),
380            ledger_parameters_bytes: crate::test_helpers::initial_ledger_parameters_bytes(),
381        };
382        let (providers, _) = scripted_providers_with_real_prover(
383            None,
384            Some(state),
385            Some(bundle),
386            TxStatus::FailEntirely,
387        );
388        let providers_arc = StdArc::new(providers);
389        let ctx = StdArc::new(TransactionContextImpl::new(
390            providers_arc.clone(),
391            ScopedTransactionOptions::default(),
392        ));
393        let executable = counter_ir_executable().await;
394        let mut rng = rand::rngs::StdRng::from_seed([0xCDu8; 32]);
395        let outcome = Box::pin(submit_call_tx(
396            &mut rng,
397            &executable,
398            &providers_arc,
399            counter_call_options(),
400            Some(&ctx),
401        ))
402        .await
403        .unwrap();
404        assert!(
405            outcome.finalized.is_none(),
406            "scoped call must defer submission"
407        );
408        assert_eq!(ctx.merged_call_count(), 1);
409        assert_eq!(
410            ctx.accumulated_circuit_ids(),
411            vec![CircuitId::new("increment")]
412        );
413    }
414}