Skip to main content

moonproof_contracts/
transaction.rs

1//! Port of `@midnight-ntwrk/midnight-js-contracts/src/transaction.ts`
2//! and `internal/transaction.ts`.
3//!
4//! Scoped contract transactions — runs a caller-supplied closure
5//! inside a transaction context that batches multiple circuit calls
6//! into a single submitted transaction. The TS API is
7//! `withContractScopedTransaction(providers, fn, options)`; the Rust
8//! port is [`with_contract_scoped_transaction`].
9//!
10//! # When to use a scoped transaction
11//!
12//! When an app wants several circuit calls to happen atomically in
13//! one tx (so they all succeed or all fail together), it routes them
14//! through a [`TransactionContext`]. Each in-scope call's
15//! `UnsubmittedCallTxData` is merged into a running queue; on a
16//! successful exit of `fn`, the queue is submitted as one
17//! transaction. If `fn` throws, the queue is discarded — nothing
18//! reaches the chain.
19//!
20//! # Identity validation
21//!
22//! Cached states inside the scope carry a [`CachedStateIdentity`]
23//! `(contract_address, private_state_id)` tuple. Re-entry attempts
24//! with a mismatched identity raise
25//! [`crate::error::ContractsError::ScopedTransactionIdentityMismatch`]
26//! before any callback runs. This guards against silent state-mixup
27//! when the caller threads the same `txCtx` through code targeting
28//! different contracts.
29//!
30//! # Submission scope
31//!
32//! A call made with the scope ([`crate::submit_call_tx::submit_call_tx`]
33//! given `Some(ctx)`) runs against the scope's cached states, so a
34//! second call to the same contract sees the first one's effects, and
35//! is merged into the scope's queue instead of being submitted. Each
36//! call's transaction carries its intent at a segment of its own, so
37//! [`TransactionContextImpl::submit`] merges them into one, balances the
38//! fee once over the merged transaction, and submits it through
39//! [`crate::submit_tx::submit_tx`].
40
41use std::collections::HashMap;
42use std::future::Future;
43use std::sync::{Arc, Mutex};
44
45use crate::error::{ContractRuntimeError, ContractsError, Result, ScopedTxIdentity};
46use crate::fee_balancing::{apply_fee_balancing, FeeBalancingConfig};
47use crate::providers::ErasedProviders;
48use crate::submit_call_tx::PrivateStateSerializer;
49use crate::submit_tx::{submit_tx, SubmitTxOptions};
50use crate::tx_model::{FinalizedCallTxData, UnsubmittedCallTxData};
51use crate::types::{BlockHash, CircuitId, CoinPublicKey, EncPublicKey, PrivateStateId};
52
53// =====================================================================
54// Public configuration
55// =====================================================================
56
57/// Options for [`with_contract_scoped_transaction`]. Port of TS
58/// `ScopedTransactionOptions`.
59#[derive(Debug, Clone, Default)]
60pub struct ScopedTransactionOptions {
61    /// Optional human-readable name for the transaction scope. Used
62    /// in error messages when the closure or submission fails so the
63    /// failure can be attributed to the right scope. Falls back to
64    /// `<unnamed>` when absent.
65    pub scope_name: Option<String>,
66    /// Optional caller-supplied additional `CoinPublicKey →
67    /// EncPublicKey` mappings. Threaded into the resolver used by
68    /// downstream call-tx builders so the scope can address coin
69    /// recipients the wallet doesn't know about.
70    pub additional_coin_enc_public_key_mappings: Option<HashMap<CoinPublicKey, EncPublicKey>>,
71}
72
73/// Cache key for in-scope contract states. Port of TS
74/// `CachedStateIdentity`.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct CachedStateIdentity {
77    pub contract_address: moonproof_ledger::coin_structure::contract::ContractAddress,
78    pub private_state_id: Option<PrivateStateId>,
79}
80
81/// Cached states pinned to one [`CachedStateIdentity`]. Port of the
82/// union TS `ContractStates<PS> | PublicContractStates`.
83///
84/// Generic on the private-state payload — `PS = ()` for stateless
85/// contracts (in which case `private_state` is `Some(())`); `PS =
86/// MyState` for stateful contracts that need to thread typed state.
87/// `private_state` is `Option<RuntimeValue>` to capture the
88/// distinction between "public-only states" (no private state) and
89/// "full states" (private state included).
90#[derive(Debug, Clone)]
91pub struct CachedStates {
92    pub contract_state: moonproof_ledger::onchain_runtime::state::ContractState<
93        moonproof_ledger::storage::db::InMemoryDB,
94    >,
95    pub zswap_chain_state_bytes: Vec<u8>,
96    pub ledger_parameters_bytes: Vec<u8>,
97    pub private_state: Option<moonproof_runtime_ir::RuntimeValue>,
98}
99
100// =====================================================================
101// TransactionContextImpl
102// =====================================================================
103
104/// Cached call-tx slot inside a scope: the most-recent merged call
105/// plus its optional private-state id.
106type LastUnsubmittedCallSlot = Option<(UnsubmittedCallTxData, Option<PrivateStateId>)>;
107
108/// The states a scope caches, with the identity they were read for and
109/// the block they were read at.
110struct CachedEntry {
111    identity: CachedStateIdentity,
112    states: CachedStates,
113    block_hash: Option<BlockHash>,
114}
115
116/// What submitting a scope needs from its calls beyond their
117/// transactions. Passed with each merged call; the last call's wins.
118#[derive(Default)]
119pub struct DeferredSubmission {
120    /// Balances the merged transaction's fee once. A call made in a
121    /// scope is built without balancing: each call balancing its own
122    /// transaction would spend the same dust twice.
123    pub fee_balancing: Option<FeeBalancingConfig>,
124    /// Network the fee-balancing intent is built for.
125    pub network_id: String,
126    /// Serializes the last call's next private state for the
127    /// private-state provider, as the unscoped path does.
128    pub serialize_next_private_state: Option<PrivateStateSerializer>,
129}
130
131/// In-scope state for a single
132/// [`with_contract_scoped_transaction`] invocation.
133///
134/// All mutable state is behind a `Mutex` so callbacks can call methods
135/// through a shared `&Self` reference, matching the TS pattern of
136/// passing `txCtx` to closures that update it.
137pub struct TransactionContextImpl {
138    providers: Arc<ErasedProviders>,
139    options: ScopedTransactionOptions,
140    cached_states: Mutex<Option<CachedEntry>>,
141    current_unsubmitted_call: Mutex<LastUnsubmittedCallSlot>,
142    deferred: Mutex<DeferredSubmission>,
143    /// Each merged call's typed unproven transaction is pushed onto
144    /// this queue. On submit, they are merged via
145    /// `Transaction::merge` and the result is fed into [`submit_tx`].
146    accumulated_unproven_txs: Mutex<Vec<crate::tx_phase::UnprovenTx>>,
147    /// Circuit ids of every merged call — preserved in order. Empty
148    /// for an unused scope.
149    accumulated_circuit_ids: Mutex<Vec<CircuitId>>,
150}
151
152impl TransactionContextImpl {
153    /// Construct a new transaction context bound to `providers`.
154    /// Port of TS `new TransactionContextImpl(providers, options?)`.
155    #[must_use]
156    pub fn new(providers: Arc<ErasedProviders>, options: ScopedTransactionOptions) -> Self {
157        Self {
158            providers,
159            options,
160            cached_states: Mutex::new(None),
161            current_unsubmitted_call: Mutex::new(None),
162            deferred: Mutex::new(DeferredSubmission::default()),
163            accumulated_unproven_txs: Mutex::new(Vec::new()),
164            accumulated_circuit_ids: Mutex::new(Vec::new()),
165        }
166    }
167
168    /// Returns the providers bundle this scope is bound to.
169    #[inline]
170    #[must_use]
171    pub fn providers(&self) -> &Arc<ErasedProviders> {
172        &self.providers
173    }
174
175    /// Returns the scope's optional `additional_coin_enc_public_key_mappings`.
176    /// Port of TS `getAdditionalMappings()`.
177    #[must_use]
178    pub fn get_additional_mappings(&self) -> Option<&HashMap<CoinPublicKey, EncPublicKey>> {
179        self.options
180            .additional_coin_enc_public_key_mappings
181            .as_ref()
182    }
183
184    /// Cache the contract / private states under `identity` for the
185    /// rest of the scope. Port of TS `[CacheStates]`. Overwrites any
186    /// previously cached states.
187    pub fn cache_states(&self, states: CachedStates, identity: CachedStateIdentity) {
188        self.cache_states_at(states, identity, None);
189    }
190
191    /// Like [`Self::cache_states`], recording the block the states were
192    /// read at: later calls in the scope read their callees at the same
193    /// block, so the whole scope sees one chain snapshot.
194    pub fn cache_states_at(
195        &self,
196        states: CachedStates,
197        identity: CachedStateIdentity,
198        block_hash: Option<BlockHash>,
199    ) {
200        *self.cached_states.lock().unwrap() = Some(CachedEntry {
201            identity,
202            states,
203            block_hash,
204        });
205    }
206
207    /// The block the cached states were read at, when it was recorded.
208    #[must_use]
209    pub fn cached_block_hash(&self) -> Option<BlockHash> {
210        self.cached_states
211            .lock()
212            .unwrap()
213            .as_ref()
214            .and_then(|entry| entry.block_hash.clone())
215    }
216
217    /// Look up the cached states **only if** `identity` matches the
218    /// identity originally cached. Returns `None` if nothing is
219    /// cached; raises [`ContractsError::ScopedTransactionIdentityMismatch`]
220    /// when a mismatched identity is supplied. Port of TS
221    /// `[GetCurrentStatesForIdentity](identity)`.
222    pub fn get_current_states_for_identity(
223        &self,
224        identity: &CachedStateIdentity,
225    ) -> Result<Option<CachedStates>> {
226        let guard = self.cached_states.lock().unwrap();
227        let Some(CachedEntry {
228            identity: cached_identity,
229            states,
230            ..
231        }) = guard.as_ref()
232        else {
233            return Ok(None);
234        };
235        if cached_identity != identity {
236            return Err(ContractRuntimeError::Contracts(
237                ContractsError::ScopedTransactionIdentityMismatch {
238                    cached: ScopedTxIdentity {
239                        contract_address: moonproof_runtime::state::contract_address_to_hex(
240                            &cached_identity.contract_address,
241                        ),
242                        private_state_id: cached_identity.private_state_id.clone(),
243                    },
244                    requested: ScopedTxIdentity {
245                        contract_address: moonproof_runtime::state::contract_address_to_hex(
246                            &identity.contract_address,
247                        ),
248                        private_state_id: identity.private_state_id.clone(),
249                    },
250                },
251            ));
252        }
253        Ok(Some(states.clone()))
254    }
255
256    /// Bypass-identity accessor — returns whatever's cached. Port of
257    /// TS `getCurrentStates()`. Marked deprecated in TS because it
258    /// can return states from a different contract; preserved here
259    /// for parity. Prefer [`Self::get_current_states_for_identity`].
260    pub fn get_current_states(&self) -> Option<CachedStates> {
261        self.cached_states
262            .lock()
263            .unwrap()
264            .as_ref()
265            .map(|entry| entry.states.clone())
266    }
267
268    /// Returns the most-recent unsubmitted call's data + optional
269    /// private-state id. Port of TS
270    /// `getLastUnsubmittedCallTxDataToTransact()`.
271    pub fn get_last_unsubmitted_call_tx_data_to_transact(
272        &self,
273    ) -> Option<(UnsubmittedCallTxData, Option<PrivateStateId>)> {
274        self.current_unsubmitted_call.lock().unwrap().clone()
275    }
276
277    /// Merge a circuit-call's unsubmitted-tx data into the running
278    /// scope. Port of TS `[MergeUnsubmittedCallTxData]`.
279    ///
280    /// 1. Records `(call_data, private_state_id)` as the latest
281    ///    unsubmitted call.
282    /// 2. Appends the call's unproven tx bytes onto the accumulator
283    ///    queue (deferred merging — see module-level docs).
284    /// 3. Appends `circuit_id` onto the circuit-id list.
285    /// 4. If states are cached, advances them by the call: the
286    ///    contract's data becomes the call's next contract state and
287    ///    the private-state slot its `next_private_state`, so the next
288    ///    call in the scope runs against them. The zswap chain state,
289    ///    the ledger parameters and the pinned block stay as read.
290    pub fn merge_unsubmitted_call_tx_data(
291        &self,
292        circuit_id: CircuitId,
293        call_data: UnsubmittedCallTxData,
294        private_state_id: Option<PrivateStateId>,
295    ) {
296        if let Some(entry) = self.cached_states.lock().unwrap().as_mut() {
297            entry.states.contract_state.data =
298                call_data.result.public.next_contract_state.data.clone();
299            entry.states.private_state = Some(call_data.result.private.next_private_state.clone());
300        }
301
302        self.accumulated_unproven_txs
303            .lock()
304            .unwrap()
305            .push(call_data.tx.unproven_tx.clone());
306        self.accumulated_circuit_ids
307            .lock()
308            .unwrap()
309            .push(circuit_id);
310        *self.current_unsubmitted_call.lock().unwrap() = Some((call_data, private_state_id));
311    }
312
313    /// Record what submitting the scope needs from the call just
314    /// merged: its fee-balancing inputs and private-state serializer.
315    pub fn defer_submission(&self, deferred: DeferredSubmission) {
316        *self.deferred.lock().unwrap() = deferred;
317    }
318
319    /// Submit the accumulated calls as a single transaction. Port of
320    /// TS `[Submit]()`.
321    ///
322    /// # Errors
323    ///
324    /// - Returns a clear `Provider` error when no calls have been
325    ///   merged into the scope (the TS variant throws `Error('No
326    ///   calls were submitted.')`).
327    /// - Propagates any error from
328    ///   [`crate::submit_tx::submit_tx`].
329    /// - On non-`SucceedEntirely`, raises
330    ///   [`ContractsError::CallTxFailed`] carrying every merged
331    ///   circuit id (matches TS's `new CallTxFailedError(...,
332    ///   submitTxOptions.circuitId!)`).
333    pub async fn submit(&self) -> Result<FinalizedCallTxData> {
334        let (last_call, last_psi) = self
335            .current_unsubmitted_call
336            .lock()
337            .unwrap()
338            .clone()
339            .ok_or(ContractRuntimeError::Provider {
340                provider: "scoped_transaction",
341                message: "No calls were submitted.".to_owned(),
342            })?;
343
344        let chunks = self.accumulated_unproven_txs.lock().unwrap().clone();
345        let circuit_ids = self.accumulated_circuit_ids.lock().unwrap().clone();
346        let merged = merge_unproven_tx_chunks(chunks)?;
347        let DeferredSubmission {
348            fee_balancing,
349            network_id,
350            serialize_next_private_state,
351        } = std::mem::take(&mut *self.deferred.lock().unwrap());
352        let merged = match fee_balancing {
353            Some(config) => crate::tx_phase::UnprovenTx::new(apply_fee_balancing(
354                &mut rand::thread_rng(),
355                merged.into_inner(),
356                &config,
357                &network_id,
358            )?),
359            None => merged,
360        };
361
362        let submit_opts = SubmitTxOptions {
363            unproven_tx: merged,
364            circuit_ids: Some(circuit_ids.clone()),
365            prove_config: crate::providers::ProveTxConfig::default(),
366            ttl_ms: None,
367        };
368        let finalized = submit_tx(&self.providers, submit_opts).await?;
369        if !finalized.status.is_success() {
370            return Err(ContractRuntimeError::Contracts(
371                ContractsError::call_tx_failed(finalized, circuit_ids),
372            ));
373        }
374
375        // On success, persist the last call's next private state — as
376        // the unscoped path does, only when the call named an id and
377        // supplied a serializer.
378        if let (Some(psi), Some(serialize)) =
379            (last_psi.as_ref(), serialize_next_private_state.as_ref())
380        {
381            let bytes = serialize(&last_call.result.private.next_private_state)?;
382            self.providers.private_state.set(psi, bytes).await?;
383        }
384
385        Ok(FinalizedCallTxData {
386            result: last_call.result,
387            tx: last_call.tx,
388            finalized,
389        })
390    }
391
392    /// Returns the accumulated `Vec<FinalizedTxData>` slot — empty
393    /// until `submit()` runs. Used by tests; equivalent to the TS
394    /// `submitTxOptions` accumulator visibility.
395    #[must_use]
396    pub fn accumulated_circuit_ids(&self) -> Vec<CircuitId> {
397        self.accumulated_circuit_ids.lock().unwrap().clone()
398    }
399
400    /// Returns the number of merged calls — a proxy for whether the
401    /// scope has been used.
402    #[must_use]
403    pub fn merged_call_count(&self) -> usize {
404        self.accumulated_circuit_ids.lock().unwrap().len()
405    }
406}
407
408// =====================================================================
409// Free functions
410// =====================================================================
411
412/// Run `fn` inside a fresh
413/// [`TransactionContextImpl`]. Port of TS
414/// `withContractScopedTransaction`.
415///
416/// On a successful exit of `fn`, the scope's accumulated calls are
417/// submitted as a single transaction via
418/// [`TransactionContextImpl::submit`]. On a failed exit, nothing is
419/// submitted and the closure's error is wrapped with the scope name
420/// so callers can attribute the failure.
421///
422/// # Errors
423///
424/// - Wraps any error raised by `fn` with the scope name: the
425///   message is `"Unexpected error executing scoped transaction
426///   '<scope_name>': <inner error>"`. Falls back to `<unnamed>` if
427///   no scope name was provided.
428/// - Wraps any error raised during submission with a similar prefix
429///   — exception: a [`ContractsError::CallTxFailed`] propagates
430///   verbatim because callers typically want to pattern-match on it
431///   rather than the wrapped variant.
432pub async fn with_contract_scoped_transaction<F, Fut>(
433    providers: Arc<ErasedProviders>,
434    f: F,
435    options: ScopedTransactionOptions,
436) -> Result<FinalizedCallTxData>
437where
438    F: FnOnce(Arc<TransactionContextImpl>) -> Fut,
439    Fut: Future<Output = Result<()>>,
440{
441    let scope_name = options.scope_name.clone();
442    let ctx = Arc::new(TransactionContextImpl::new(providers, options));
443
444    if let Err(err) = f(ctx.clone()).await {
445        return Err(wrap_with_scope_name(
446            &err,
447            scope_name.as_deref(),
448            "executing",
449        ));
450    }
451
452    match ctx.submit().await {
453        Ok(data) => Ok(data),
454        Err(err) => match err {
455            // Preserve CallTxFailedError verbatim — callers
456            // pattern-match on it for retry / refund logic.
457            ContractRuntimeError::Contracts(ContractsError::CallTxFailed { .. }) => Err(err),
458            other => Err(wrap_with_scope_name(
459                &other,
460                scope_name.as_deref(),
461                "submitting",
462            )),
463        },
464    }
465}
466
467/// Convenience: wrap an error with `<unnamed>` or the supplied
468/// scope name, mirroring the TS `Unexpected error <action> scoped
469/// transaction '...': ...` format.
470fn wrap_with_scope_name(
471    err: &ContractRuntimeError,
472    scope_name: Option<&str>,
473    action: &str,
474) -> ContractRuntimeError {
475    let name = scope_name.unwrap_or("<unnamed>");
476    let inner = err.to_string();
477    ContractRuntimeError::Provider {
478        provider: "scoped_transaction",
479        message: format!("Unexpected error {action} scoped transaction '{name}': {inner}"),
480    }
481}
482
483/// Merge a sequence of tagged-serialized unproven-tx byte chunks
484/// into one, via `Transaction::merge`. Returns the first chunk
485/// verbatim if there's only one; errors if `chunks` is empty or if
486/// any chunk fails to deserialize.
487fn merge_unproven_tx_chunks(
488    chunks: Vec<crate::tx_phase::UnprovenTx>,
489) -> Result<crate::tx_phase::UnprovenTx> {
490    if chunks.is_empty() {
491        return Err(ContractRuntimeError::Provider {
492            provider: "scoped_transaction",
493            message: "merge: no unproven tx chunks to merge".to_owned(),
494        });
495    }
496    let mut iter = chunks.into_iter();
497    let first = iter.next().expect("non-empty checked above");
498    if iter.len() == 0 {
499        return Ok(first);
500    }
501    let mut merged = first.into_inner();
502    for next in iter {
503        merged = merged
504            .merge(&next.into_inner())
505            .map_err(|e| ContractRuntimeError::Provider {
506                provider: "scoped_transaction",
507                message: format!("Transaction::merge failed: {e}"),
508            })?;
509    }
510    Ok(crate::tx_phase::UnprovenTx::new(merged))
511}
512
513#[cfg(test)]
514mod tests {
515    //! Ports of `scoped-transaction.test.ts` and
516    //! `transaction-identity.test.ts`.
517
518    use super::*;
519    use crate::test_helpers::{counter_ir_executable, dummy_address, scripted_providers};
520    use crate::tx_model::UnsubmittedTxData;
521    use crate::types::{
522        CallResult, CallResultPrivate, CallResultPublic, CircuitId, PrivateStateId, TxStatus,
523    };
524    use moonproof_ledger::base_crypto::fab::AlignedValue;
525    use moonproof_ledger::onchain_runtime::state::ContractState;
526    use moonproof_ledger::storage::db::InMemoryDB;
527    use moonproof_runtime_ir::RuntimeValue;
528
529    fn dummy_address_with_nonce(
530        nonce: u8,
531    ) -> moonproof_ledger::coin_structure::contract::ContractAddress {
532        moonproof_ledger::coin_structure::contract::ContractAddress(
533            moonproof_ledger::base_crypto::hash::HashOutput([nonce; 32]),
534        )
535    }
536
537    async fn fresh_contract_state() -> ContractState<InMemoryDB> {
538        let executable = counter_ir_executable().await;
539        let ctor = moonproof_runtime::executable::ConstructorContext {
540            initial_private_state: moonproof_runtime_ir::RuntimeValue::Null,
541            initial_zswap_local_state: crate::utils::zswap_utils::CompactZswapLocalState::empty(
542                crate::types::CoinPublicKey([0u8; 32]),
543            ),
544            coin_public_key: crate::types::CoinPublicKey([0u8; 32]),
545            signing_key: moonproof_ledger::signatures::schnorr_signing_key(&[0x21u8; 32]).unwrap(),
546            time: None,
547        };
548        executable
549            .initialize(ctor, moonproof_runtime_ir::RuntimeValue::Null)
550            .await
551            .unwrap()
552            .initial_contract_state
553    }
554
555    fn fixture_states(state: ContractState<InMemoryDB>) -> CachedStates {
556        CachedStates {
557            contract_state: state,
558            zswap_chain_state_bytes: vec![0xAA, 0xBB],
559            ledger_parameters_bytes: vec![0xCC, 0xDD],
560            private_state: Some(RuntimeValue::Int(0)),
561        }
562    }
563
564    fn fixture_call_data(next_private_state: u64) -> UnsubmittedCallTxData {
565        UnsubmittedCallTxData {
566            result: CallResult {
567                public: CallResultPublic {
568                    next_contract_state: ContractState::<InMemoryDB>::new(
569                        moonproof_ledger::onchain_runtime::state::StateValue::Null,
570                        moonproof_ledger::storage::storage::HashMap::new(),
571                        moonproof_ledger::onchain_runtime::state::ContractMaintenanceAuthority::default(),
572                    ),
573                    public_transcript: Vec::new(),
574                    partitioned_transcript: (None, None),
575                    events: Vec::new(),
576                },
577                private: CallResultPrivate {
578                    input: AlignedValue::concat(std::iter::empty::<&AlignedValue>()),
579                    output: AlignedValue::concat(std::iter::empty::<&AlignedValue>()),
580                    private_transcript_outputs: Vec::new(),
581                    result: RuntimeValue::Null,
582                    next_private_state: RuntimeValue::Int(i128::from(next_private_state)),
583                    next_zswap_local_state:
584                        crate::utils::zswap_utils::CompactZswapLocalState::empty(
585                            crate::types::CoinPublicKey([0u8; 32]),
586                        ),
587                },
588                callees: Vec::new(),
589            },
590            tx: UnsubmittedTxData {
591                unproven_tx: empty_unproven_tx(),
592                new_coins: Vec::new(),
593            },
594        }
595    }
596
597    /// Empty pre-prove transaction — convenience for the tests that
598    /// don't care about tx contents, only about the wiring of the
599    /// scoped-transaction context around them.
600    fn empty_unproven_tx() -> crate::tx_phase::UnprovenTx {
601        use moonproof_ledger::ledger::structure::Transaction;
602        let tx: Transaction<
603            moonproof_ledger::signatures::Signature,
604            moonproof_ledger::ledger::structure::ProofPreimageMarker,
605            moonproof_ledger::transient_crypto::commitment::PedersenRandomness,
606            moonproof_ledger::storage::db::InMemoryDB,
607        > = Transaction::from_intents(
608            "local-test",
609            moonproof_ledger::storage::storage::HashMap::new(),
610        );
611        crate::tx_phase::UnprovenTx::new(tx)
612    }
613
614    fn make_ctx() -> Arc<TransactionContextImpl> {
615        let (providers, _) = scripted_providers(None, None, TxStatus::SucceedEntirely);
616        Arc::new(TransactionContextImpl::new(
617            Arc::new(providers),
618            ScopedTransactionOptions::default(),
619        ))
620    }
621
622    /// ports: `scoped-transaction.test.ts::should include scopeName in execution error message`
623    #[tokio::test]
624    async fn fn_error_is_wrapped_with_scope_name() {
625        let (providers, _) = scripted_providers(None, None, TxStatus::SucceedEntirely);
626        let result: Result<FinalizedCallTxData> = with_contract_scoped_transaction(
627            Arc::new(providers),
628            |_ctx| async {
629                Err(ContractRuntimeError::Provider {
630                    provider: "test",
631                    message: "circuit failed".to_owned(),
632                })
633            },
634            ScopedTransactionOptions {
635                scope_name: Some("myTransfer".to_owned()),
636                additional_coin_enc_public_key_mappings: None,
637            },
638        )
639        .await;
640        let err = result.expect_err("scoped transaction with throwing fn should error");
641        let msg = format!("{err}");
642        assert!(msg.contains("myTransfer"), "{msg}");
643        assert!(msg.contains("circuit failed"), "{msg}");
644    }
645
646    /// ports: `scoped-transaction.test.ts::should show <unnamed> when no scopeName`
647    #[tokio::test]
648    async fn fn_error_falls_back_to_unnamed_when_scope_name_absent() {
649        let (providers, _) = scripted_providers(None, None, TxStatus::SucceedEntirely);
650        let result: Result<FinalizedCallTxData> = with_contract_scoped_transaction(
651            Arc::new(providers),
652            |_ctx| async {
653                Err(ContractRuntimeError::Provider {
654                    provider: "test",
655                    message: "circuit failed".to_owned(),
656                })
657            },
658            ScopedTransactionOptions::default(),
659        )
660        .await;
661        let err = result.expect_err("scoped transaction with throwing fn should error");
662        let msg = format!("{err}");
663        assert!(msg.contains("<unnamed>"), "{msg}");
664    }
665
666    #[tokio::test]
667    async fn get_current_states_for_identity_returns_none_when_unset() {
668        let ctx = make_ctx();
669        let id = CachedStateIdentity {
670            contract_address: dummy_address(),
671            private_state_id: Some(PrivateStateId::new("test")),
672        };
673        assert!(ctx.get_current_states_for_identity(&id).unwrap().is_none());
674    }
675
676    #[tokio::test]
677    async fn get_current_states_for_identity_returns_cached_when_identity_matches() {
678        let ctx = make_ctx();
679        let state = fresh_contract_state().await;
680        let id = CachedStateIdentity {
681            contract_address: dummy_address(),
682            private_state_id: Some(PrivateStateId::new("test")),
683        };
684        ctx.cache_states(fixture_states(state), id.clone());
685        let got = ctx.get_current_states_for_identity(&id).unwrap();
686        assert!(got.is_some());
687        assert_eq!(
688            got.unwrap().private_state.as_ref().unwrap().as_u64(),
689            Some(0u64)
690        );
691    }
692
693    #[tokio::test]
694    async fn get_current_states_for_identity_throws_on_address_mismatch() {
695        let ctx = make_ctx();
696        let state = fresh_contract_state().await;
697        let id1 = CachedStateIdentity {
698            contract_address: dummy_address_with_nonce(0xA1),
699            private_state_id: Some(PrivateStateId::new("test")),
700        };
701        let id2 = CachedStateIdentity {
702            contract_address: dummy_address_with_nonce(0xB2),
703            private_state_id: Some(PrivateStateId::new("test")),
704        };
705        ctx.cache_states(fixture_states(state), id1);
706        let err = ctx.get_current_states_for_identity(&id2).unwrap_err();
707        matches!(
708            err,
709            ContractRuntimeError::Contracts(
710                ContractsError::ScopedTransactionIdentityMismatch { .. }
711            )
712        );
713    }
714
715    #[tokio::test]
716    async fn get_current_states_for_identity_throws_on_private_state_id_mismatch() {
717        let ctx = make_ctx();
718        let state = fresh_contract_state().await;
719        let id1 = CachedStateIdentity {
720            contract_address: dummy_address(),
721            private_state_id: Some(PrivateStateId::new("a")),
722        };
723        let id2 = CachedStateIdentity {
724            contract_address: dummy_address(),
725            private_state_id: Some(PrivateStateId::new("b")),
726        };
727        ctx.cache_states(fixture_states(state), id1);
728        let err = ctx.get_current_states_for_identity(&id2).unwrap_err();
729        matches!(
730            err,
731            ContractRuntimeError::Contracts(
732                ContractsError::ScopedTransactionIdentityMismatch { .. }
733            )
734        );
735    }
736
737    #[tokio::test]
738    async fn get_current_states_for_identity_throws_when_only_one_has_private_state_id() {
739        let ctx = make_ctx();
740        let state = fresh_contract_state().await;
741        let with_psi = CachedStateIdentity {
742            contract_address: dummy_address(),
743            private_state_id: Some(PrivateStateId::new("test")),
744        };
745        let without_psi = CachedStateIdentity {
746            contract_address: dummy_address(),
747            private_state_id: None,
748        };
749        ctx.cache_states(fixture_states(state), with_psi);
750        let err = ctx
751            .get_current_states_for_identity(&without_psi)
752            .unwrap_err();
753        matches!(
754            err,
755            ContractRuntimeError::Contracts(
756                ContractsError::ScopedTransactionIdentityMismatch { .. }
757            )
758        );
759    }
760
761    #[tokio::test]
762    async fn identity_mismatch_error_carries_both_sides() {
763        let ctx = make_ctx();
764        let state = fresh_contract_state().await;
765        let cached = CachedStateIdentity {
766            contract_address: dummy_address_with_nonce(0xA1),
767            private_state_id: Some(PrivateStateId::new("ps-id-1")),
768        };
769        let requested = CachedStateIdentity {
770            contract_address: dummy_address_with_nonce(0xB2),
771            private_state_id: Some(PrivateStateId::new("ps-id-2")),
772        };
773        ctx.cache_states(fixture_states(state), cached.clone());
774        let err = ctx.get_current_states_for_identity(&requested).unwrap_err();
775        match err {
776            ContractRuntimeError::Contracts(
777                ContractsError::ScopedTransactionIdentityMismatch {
778                    cached: c,
779                    requested: r,
780                },
781            ) => {
782                assert_eq!(
783                    c.contract_address,
784                    moonproof_runtime::state::contract_address_to_hex(&cached.contract_address)
785                );
786                assert_eq!(c.private_state_id.as_ref().unwrap().as_str(), "ps-id-1");
787                assert_eq!(
788                    r.contract_address,
789                    moonproof_runtime::state::contract_address_to_hex(&requested.contract_address)
790                );
791                assert_eq!(r.private_state_id.as_ref().unwrap().as_str(), "ps-id-2");
792            }
793            other => panic!("unexpected error variant: {other:?}"),
794        }
795    }
796
797    #[tokio::test]
798    async fn get_current_states_for_identity_allows_repeated_lookups() {
799        let ctx = make_ctx();
800        let state = fresh_contract_state().await;
801        let id = CachedStateIdentity {
802            contract_address: dummy_address(),
803            private_state_id: Some(PrivateStateId::new("test")),
804        };
805        ctx.cache_states(fixture_states(state), id.clone());
806        let r1 = ctx.get_current_states_for_identity(&id).unwrap();
807        let r2 = ctx.get_current_states_for_identity(&id).unwrap();
808        assert!(r1.is_some());
809        assert!(r2.is_some());
810    }
811
812    #[tokio::test]
813    async fn get_current_states_for_identity_works_for_public_only() {
814        let ctx = make_ctx();
815        let state = fresh_contract_state().await;
816        let id = CachedStateIdentity {
817            contract_address: dummy_address(),
818            private_state_id: None,
819        };
820        let mut states = fixture_states(state);
821        states.private_state = None;
822        ctx.cache_states(states, id.clone());
823        let got = ctx.get_current_states_for_identity(&id).unwrap();
824        assert!(got.is_some());
825        assert!(got.unwrap().private_state.is_none());
826    }
827
828    #[tokio::test]
829    async fn get_current_states_for_identity_throws_when_requested_psi_but_cached_without() {
830        let ctx = make_ctx();
831        let state = fresh_contract_state().await;
832        let cached = CachedStateIdentity {
833            contract_address: dummy_address(),
834            private_state_id: None,
835        };
836        let requested = CachedStateIdentity {
837            contract_address: dummy_address(),
838            private_state_id: Some(PrivateStateId::new("some-id")),
839        };
840        let mut states = fixture_states(state);
841        states.private_state = None;
842        ctx.cache_states(states, cached);
843        let err = ctx.get_current_states_for_identity(&requested).unwrap_err();
844        matches!(
845            err,
846            ContractRuntimeError::Contracts(
847                ContractsError::ScopedTransactionIdentityMismatch { .. }
848            )
849        );
850    }
851
852    #[tokio::test]
853    async fn get_current_states_returns_none_when_unset() {
854        let ctx = make_ctx();
855        assert!(ctx.get_current_states().is_none());
856    }
857
858    #[tokio::test]
859    async fn get_current_states_returns_cached_without_identity_check() {
860        let ctx = make_ctx();
861        let state = fresh_contract_state().await;
862        let id = CachedStateIdentity {
863            contract_address: dummy_address(),
864            private_state_id: Some(PrivateStateId::new("test")),
865        };
866        ctx.cache_states(fixture_states(state), id);
867        let got = ctx.get_current_states();
868        assert!(got.is_some());
869        assert_eq!(
870            got.unwrap().private_state.as_ref().unwrap().as_u64(),
871            Some(0u64)
872        );
873    }
874
875    #[tokio::test]
876    async fn merge_preserves_original_identity() {
877        let ctx = make_ctx();
878        let state = fresh_contract_state().await;
879        let id = CachedStateIdentity {
880            contract_address: dummy_address(),
881            private_state_id: Some(PrivateStateId::new("test")),
882        };
883        ctx.cache_states(fixture_states(state), id.clone());
884        ctx.merge_unsubmitted_call_tx_data(
885            CircuitId::new("testCircuit"),
886            fixture_call_data(42),
887            Some(PrivateStateId::new("test")),
888        );
889        let got = ctx.get_current_states_for_identity(&id).unwrap().unwrap();
890        assert_eq!(got.private_state.as_ref().unwrap().as_u64(), Some(42u64));
891    }
892
893    #[tokio::test]
894    async fn multiple_merges_keep_identity_lookup_consistent() {
895        let ctx = make_ctx();
896        let state = fresh_contract_state().await;
897        let id = CachedStateIdentity {
898            contract_address: dummy_address(),
899            private_state_id: Some(PrivateStateId::new("test")),
900        };
901        ctx.cache_states(fixture_states(state), id.clone());
902        ctx.merge_unsubmitted_call_tx_data(
903            CircuitId::new("testCircuit"),
904            fixture_call_data(1),
905            Some(PrivateStateId::new("test")),
906        );
907        ctx.merge_unsubmitted_call_tx_data(
908            CircuitId::new("testCircuit"),
909            fixture_call_data(2),
910            Some(PrivateStateId::new("test")),
911        );
912        let got = ctx.get_current_states_for_identity(&id).unwrap().unwrap();
913        assert_eq!(got.private_state.as_ref().unwrap().as_u64(), Some(2u64));
914    }
915
916    #[tokio::test]
917    async fn merge_preserves_original_ledger_parameters() {
918        let ctx = make_ctx();
919        let state = fresh_contract_state().await;
920        let mut original = fixture_states(state);
921        original.ledger_parameters_bytes = vec![0xDE, 0xAD, 0xBE, 0xEF];
922        let id = CachedStateIdentity {
923            contract_address: dummy_address(),
924            private_state_id: Some(PrivateStateId::new("test")),
925        };
926        ctx.cache_states(original.clone(), id.clone());
927        ctx.merge_unsubmitted_call_tx_data(
928            CircuitId::new("testCircuit"),
929            fixture_call_data(7),
930            Some(PrivateStateId::new("test")),
931        );
932        let got = ctx.get_current_states_for_identity(&id).unwrap().unwrap();
933        assert_eq!(got.ledger_parameters_bytes, vec![0xDE, 0xAD, 0xBE, 0xEF]);
934    }
935
936    #[tokio::test]
937    async fn multiple_merges_preserve_original_ledger_parameters() {
938        let ctx = make_ctx();
939        let state = fresh_contract_state().await;
940        let mut original = fixture_states(state);
941        original.ledger_parameters_bytes = vec![0xDE, 0xAD];
942        let id = CachedStateIdentity {
943            contract_address: dummy_address(),
944            private_state_id: Some(PrivateStateId::new("test")),
945        };
946        ctx.cache_states(original, id.clone());
947        for v in 1..=3 {
948            ctx.merge_unsubmitted_call_tx_data(
949                CircuitId::new("testCircuit"),
950                fixture_call_data(v),
951                Some(PrivateStateId::new("test")),
952            );
953        }
954        let got = ctx.get_current_states_for_identity(&id).unwrap().unwrap();
955        assert_eq!(got.ledger_parameters_bytes, vec![0xDE, 0xAD]);
956    }
957
958    #[tokio::test]
959    async fn merge_preserves_original_zswap_chain_state() {
960        let ctx = make_ctx();
961        let state = fresh_contract_state().await;
962        let mut original = fixture_states(state);
963        original.zswap_chain_state_bytes = vec![0xCA, 0xFE];
964        let id = CachedStateIdentity {
965            contract_address: dummy_address(),
966            private_state_id: Some(PrivateStateId::new("test")),
967        };
968        ctx.cache_states(original, id.clone());
969        ctx.merge_unsubmitted_call_tx_data(
970            CircuitId::new("testCircuit"),
971            fixture_call_data(7),
972            Some(PrivateStateId::new("test")),
973        );
974        let got = ctx.get_current_states_for_identity(&id).unwrap().unwrap();
975        assert_eq!(got.zswap_chain_state_bytes, vec![0xCA, 0xFE]);
976    }
977
978    #[tokio::test]
979    async fn multiple_merges_preserve_original_zswap_chain_state() {
980        let ctx = make_ctx();
981        let state = fresh_contract_state().await;
982        let mut original = fixture_states(state);
983        original.zswap_chain_state_bytes = vec![0xCA, 0xFE];
984        let id = CachedStateIdentity {
985            contract_address: dummy_address(),
986            private_state_id: Some(PrivateStateId::new("test")),
987        };
988        ctx.cache_states(original, id.clone());
989        for v in 1..=3 {
990            ctx.merge_unsubmitted_call_tx_data(
991                CircuitId::new("testCircuit"),
992                fixture_call_data(v),
993                Some(PrivateStateId::new("test")),
994            );
995        }
996        let got = ctx.get_current_states_for_identity(&id).unwrap().unwrap();
997        assert_eq!(got.zswap_chain_state_bytes, vec![0xCA, 0xFE]);
998    }
999
1000    #[tokio::test]
1001    async fn merge_then_query_with_different_identity_throws() {
1002        let ctx = make_ctx();
1003        let state = fresh_contract_state().await;
1004        let cached = CachedStateIdentity {
1005            contract_address: dummy_address_with_nonce(0xA1),
1006            private_state_id: Some(PrivateStateId::new("test")),
1007        };
1008        let other = CachedStateIdentity {
1009            contract_address: dummy_address_with_nonce(0xB2),
1010            private_state_id: Some(PrivateStateId::new("test")),
1011        };
1012        ctx.cache_states(fixture_states(state), cached);
1013        ctx.merge_unsubmitted_call_tx_data(
1014            CircuitId::new("testCircuit"),
1015            fixture_call_data(7),
1016            Some(PrivateStateId::new("test")),
1017        );
1018        let err = ctx.get_current_states_for_identity(&other).unwrap_err();
1019        matches!(
1020            err,
1021            ContractRuntimeError::Contracts(
1022                ContractsError::ScopedTransactionIdentityMismatch { .. }
1023            )
1024        );
1025    }
1026
1027    #[tokio::test]
1028    async fn submit_with_no_merged_calls_returns_no_calls_error() {
1029        let ctx = make_ctx();
1030        let err = ctx.submit().await.unwrap_err();
1031        let msg = format!("{err}");
1032        assert!(msg.contains("No calls were submitted"), "{msg}");
1033    }
1034
1035    /// Two calls in one scope build one valid transaction: the second
1036    /// runs against the state the first left, and their transactions,
1037    /// each with its intent at a segment of its own, merge.
1038    #[tokio::test]
1039    async fn two_scoped_calls_chain_their_states_and_merge() {
1040        use crate::providers::public_data::ZSwapAndContractState;
1041        use crate::submit_call_tx::submit_call_tx;
1042        use crate::test_helpers::scripted_providers_with_real_prover;
1043        use crate::unproven_call_tx::BuildCallOptions;
1044        use rand::SeedableRng;
1045
1046        let state = fresh_contract_state().await;
1047        let bundle = ZSwapAndContractState {
1048            zswap_chain_state_bytes: Vec::new(),
1049            contract_state: state.clone(),
1050            ledger_parameters_bytes: crate::test_helpers::initial_ledger_parameters_bytes(),
1051        };
1052        let (providers, _) = scripted_providers_with_real_prover(
1053            None,
1054            Some(state),
1055            Some(bundle),
1056            TxStatus::SucceedEntirely,
1057        );
1058        let providers = Arc::new(providers);
1059        let ctx = Arc::new(TransactionContextImpl::new(
1060            providers.clone(),
1061            ScopedTransactionOptions::default(),
1062        ));
1063        let executable = counter_ir_executable().await;
1064        let mut rng = rand::rngs::StdRng::seed_from_u64(0x5C0);
1065        let options = || BuildCallOptions {
1066            contract_address: dummy_address(),
1067            circuit_id: CircuitId::new("increment"),
1068            initial_private_state: Some(RuntimeValue::Null),
1069            network_id: "local-test".into(),
1070            ..BuildCallOptions::default()
1071        };
1072        let first = Box::pin(submit_call_tx(
1073            &mut rng,
1074            &executable,
1075            &providers,
1076            options(),
1077            Some(&ctx),
1078        ))
1079        .await
1080        .unwrap();
1081        let second = Box::pin(submit_call_tx(
1082            &mut rng,
1083            &executable,
1084            &providers,
1085            options(),
1086            Some(&ctx),
1087        ))
1088        .await
1089        .unwrap();
1090
1091        assert_ne!(
1092            first.unsubmitted.result.public.next_contract_state.data,
1093            second.unsubmitted.result.public.next_contract_state.data,
1094            "the second increment ran against the first's state"
1095        );
1096        let id = CachedStateIdentity {
1097            contract_address: dummy_address(),
1098            private_state_id: None,
1099        };
1100        assert_eq!(
1101            ctx.get_current_states_for_identity(&id)
1102                .unwrap()
1103                .unwrap()
1104                .contract_state
1105                .data,
1106            second.unsubmitted.result.public.next_contract_state.data
1107        );
1108
1109        let chunks = ctx.accumulated_unproven_txs.lock().unwrap().clone();
1110        let merged = merge_unproven_tx_chunks(chunks).expect("the calls merge");
1111        match merged.as_inner() {
1112            moonproof_ledger::ledger::structure::Transaction::Standard(stx) => {
1113                assert_eq!(stx.intents.size(), 2);
1114            }
1115            other @ moonproof_ledger::ledger::structure::Transaction::ClaimRewards(_) => {
1116                panic!("expected a standard transaction, got {other:?}")
1117            }
1118        }
1119    }
1120
1121    /// A call for another contract in a scope already holding one's
1122    /// states is refused, as midnight-js refuses it.
1123    #[tokio::test]
1124    async fn a_scoped_call_for_another_contract_is_refused() {
1125        use crate::providers::public_data::ZSwapAndContractState;
1126        use crate::submit_call_tx::submit_call_tx;
1127        use crate::test_helpers::scripted_providers_with_real_prover;
1128        use crate::unproven_call_tx::BuildCallOptions;
1129        use rand::SeedableRng;
1130
1131        let state = fresh_contract_state().await;
1132        let bundle = ZSwapAndContractState {
1133            zswap_chain_state_bytes: Vec::new(),
1134            contract_state: state.clone(),
1135            ledger_parameters_bytes: crate::test_helpers::initial_ledger_parameters_bytes(),
1136        };
1137        let (providers, _) = scripted_providers_with_real_prover(
1138            None,
1139            Some(state),
1140            Some(bundle),
1141            TxStatus::SucceedEntirely,
1142        );
1143        let providers = Arc::new(providers);
1144        let ctx = Arc::new(TransactionContextImpl::new(
1145            providers.clone(),
1146            ScopedTransactionOptions::default(),
1147        ));
1148        let executable = counter_ir_executable().await;
1149        let mut rng = rand::rngs::StdRng::seed_from_u64(0x5C1);
1150        let options = |address| BuildCallOptions {
1151            contract_address: address,
1152            circuit_id: CircuitId::new("increment"),
1153            initial_private_state: Some(RuntimeValue::Null),
1154            network_id: "local-test".into(),
1155            ..BuildCallOptions::default()
1156        };
1157        Box::pin(submit_call_tx(
1158            &mut rng,
1159            &executable,
1160            &providers,
1161            options(dummy_address()),
1162            Some(&ctx),
1163        ))
1164        .await
1165        .unwrap();
1166        let err = Box::pin(submit_call_tx(
1167            &mut rng,
1168            &executable,
1169            &providers,
1170            options(dummy_address_with_nonce(0xB2)),
1171            Some(&ctx),
1172        ))
1173        .await
1174        .unwrap_err();
1175        assert!(
1176            matches!(
1177                err,
1178                ContractRuntimeError::Contracts(
1179                    ContractsError::ScopedTransactionIdentityMismatch { .. }
1180                )
1181            ),
1182            "{err}"
1183        );
1184    }
1185}