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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
//! Port of `@midnight-ntwrk/midnight-js-contracts/src/transaction.ts`
//! and `internal/transaction.ts`.
//!
//! Scoped contract transactions — runs a caller-supplied closure
//! inside a transaction context that batches multiple circuit calls
//! into a single submitted transaction. The TS API is
//! `withContractScopedTransaction(providers, fn, options)`; the Rust
//! port is [`with_contract_scoped_transaction`].
//!
//! # When to use a scoped transaction
//!
//! When an app wants several circuit calls to happen atomically in
//! one tx (so they all succeed or all fail together), it routes them
//! through a [`TransactionContext`]. Each in-scope call's
//! `UnsubmittedCallTxData` is merged into a running queue; on a
//! successful exit of `fn`, the queue is submitted as one
//! transaction. If `fn` throws, the queue is discarded — nothing
//! reaches the chain.
//!
//! # Identity validation
//!
//! Cached states inside the scope carry a [`CachedStateIdentity`]
//! `(contract_address, private_state_id)` tuple. Re-entry attempts
//! with a mismatched identity raise
//! [`crate::error::ContractsError::ScopedTransactionIdentityMismatch`]
//! before any callback runs. This guards against silent state-mixup
//! when the caller threads the same `txCtx` through code targeting
//! different contracts.
//!
//! # Submission scope
//!
//! A call made with the scope ([`crate::submit_call_tx::submit_call_tx`]
//! given `Some(ctx)`) runs against the scope's cached states, so a
//! second call to the same contract sees the first one's effects, and
//! is merged into the scope's queue instead of being submitted. Each
//! call's transaction carries its intent at a segment of its own, so
//! [`TransactionContextImpl::submit`] merges them into one, balances the
//! fee once over the merged transaction, and submits it through
//! [`crate::submit_tx::submit_tx`].

use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, Mutex};

use crate::error::{ContractRuntimeError, ContractsError, Result, ScopedTxIdentity};
use crate::fee_balancing::{apply_fee_balancing, FeeBalancingConfig};
use crate::providers::ErasedProviders;
use crate::submit_call_tx::PrivateStateSerializer;
use crate::submit_tx::{submit_tx, SubmitTxOptions};
use crate::tx_model::{FinalizedCallTxData, UnsubmittedCallTxData};
use crate::types::{BlockHash, CircuitId, CoinPublicKey, EncPublicKey, PrivateStateId};

// =====================================================================
// Public configuration
// =====================================================================

/// Options for [`with_contract_scoped_transaction`]. Port of TS
/// `ScopedTransactionOptions`.
#[derive(Debug, Clone, Default)]
pub struct ScopedTransactionOptions {
    /// Optional human-readable name for the transaction scope. Used
    /// in error messages when the closure or submission fails so the
    /// failure can be attributed to the right scope. Falls back to
    /// `<unnamed>` when absent.
    pub scope_name: Option<String>,
    /// Optional caller-supplied additional `CoinPublicKey →
    /// EncPublicKey` mappings. Threaded into the resolver used by
    /// downstream call-tx builders so the scope can address coin
    /// recipients the wallet doesn't know about.
    pub additional_coin_enc_public_key_mappings: Option<HashMap<CoinPublicKey, EncPublicKey>>,
}

/// Cache key for in-scope contract states. Port of TS
/// `CachedStateIdentity`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CachedStateIdentity {
    pub contract_address: moonproof_ledger::coin_structure::contract::ContractAddress,
    pub private_state_id: Option<PrivateStateId>,
}

/// Cached states pinned to one [`CachedStateIdentity`]. Port of the
/// union TS `ContractStates<PS> | PublicContractStates`.
///
/// Generic on the private-state payload — `PS = ()` for stateless
/// contracts (in which case `private_state` is `Some(())`); `PS =
/// MyState` for stateful contracts that need to thread typed state.
/// `private_state` is `Option<RuntimeValue>` to capture the
/// distinction between "public-only states" (no private state) and
/// "full states" (private state included).
#[derive(Debug, Clone)]
pub struct CachedStates {
    pub contract_state: moonproof_ledger::onchain_runtime::state::ContractState<
        moonproof_ledger::storage::db::InMemoryDB,
    >,
    pub zswap_chain_state_bytes: Vec<u8>,
    pub ledger_parameters_bytes: Vec<u8>,
    pub private_state: Option<moonproof_runtime_ir::RuntimeValue>,
}

// =====================================================================
// TransactionContextImpl
// =====================================================================

/// Cached call-tx slot inside a scope: the most-recent merged call
/// plus its optional private-state id.
type LastUnsubmittedCallSlot = Option<(UnsubmittedCallTxData, Option<PrivateStateId>)>;

/// The states a scope caches, with the identity they were read for and
/// the block they were read at.
struct CachedEntry {
    identity: CachedStateIdentity,
    states: CachedStates,
    block_hash: Option<BlockHash>,
}

/// What submitting a scope needs from its calls beyond their
/// transactions. Passed with each merged call; the last call's wins.
#[derive(Default)]
pub struct DeferredSubmission {
    /// Balances the merged transaction's fee once. A call made in a
    /// scope is built without balancing: each call balancing its own
    /// transaction would spend the same dust twice.
    pub fee_balancing: Option<FeeBalancingConfig>,
    /// Network the fee-balancing intent is built for.
    pub network_id: String,
    /// Serializes the last call's next private state for the
    /// private-state provider, as the unscoped path does.
    pub serialize_next_private_state: Option<PrivateStateSerializer>,
}

/// In-scope state for a single
/// [`with_contract_scoped_transaction`] invocation.
///
/// All mutable state is behind a `Mutex` so callbacks can call methods
/// through a shared `&Self` reference, matching the TS pattern of
/// passing `txCtx` to closures that update it.
pub struct TransactionContextImpl {
    providers: Arc<ErasedProviders>,
    options: ScopedTransactionOptions,
    cached_states: Mutex<Option<CachedEntry>>,
    current_unsubmitted_call: Mutex<LastUnsubmittedCallSlot>,
    deferred: Mutex<DeferredSubmission>,
    /// Each merged call's typed unproven transaction is pushed onto
    /// this queue. On submit, they are merged via
    /// `Transaction::merge` and the result is fed into [`submit_tx`].
    accumulated_unproven_txs: Mutex<Vec<crate::tx_phase::UnprovenTx>>,
    /// Circuit ids of every merged call — preserved in order. Empty
    /// for an unused scope.
    accumulated_circuit_ids: Mutex<Vec<CircuitId>>,
}

impl TransactionContextImpl {
    /// Construct a new transaction context bound to `providers`.
    /// Port of TS `new TransactionContextImpl(providers, options?)`.
    #[must_use]
    pub fn new(providers: Arc<ErasedProviders>, options: ScopedTransactionOptions) -> Self {
        Self {
            providers,
            options,
            cached_states: Mutex::new(None),
            current_unsubmitted_call: Mutex::new(None),
            deferred: Mutex::new(DeferredSubmission::default()),
            accumulated_unproven_txs: Mutex::new(Vec::new()),
            accumulated_circuit_ids: Mutex::new(Vec::new()),
        }
    }

    /// Returns the providers bundle this scope is bound to.
    #[inline]
    #[must_use]
    pub fn providers(&self) -> &Arc<ErasedProviders> {
        &self.providers
    }

    /// Returns the scope's optional `additional_coin_enc_public_key_mappings`.
    /// Port of TS `getAdditionalMappings()`.
    #[must_use]
    pub fn get_additional_mappings(&self) -> Option<&HashMap<CoinPublicKey, EncPublicKey>> {
        self.options
            .additional_coin_enc_public_key_mappings
            .as_ref()
    }

    /// Cache the contract / private states under `identity` for the
    /// rest of the scope. Port of TS `[CacheStates]`. Overwrites any
    /// previously cached states.
    pub fn cache_states(&self, states: CachedStates, identity: CachedStateIdentity) {
        self.cache_states_at(states, identity, None);
    }

    /// Like [`Self::cache_states`], recording the block the states were
    /// read at: later calls in the scope read their callees at the same
    /// block, so the whole scope sees one chain snapshot.
    pub fn cache_states_at(
        &self,
        states: CachedStates,
        identity: CachedStateIdentity,
        block_hash: Option<BlockHash>,
    ) {
        *self.cached_states.lock().unwrap() = Some(CachedEntry {
            identity,
            states,
            block_hash,
        });
    }

    /// The block the cached states were read at, when it was recorded.
    #[must_use]
    pub fn cached_block_hash(&self) -> Option<BlockHash> {
        self.cached_states
            .lock()
            .unwrap()
            .as_ref()
            .and_then(|entry| entry.block_hash.clone())
    }

    /// Look up the cached states **only if** `identity` matches the
    /// identity originally cached. Returns `None` if nothing is
    /// cached; raises [`ContractsError::ScopedTransactionIdentityMismatch`]
    /// when a mismatched identity is supplied. Port of TS
    /// `[GetCurrentStatesForIdentity](identity)`.
    pub fn get_current_states_for_identity(
        &self,
        identity: &CachedStateIdentity,
    ) -> Result<Option<CachedStates>> {
        let guard = self.cached_states.lock().unwrap();
        let Some(CachedEntry {
            identity: cached_identity,
            states,
            ..
        }) = guard.as_ref()
        else {
            return Ok(None);
        };
        if cached_identity != identity {
            return Err(ContractRuntimeError::Contracts(
                ContractsError::ScopedTransactionIdentityMismatch {
                    cached: ScopedTxIdentity {
                        contract_address: moonproof_runtime::state::contract_address_to_hex(
                            &cached_identity.contract_address,
                        ),
                        private_state_id: cached_identity.private_state_id.clone(),
                    },
                    requested: ScopedTxIdentity {
                        contract_address: moonproof_runtime::state::contract_address_to_hex(
                            &identity.contract_address,
                        ),
                        private_state_id: identity.private_state_id.clone(),
                    },
                },
            ));
        }
        Ok(Some(states.clone()))
    }

    /// Bypass-identity accessor — returns whatever's cached. Port of
    /// TS `getCurrentStates()`. Marked deprecated in TS because it
    /// can return states from a different contract; preserved here
    /// for parity. Prefer [`Self::get_current_states_for_identity`].
    pub fn get_current_states(&self) -> Option<CachedStates> {
        self.cached_states
            .lock()
            .unwrap()
            .as_ref()
            .map(|entry| entry.states.clone())
    }

    /// Returns the most-recent unsubmitted call's data + optional
    /// private-state id. Port of TS
    /// `getLastUnsubmittedCallTxDataToTransact()`.
    pub fn get_last_unsubmitted_call_tx_data_to_transact(
        &self,
    ) -> Option<(UnsubmittedCallTxData, Option<PrivateStateId>)> {
        self.current_unsubmitted_call.lock().unwrap().clone()
    }

    /// Merge a circuit-call's unsubmitted-tx data into the running
    /// scope. Port of TS `[MergeUnsubmittedCallTxData]`.
    ///
    /// 1. Records `(call_data, private_state_id)` as the latest
    ///    unsubmitted call.
    /// 2. Appends the call's unproven tx bytes onto the accumulator
    ///    queue (deferred merging — see module-level docs).
    /// 3. Appends `circuit_id` onto the circuit-id list.
    /// 4. If states are cached, advances them by the call: the
    ///    contract's data becomes the call's next contract state and
    ///    the private-state slot its `next_private_state`, so the next
    ///    call in the scope runs against them. The zswap chain state,
    ///    the ledger parameters and the pinned block stay as read.
    pub fn merge_unsubmitted_call_tx_data(
        &self,
        circuit_id: CircuitId,
        call_data: UnsubmittedCallTxData,
        private_state_id: Option<PrivateStateId>,
    ) {
        if let Some(entry) = self.cached_states.lock().unwrap().as_mut() {
            entry.states.contract_state.data =
                call_data.result.public.next_contract_state.data.clone();
            entry.states.private_state = Some(call_data.result.private.next_private_state.clone());
        }

        self.accumulated_unproven_txs
            .lock()
            .unwrap()
            .push(call_data.tx.unproven_tx.clone());
        self.accumulated_circuit_ids
            .lock()
            .unwrap()
            .push(circuit_id);
        *self.current_unsubmitted_call.lock().unwrap() = Some((call_data, private_state_id));
    }

    /// Record what submitting the scope needs from the call just
    /// merged: its fee-balancing inputs and private-state serializer.
    pub fn defer_submission(&self, deferred: DeferredSubmission) {
        *self.deferred.lock().unwrap() = deferred;
    }

    /// Submit the accumulated calls as a single transaction. Port of
    /// TS `[Submit]()`.
    ///
    /// # Errors
    ///
    /// - Returns a clear `Provider` error when no calls have been
    ///   merged into the scope (the TS variant throws `Error('No
    ///   calls were submitted.')`).
    /// - Propagates any error from
    ///   [`crate::submit_tx::submit_tx`].
    /// - On non-`SucceedEntirely`, raises
    ///   [`ContractsError::CallTxFailed`] carrying every merged
    ///   circuit id (matches TS's `new CallTxFailedError(...,
    ///   submitTxOptions.circuitId!)`).
    pub async fn submit(&self) -> Result<FinalizedCallTxData> {
        let (last_call, last_psi) = self
            .current_unsubmitted_call
            .lock()
            .unwrap()
            .clone()
            .ok_or(ContractRuntimeError::Provider {
                provider: "scoped_transaction",
                message: "No calls were submitted.".to_owned(),
            })?;

        let chunks = self.accumulated_unproven_txs.lock().unwrap().clone();
        let circuit_ids = self.accumulated_circuit_ids.lock().unwrap().clone();
        let merged = merge_unproven_tx_chunks(chunks)?;
        let DeferredSubmission {
            fee_balancing,
            network_id,
            serialize_next_private_state,
        } = std::mem::take(&mut *self.deferred.lock().unwrap());
        let merged = match fee_balancing {
            Some(config) => crate::tx_phase::UnprovenTx::new(apply_fee_balancing(
                &mut rand::thread_rng(),
                merged.into_inner(),
                &config,
                &network_id,
            )?),
            None => merged,
        };

        let submit_opts = SubmitTxOptions {
            unproven_tx: merged,
            circuit_ids: Some(circuit_ids.clone()),
            prove_config: crate::providers::ProveTxConfig::default(),
            ttl_ms: None,
        };
        let finalized = submit_tx(&self.providers, submit_opts).await?;
        if !finalized.status.is_success() {
            return Err(ContractRuntimeError::Contracts(
                ContractsError::call_tx_failed(finalized, circuit_ids),
            ));
        }

        // On success, persist the last call's next private state — as
        // the unscoped path does, only when the call named an id and
        // supplied a serializer.
        if let (Some(psi), Some(serialize)) =
            (last_psi.as_ref(), serialize_next_private_state.as_ref())
        {
            let bytes = serialize(&last_call.result.private.next_private_state)?;
            self.providers.private_state.set(psi, bytes).await?;
        }

        Ok(FinalizedCallTxData {
            result: last_call.result,
            tx: last_call.tx,
            finalized,
        })
    }

    /// Returns the accumulated `Vec<FinalizedTxData>` slot — empty
    /// until `submit()` runs. Used by tests; equivalent to the TS
    /// `submitTxOptions` accumulator visibility.
    #[must_use]
    pub fn accumulated_circuit_ids(&self) -> Vec<CircuitId> {
        self.accumulated_circuit_ids.lock().unwrap().clone()
    }

    /// Returns the number of merged calls — a proxy for whether the
    /// scope has been used.
    #[must_use]
    pub fn merged_call_count(&self) -> usize {
        self.accumulated_circuit_ids.lock().unwrap().len()
    }
}

// =====================================================================
// Free functions
// =====================================================================

/// Run `fn` inside a fresh
/// [`TransactionContextImpl`]. Port of TS
/// `withContractScopedTransaction`.
///
/// On a successful exit of `fn`, the scope's accumulated calls are
/// submitted as a single transaction via
/// [`TransactionContextImpl::submit`]. On a failed exit, nothing is
/// submitted and the closure's error is wrapped with the scope name
/// so callers can attribute the failure.
///
/// # Errors
///
/// - Wraps any error raised by `fn` with the scope name: the
///   message is `"Unexpected error executing scoped transaction
///   '<scope_name>': <inner error>"`. Falls back to `<unnamed>` if
///   no scope name was provided.
/// - Wraps any error raised during submission with a similar prefix
///   — exception: a [`ContractsError::CallTxFailed`] propagates
///   verbatim because callers typically want to pattern-match on it
///   rather than the wrapped variant.
pub async fn with_contract_scoped_transaction<F, Fut>(
    providers: Arc<ErasedProviders>,
    f: F,
    options: ScopedTransactionOptions,
) -> Result<FinalizedCallTxData>
where
    F: FnOnce(Arc<TransactionContextImpl>) -> Fut,
    Fut: Future<Output = Result<()>>,
{
    let scope_name = options.scope_name.clone();
    let ctx = Arc::new(TransactionContextImpl::new(providers, options));

    if let Err(err) = f(ctx.clone()).await {
        return Err(wrap_with_scope_name(
            &err,
            scope_name.as_deref(),
            "executing",
        ));
    }

    match ctx.submit().await {
        Ok(data) => Ok(data),
        Err(err) => match err {
            // Preserve CallTxFailedError verbatim — callers
            // pattern-match on it for retry / refund logic.
            ContractRuntimeError::Contracts(ContractsError::CallTxFailed { .. }) => Err(err),
            other => Err(wrap_with_scope_name(
                &other,
                scope_name.as_deref(),
                "submitting",
            )),
        },
    }
}

/// Convenience: wrap an error with `<unnamed>` or the supplied
/// scope name, mirroring the TS `Unexpected error <action> scoped
/// transaction '...': ...` format.
fn wrap_with_scope_name(
    err: &ContractRuntimeError,
    scope_name: Option<&str>,
    action: &str,
) -> ContractRuntimeError {
    let name = scope_name.unwrap_or("<unnamed>");
    let inner = err.to_string();
    ContractRuntimeError::Provider {
        provider: "scoped_transaction",
        message: format!("Unexpected error {action} scoped transaction '{name}': {inner}"),
    }
}

/// Merge a sequence of tagged-serialized unproven-tx byte chunks
/// into one, via `Transaction::merge`. Returns the first chunk
/// verbatim if there's only one; errors if `chunks` is empty or if
/// any chunk fails to deserialize.
fn merge_unproven_tx_chunks(
    chunks: Vec<crate::tx_phase::UnprovenTx>,
) -> Result<crate::tx_phase::UnprovenTx> {
    if chunks.is_empty() {
        return Err(ContractRuntimeError::Provider {
            provider: "scoped_transaction",
            message: "merge: no unproven tx chunks to merge".to_owned(),
        });
    }
    let mut iter = chunks.into_iter();
    let first = iter.next().expect("non-empty checked above");
    if iter.len() == 0 {
        return Ok(first);
    }
    let mut merged = first.into_inner();
    for next in iter {
        merged = merged
            .merge(&next.into_inner())
            .map_err(|e| ContractRuntimeError::Provider {
                provider: "scoped_transaction",
                message: format!("Transaction::merge failed: {e}"),
            })?;
    }
    Ok(crate::tx_phase::UnprovenTx::new(merged))
}

#[cfg(test)]
mod tests {
    //! Ports of `scoped-transaction.test.ts` and
    //! `transaction-identity.test.ts`.

    use super::*;
    use crate::test_helpers::{counter_ir_executable, dummy_address, scripted_providers};
    use crate::tx_model::UnsubmittedTxData;
    use crate::types::{
        CallResult, CallResultPrivate, CallResultPublic, CircuitId, PrivateStateId, TxStatus,
    };
    use moonproof_ledger::base_crypto::fab::AlignedValue;
    use moonproof_ledger::onchain_runtime::state::ContractState;
    use moonproof_ledger::storage::db::InMemoryDB;
    use moonproof_runtime_ir::RuntimeValue;

    fn dummy_address_with_nonce(
        nonce: u8,
    ) -> moonproof_ledger::coin_structure::contract::ContractAddress {
        moonproof_ledger::coin_structure::contract::ContractAddress(
            moonproof_ledger::base_crypto::hash::HashOutput([nonce; 32]),
        )
    }

    async fn fresh_contract_state() -> ContractState<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(&[0x21u8; 32]).unwrap(),
            time: None,
        };
        executable
            .initialize(ctor, moonproof_runtime_ir::RuntimeValue::Null)
            .await
            .unwrap()
            .initial_contract_state
    }

    fn fixture_states(state: ContractState<InMemoryDB>) -> CachedStates {
        CachedStates {
            contract_state: state,
            zswap_chain_state_bytes: vec![0xAA, 0xBB],
            ledger_parameters_bytes: vec![0xCC, 0xDD],
            private_state: Some(RuntimeValue::Int(0)),
        }
    }

    fn fixture_call_data(next_private_state: u64) -> UnsubmittedCallTxData {
        UnsubmittedCallTxData {
            result: CallResult {
                public: CallResultPublic {
                    next_contract_state: ContractState::<InMemoryDB>::new(
                        moonproof_ledger::onchain_runtime::state::StateValue::Null,
                        moonproof_ledger::storage::storage::HashMap::new(),
                        moonproof_ledger::onchain_runtime::state::ContractMaintenanceAuthority::default(),
                    ),
                    public_transcript: Vec::new(),
                    partitioned_transcript: (None, None),
                    events: Vec::new(),
                },
                private: CallResultPrivate {
                    input: AlignedValue::concat(std::iter::empty::<&AlignedValue>()),
                    output: AlignedValue::concat(std::iter::empty::<&AlignedValue>()),
                    private_transcript_outputs: Vec::new(),
                    result: RuntimeValue::Null,
                    next_private_state: RuntimeValue::Int(i128::from(next_private_state)),
                    next_zswap_local_state:
                        crate::utils::zswap_utils::CompactZswapLocalState::empty(
                            crate::types::CoinPublicKey([0u8; 32]),
                        ),
                },
                callees: Vec::new(),
            },
            tx: UnsubmittedTxData {
                unproven_tx: empty_unproven_tx(),
                new_coins: Vec::new(),
            },
        }
    }

    /// Empty pre-prove transaction — convenience for the tests that
    /// don't care about tx contents, only about the wiring of the
    /// scoped-transaction context around them.
    fn empty_unproven_tx() -> crate::tx_phase::UnprovenTx {
        use moonproof_ledger::ledger::structure::Transaction;
        let tx: Transaction<
            moonproof_ledger::signatures::Signature,
            moonproof_ledger::ledger::structure::ProofPreimageMarker,
            moonproof_ledger::transient_crypto::commitment::PedersenRandomness,
            moonproof_ledger::storage::db::InMemoryDB,
        > = Transaction::from_intents(
            "local-test",
            moonproof_ledger::storage::storage::HashMap::new(),
        );
        crate::tx_phase::UnprovenTx::new(tx)
    }

    fn make_ctx() -> Arc<TransactionContextImpl> {
        let (providers, _) = scripted_providers(None, None, TxStatus::SucceedEntirely);
        Arc::new(TransactionContextImpl::new(
            Arc::new(providers),
            ScopedTransactionOptions::default(),
        ))
    }

    /// ports: `scoped-transaction.test.ts::should include scopeName in execution error message`
    #[tokio::test]
    async fn fn_error_is_wrapped_with_scope_name() {
        let (providers, _) = scripted_providers(None, None, TxStatus::SucceedEntirely);
        let result: Result<FinalizedCallTxData> = with_contract_scoped_transaction(
            Arc::new(providers),
            |_ctx| async {
                Err(ContractRuntimeError::Provider {
                    provider: "test",
                    message: "circuit failed".to_owned(),
                })
            },
            ScopedTransactionOptions {
                scope_name: Some("myTransfer".to_owned()),
                additional_coin_enc_public_key_mappings: None,
            },
        )
        .await;
        let err = result.expect_err("scoped transaction with throwing fn should error");
        let msg = format!("{err}");
        assert!(msg.contains("myTransfer"), "{msg}");
        assert!(msg.contains("circuit failed"), "{msg}");
    }

    /// ports: `scoped-transaction.test.ts::should show <unnamed> when no scopeName`
    #[tokio::test]
    async fn fn_error_falls_back_to_unnamed_when_scope_name_absent() {
        let (providers, _) = scripted_providers(None, None, TxStatus::SucceedEntirely);
        let result: Result<FinalizedCallTxData> = with_contract_scoped_transaction(
            Arc::new(providers),
            |_ctx| async {
                Err(ContractRuntimeError::Provider {
                    provider: "test",
                    message: "circuit failed".to_owned(),
                })
            },
            ScopedTransactionOptions::default(),
        )
        .await;
        let err = result.expect_err("scoped transaction with throwing fn should error");
        let msg = format!("{err}");
        assert!(msg.contains("<unnamed>"), "{msg}");
    }

    #[tokio::test]
    async fn get_current_states_for_identity_returns_none_when_unset() {
        let ctx = make_ctx();
        let id = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        assert!(ctx.get_current_states_for_identity(&id).unwrap().is_none());
    }

    #[tokio::test]
    async fn get_current_states_for_identity_returns_cached_when_identity_matches() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let id = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        ctx.cache_states(fixture_states(state), id.clone());
        let got = ctx.get_current_states_for_identity(&id).unwrap();
        assert!(got.is_some());
        assert_eq!(
            got.unwrap().private_state.as_ref().unwrap().as_u64(),
            Some(0u64)
        );
    }

    #[tokio::test]
    async fn get_current_states_for_identity_throws_on_address_mismatch() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let id1 = CachedStateIdentity {
            contract_address: dummy_address_with_nonce(0xA1),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        let id2 = CachedStateIdentity {
            contract_address: dummy_address_with_nonce(0xB2),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        ctx.cache_states(fixture_states(state), id1);
        let err = ctx.get_current_states_for_identity(&id2).unwrap_err();
        matches!(
            err,
            ContractRuntimeError::Contracts(
                ContractsError::ScopedTransactionIdentityMismatch { .. }
            )
        );
    }

    #[tokio::test]
    async fn get_current_states_for_identity_throws_on_private_state_id_mismatch() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let id1 = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: Some(PrivateStateId::new("a")),
        };
        let id2 = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: Some(PrivateStateId::new("b")),
        };
        ctx.cache_states(fixture_states(state), id1);
        let err = ctx.get_current_states_for_identity(&id2).unwrap_err();
        matches!(
            err,
            ContractRuntimeError::Contracts(
                ContractsError::ScopedTransactionIdentityMismatch { .. }
            )
        );
    }

    #[tokio::test]
    async fn get_current_states_for_identity_throws_when_only_one_has_private_state_id() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let with_psi = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        let without_psi = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: None,
        };
        ctx.cache_states(fixture_states(state), with_psi);
        let err = ctx
            .get_current_states_for_identity(&without_psi)
            .unwrap_err();
        matches!(
            err,
            ContractRuntimeError::Contracts(
                ContractsError::ScopedTransactionIdentityMismatch { .. }
            )
        );
    }

    #[tokio::test]
    async fn identity_mismatch_error_carries_both_sides() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let cached = CachedStateIdentity {
            contract_address: dummy_address_with_nonce(0xA1),
            private_state_id: Some(PrivateStateId::new("ps-id-1")),
        };
        let requested = CachedStateIdentity {
            contract_address: dummy_address_with_nonce(0xB2),
            private_state_id: Some(PrivateStateId::new("ps-id-2")),
        };
        ctx.cache_states(fixture_states(state), cached.clone());
        let err = ctx.get_current_states_for_identity(&requested).unwrap_err();
        match err {
            ContractRuntimeError::Contracts(
                ContractsError::ScopedTransactionIdentityMismatch {
                    cached: c,
                    requested: r,
                },
            ) => {
                assert_eq!(
                    c.contract_address,
                    moonproof_runtime::state::contract_address_to_hex(&cached.contract_address)
                );
                assert_eq!(c.private_state_id.as_ref().unwrap().as_str(), "ps-id-1");
                assert_eq!(
                    r.contract_address,
                    moonproof_runtime::state::contract_address_to_hex(&requested.contract_address)
                );
                assert_eq!(r.private_state_id.as_ref().unwrap().as_str(), "ps-id-2");
            }
            other => panic!("unexpected error variant: {other:?}"),
        }
    }

    #[tokio::test]
    async fn get_current_states_for_identity_allows_repeated_lookups() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let id = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        ctx.cache_states(fixture_states(state), id.clone());
        let r1 = ctx.get_current_states_for_identity(&id).unwrap();
        let r2 = ctx.get_current_states_for_identity(&id).unwrap();
        assert!(r1.is_some());
        assert!(r2.is_some());
    }

    #[tokio::test]
    async fn get_current_states_for_identity_works_for_public_only() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let id = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: None,
        };
        let mut states = fixture_states(state);
        states.private_state = None;
        ctx.cache_states(states, id.clone());
        let got = ctx.get_current_states_for_identity(&id).unwrap();
        assert!(got.is_some());
        assert!(got.unwrap().private_state.is_none());
    }

    #[tokio::test]
    async fn get_current_states_for_identity_throws_when_requested_psi_but_cached_without() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let cached = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: None,
        };
        let requested = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: Some(PrivateStateId::new("some-id")),
        };
        let mut states = fixture_states(state);
        states.private_state = None;
        ctx.cache_states(states, cached);
        let err = ctx.get_current_states_for_identity(&requested).unwrap_err();
        matches!(
            err,
            ContractRuntimeError::Contracts(
                ContractsError::ScopedTransactionIdentityMismatch { .. }
            )
        );
    }

    #[tokio::test]
    async fn get_current_states_returns_none_when_unset() {
        let ctx = make_ctx();
        assert!(ctx.get_current_states().is_none());
    }

    #[tokio::test]
    async fn get_current_states_returns_cached_without_identity_check() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let id = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        ctx.cache_states(fixture_states(state), id);
        let got = ctx.get_current_states();
        assert!(got.is_some());
        assert_eq!(
            got.unwrap().private_state.as_ref().unwrap().as_u64(),
            Some(0u64)
        );
    }

    #[tokio::test]
    async fn merge_preserves_original_identity() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let id = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        ctx.cache_states(fixture_states(state), id.clone());
        ctx.merge_unsubmitted_call_tx_data(
            CircuitId::new("testCircuit"),
            fixture_call_data(42),
            Some(PrivateStateId::new("test")),
        );
        let got = ctx.get_current_states_for_identity(&id).unwrap().unwrap();
        assert_eq!(got.private_state.as_ref().unwrap().as_u64(), Some(42u64));
    }

    #[tokio::test]
    async fn multiple_merges_keep_identity_lookup_consistent() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let id = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        ctx.cache_states(fixture_states(state), id.clone());
        ctx.merge_unsubmitted_call_tx_data(
            CircuitId::new("testCircuit"),
            fixture_call_data(1),
            Some(PrivateStateId::new("test")),
        );
        ctx.merge_unsubmitted_call_tx_data(
            CircuitId::new("testCircuit"),
            fixture_call_data(2),
            Some(PrivateStateId::new("test")),
        );
        let got = ctx.get_current_states_for_identity(&id).unwrap().unwrap();
        assert_eq!(got.private_state.as_ref().unwrap().as_u64(), Some(2u64));
    }

    #[tokio::test]
    async fn merge_preserves_original_ledger_parameters() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let mut original = fixture_states(state);
        original.ledger_parameters_bytes = vec![0xDE, 0xAD, 0xBE, 0xEF];
        let id = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        ctx.cache_states(original.clone(), id.clone());
        ctx.merge_unsubmitted_call_tx_data(
            CircuitId::new("testCircuit"),
            fixture_call_data(7),
            Some(PrivateStateId::new("test")),
        );
        let got = ctx.get_current_states_for_identity(&id).unwrap().unwrap();
        assert_eq!(got.ledger_parameters_bytes, vec![0xDE, 0xAD, 0xBE, 0xEF]);
    }

    #[tokio::test]
    async fn multiple_merges_preserve_original_ledger_parameters() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let mut original = fixture_states(state);
        original.ledger_parameters_bytes = vec![0xDE, 0xAD];
        let id = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        ctx.cache_states(original, id.clone());
        for v in 1..=3 {
            ctx.merge_unsubmitted_call_tx_data(
                CircuitId::new("testCircuit"),
                fixture_call_data(v),
                Some(PrivateStateId::new("test")),
            );
        }
        let got = ctx.get_current_states_for_identity(&id).unwrap().unwrap();
        assert_eq!(got.ledger_parameters_bytes, vec![0xDE, 0xAD]);
    }

    #[tokio::test]
    async fn merge_preserves_original_zswap_chain_state() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let mut original = fixture_states(state);
        original.zswap_chain_state_bytes = vec![0xCA, 0xFE];
        let id = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        ctx.cache_states(original, id.clone());
        ctx.merge_unsubmitted_call_tx_data(
            CircuitId::new("testCircuit"),
            fixture_call_data(7),
            Some(PrivateStateId::new("test")),
        );
        let got = ctx.get_current_states_for_identity(&id).unwrap().unwrap();
        assert_eq!(got.zswap_chain_state_bytes, vec![0xCA, 0xFE]);
    }

    #[tokio::test]
    async fn multiple_merges_preserve_original_zswap_chain_state() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let mut original = fixture_states(state);
        original.zswap_chain_state_bytes = vec![0xCA, 0xFE];
        let id = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        ctx.cache_states(original, id.clone());
        for v in 1..=3 {
            ctx.merge_unsubmitted_call_tx_data(
                CircuitId::new("testCircuit"),
                fixture_call_data(v),
                Some(PrivateStateId::new("test")),
            );
        }
        let got = ctx.get_current_states_for_identity(&id).unwrap().unwrap();
        assert_eq!(got.zswap_chain_state_bytes, vec![0xCA, 0xFE]);
    }

    #[tokio::test]
    async fn merge_then_query_with_different_identity_throws() {
        let ctx = make_ctx();
        let state = fresh_contract_state().await;
        let cached = CachedStateIdentity {
            contract_address: dummy_address_with_nonce(0xA1),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        let other = CachedStateIdentity {
            contract_address: dummy_address_with_nonce(0xB2),
            private_state_id: Some(PrivateStateId::new("test")),
        };
        ctx.cache_states(fixture_states(state), cached);
        ctx.merge_unsubmitted_call_tx_data(
            CircuitId::new("testCircuit"),
            fixture_call_data(7),
            Some(PrivateStateId::new("test")),
        );
        let err = ctx.get_current_states_for_identity(&other).unwrap_err();
        matches!(
            err,
            ContractRuntimeError::Contracts(
                ContractsError::ScopedTransactionIdentityMismatch { .. }
            )
        );
    }

    #[tokio::test]
    async fn submit_with_no_merged_calls_returns_no_calls_error() {
        let ctx = make_ctx();
        let err = ctx.submit().await.unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("No calls were submitted"), "{msg}");
    }

    /// Two calls in one scope build one valid transaction: the second
    /// runs against the state the first left, and their transactions,
    /// each with its intent at a segment of its own, merge.
    #[tokio::test]
    async fn two_scoped_calls_chain_their_states_and_merge() {
        use crate::providers::public_data::ZSwapAndContractState;
        use crate::submit_call_tx::submit_call_tx;
        use crate::test_helpers::scripted_providers_with_real_prover;
        use crate::unproven_call_tx::BuildCallOptions;
        use rand::SeedableRng;

        let state = fresh_contract_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 providers = Arc::new(providers);
        let ctx = Arc::new(TransactionContextImpl::new(
            providers.clone(),
            ScopedTransactionOptions::default(),
        ));
        let executable = counter_ir_executable().await;
        let mut rng = rand::rngs::StdRng::seed_from_u64(0x5C0);
        let options = || BuildCallOptions {
            contract_address: dummy_address(),
            circuit_id: CircuitId::new("increment"),
            initial_private_state: Some(RuntimeValue::Null),
            network_id: "local-test".into(),
            ..BuildCallOptions::default()
        };
        let first = Box::pin(submit_call_tx(
            &mut rng,
            &executable,
            &providers,
            options(),
            Some(&ctx),
        ))
        .await
        .unwrap();
        let second = Box::pin(submit_call_tx(
            &mut rng,
            &executable,
            &providers,
            options(),
            Some(&ctx),
        ))
        .await
        .unwrap();

        assert_ne!(
            first.unsubmitted.result.public.next_contract_state.data,
            second.unsubmitted.result.public.next_contract_state.data,
            "the second increment ran against the first's state"
        );
        let id = CachedStateIdentity {
            contract_address: dummy_address(),
            private_state_id: None,
        };
        assert_eq!(
            ctx.get_current_states_for_identity(&id)
                .unwrap()
                .unwrap()
                .contract_state
                .data,
            second.unsubmitted.result.public.next_contract_state.data
        );

        let chunks = ctx.accumulated_unproven_txs.lock().unwrap().clone();
        let merged = merge_unproven_tx_chunks(chunks).expect("the calls merge");
        match merged.as_inner() {
            moonproof_ledger::ledger::structure::Transaction::Standard(stx) => {
                assert_eq!(stx.intents.size(), 2);
            }
            other @ moonproof_ledger::ledger::structure::Transaction::ClaimRewards(_) => {
                panic!("expected a standard transaction, got {other:?}")
            }
        }
    }

    /// A call for another contract in a scope already holding one's
    /// states is refused, as midnight-js refuses it.
    #[tokio::test]
    async fn a_scoped_call_for_another_contract_is_refused() {
        use crate::providers::public_data::ZSwapAndContractState;
        use crate::submit_call_tx::submit_call_tx;
        use crate::test_helpers::scripted_providers_with_real_prover;
        use crate::unproven_call_tx::BuildCallOptions;
        use rand::SeedableRng;

        let state = fresh_contract_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 providers = Arc::new(providers);
        let ctx = Arc::new(TransactionContextImpl::new(
            providers.clone(),
            ScopedTransactionOptions::default(),
        ));
        let executable = counter_ir_executable().await;
        let mut rng = rand::rngs::StdRng::seed_from_u64(0x5C1);
        let options = |address| BuildCallOptions {
            contract_address: address,
            circuit_id: CircuitId::new("increment"),
            initial_private_state: Some(RuntimeValue::Null),
            network_id: "local-test".into(),
            ..BuildCallOptions::default()
        };
        Box::pin(submit_call_tx(
            &mut rng,
            &executable,
            &providers,
            options(dummy_address()),
            Some(&ctx),
        ))
        .await
        .unwrap();
        let err = Box::pin(submit_call_tx(
            &mut rng,
            &executable,
            &providers,
            options(dummy_address_with_nonce(0xB2)),
            Some(&ctx),
        ))
        .await
        .unwrap_err();
        assert!(
            matches!(
                err,
                ContractRuntimeError::Contracts(
                    ContractsError::ScopedTransactionIdentityMismatch { .. }
                )
            ),
            "{err}"
        );
    }
}