miden-client-web 0.16.0

Web Client library that facilitates interaction with the Miden network
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
use alloc::collections::BTreeMap;

use js_export_macro::js_export;
use miden_client::account::{AccountComponentInterfaceExt, AccountId as NativeAccountId};
use miden_client::agglayer::B2AggNote;
use miden_client::asset::{AssetAmount, FungibleAsset};
use miden_client::crypto::FeltRng;
use miden_client::note::{
    BlockNumber,
    Note as NativeNote,
    NoteAssets as NativeNoteAssets,
    PswapNote,
};
#[cfg(feature = "testing")]
use miden_client::transaction::LocalTransactionProver;
use miden_client::transaction::{
    AccountComponentInterface,
    ChainAnchorError,
    ForeignAccount as NativeForeignAccount,
    PaymentNoteDescription,
    ProvenTransaction as NativeProvenTransaction,
    PswapTransactionData,
    SwapTransactionData,
    TransactionExecutorError,
    TransactionRequest as NativeTransactionRequest,
    TransactionRequestBuilder as NativeTransactionRequestBuilder,
};
use miden_client::{Client, ClientError, Word as NativeWord};

use crate::models::NoteType;
use crate::models::account_id::AccountId;
use crate::models::advice_inputs::AdviceInputs;
use crate::models::chain_anchor::ChainAnchor;
use crate::models::eth_address::EthAddress;
use crate::models::felt::Felt;
use crate::models::miden_arrays::{FeltArray, ForeignAccountArray};
use crate::models::note::Note;
use crate::models::proven_transaction::ProvenTransaction;
use crate::models::provers::TransactionProver;
use crate::models::transaction_id::TransactionId;
use crate::models::transaction_request::TransactionRequest;
use crate::models::transaction_request::transaction_request_builder::TransactionRequestBuilder;
use crate::models::transaction_result::TransactionResult;
use crate::models::transaction_script::TransactionScript;
use crate::models::transaction_store_update::TransactionStoreUpdate;
use crate::models::transaction_summary::TransactionSummary;
use crate::platform::{
    JsBytes,
    JsErr,
    from_str_err,
    from_str_err_with_code,
    js_u64_to_u64,
    maybe_wrap_send,
};
use crate::utils::deserialize_from_bytes;
use crate::{WebClient, js_error_with_context};

#[js_export]
impl WebClient {
    #[js_export(js_name = "newMintTransactionRequest")]
    pub async fn new_mint_transaction_request(
        &self,
        target_account_id: &AccountId,
        faucet_id: &AccountId,
        note_type: NoteType,
        amount: JsU64,
    ) -> Result<TransactionRequest, JsErr> {
        let amount = js_u64_to_u64(amount);
        let fungible_asset = FungibleAsset::new(faucet_id.into(), amount)
            .map_err(|err| js_error_with_context(err, "failed to create fungible asset"))?;

        let mint_transaction_request = {
            let mut guard = self.get_mut_inner().await;
            let client = guard.as_mut().ok_or_else(|| {
                from_str_err("Client not initialized while generating transaction request")
            })?;

            // The faucet executes a mint, so it is the account whose auth procedure reads the
            // conversion info.
            let builder = fee_aware_builder(client, faucet_id.into()).await?;
            builder
                .build_mint_fungible_asset(
                    fungible_asset,
                    target_account_id.into(),
                    note_type.into(),
                    client.rng(),
                )
                .map_err(|err| {
                    js_error_with_context(err, "failed to create mint transaction request")
                })?
        };

        Ok(mint_transaction_request.into())
    }

    #[js_export(js_name = "newSendTransactionRequest")]
    #[allow(clippy::too_many_arguments)]
    pub async fn new_send_transaction_request(
        &self,
        sender_account_id: &AccountId,
        target_account_id: &AccountId,
        faucet_id: &AccountId,
        note_type: NoteType,
        amount: JsU64,
        recall_height: Option<u32>,
        timelock_height: Option<u32>,
    ) -> Result<TransactionRequest, JsErr> {
        let mut guard = self.get_mut_inner().await;
        let client = guard.as_mut().ok_or_else(|| {
            from_str_err("Client not initialized while generating transaction request")
        })?;

        let amount = js_u64_to_u64(amount);
        let fungible_asset = FungibleAsset::new(faucet_id.into(), amount)
            .map_err(|err| js_error_with_context(err, "failed to create fungible asset"))?;

        let mut payment_description = PaymentNoteDescription::new(
            vec![fungible_asset.into()],
            sender_account_id.into(),
            target_account_id.into(),
        );

        if let Some(recall_height) = recall_height {
            payment_description =
                payment_description.with_reclaim_height(BlockNumber::from(recall_height));
        }

        if let Some(height) = timelock_height {
            payment_description =
                payment_description.with_timelock_height(BlockNumber::from(height));
        }

        let builder = fee_aware_builder(client, sender_account_id.into()).await?;
        let send_transaction_request = builder
            .build_pay_to_id(payment_description, note_type.into(), client.rng())
            .map_err(|err| {
                js_error_with_context(err, "failed to create send transaction request")
            })?;

        Ok(send_transaction_request.into())
    }

    /// Builds a transaction request that bridges a fungible asset out to another network via the
    /// `AggLayer`.
    ///
    /// The request emits a single public B2AGG (Bridge-to-AggLayer) note holding `amount` units of
    /// the `faucet_id` asset. The note is consumed by `bridge_account_id`, which burns the asset so
    /// it can be claimed at `destination_address` (an Ethereum address) on the AggLayer-assigned
    /// `destination_network`.
    #[js_export(js_name = "newB2AggTransactionRequest")]
    #[allow(clippy::too_many_arguments)]
    pub async fn new_b2agg_transaction_request(
        &self,
        sender_account_id: &AccountId,
        bridge_account_id: &AccountId,
        faucet_id: &AccountId,
        amount: JsU64,
        destination_network: u32,
        destination_address: &EthAddress,
    ) -> Result<TransactionRequest, JsErr> {
        let mut guard = self.get_mut_inner().await;
        let client = guard.as_mut().ok_or_else(|| {
            from_str_err("Client not initialized while generating transaction request")
        })?;

        let amount = js_u64_to_u64(amount);
        let fungible_asset = FungibleAsset::new(faucet_id.into(), amount)
            .map_err(|err| js_error_with_context(err, "failed to create fungible asset"))?;
        let note_assets = NativeNoteAssets::new(vec![fungible_asset.into()])
            .map_err(|err| js_error_with_context(err, "failed to create b2agg note assets"))?;

        let b2agg_note = B2AggNote::create(
            destination_network,
            destination_address.into(),
            note_assets,
            bridge_account_id.into(),
            sender_account_id.into(),
            client.rng(),
        )
        .map_err(|err| js_error_with_context(err, "failed to create b2agg note"))?;

        let builder = fee_aware_builder(client, sender_account_id.into()).await?;
        let b2agg_transaction_request =
            builder.own_output_notes(vec![b2agg_note]).build().map_err(|err| {
                js_error_with_context(err, "failed to create b2agg transaction request")
            })?;

        Ok(b2agg_transaction_request.into())
    }

    #[js_export(js_name = "newSwapTransactionRequest")]
    #[allow(clippy::too_many_arguments)]
    pub async fn new_swap_transaction_request(
        &self,
        sender_account_id: &AccountId,
        offered_asset_faucet_id: &AccountId,
        offered_asset_amount: JsU64,
        requested_asset_faucet_id: &AccountId,
        requested_asset_amount: JsU64,
        note_type: NoteType,
        payback_note_type: NoteType,
    ) -> Result<TransactionRequest, JsErr> {
        let offered_asset_amount = js_u64_to_u64(offered_asset_amount);
        let offered_fungible_asset =
            FungibleAsset::new(offered_asset_faucet_id.into(), offered_asset_amount)
                .map_err(|err| {
                    js_error_with_context(err, "failed to create offered fungible asset")
                })?
                .into();

        let requested_asset_amount = js_u64_to_u64(requested_asset_amount);
        let requested_fungible_asset =
            FungibleAsset::new(requested_asset_faucet_id.into(), requested_asset_amount)
                .map_err(|err| {
                    js_error_with_context(err, "failed to create requested fungible asset")
                })?
                .into();

        let swap_transaction_data = SwapTransactionData::new(
            sender_account_id.into(),
            offered_fungible_asset,
            requested_fungible_asset,
        );

        let swap_transaction_request = {
            let mut guard = self.get_mut_inner().await;
            let client = guard.as_mut().ok_or_else(|| {
                from_str_err("Client not initialized while generating transaction request")
            })?;

            let builder = fee_aware_builder(client, sender_account_id.into()).await?;
            builder
                .build_swap(
                    &swap_transaction_data,
                    note_type.into(),
                    payback_note_type.into(),
                    client.rng(),
                )
                .map_err(|err| {
                    js_error_with_context(err, "failed to create swap transaction request")
                })?
        };

        Ok(swap_transaction_request.into())
    }

    #[js_export(js_name = "newPswapCreateTransactionRequest")]
    #[allow(clippy::too_many_arguments)]
    pub async fn new_pswap_create_transaction_request(
        &self,
        creator_account_id: &AccountId,
        offered_asset_faucet_id: &AccountId,
        offered_asset_amount: JsU64,
        requested_asset_faucet_id: &AccountId,
        requested_asset_amount: JsU64,
        note_type: NoteType,
        payback_note_type: NoteType,
    ) -> Result<TransactionRequest, JsErr> {
        let offered_asset_amount = js_u64_to_u64(offered_asset_amount);
        let offered_fungible_asset =
            FungibleAsset::new(offered_asset_faucet_id.into(), offered_asset_amount).map_err(
                |err| js_error_with_context(err, "failed to create offered fungible asset"),
            )?;

        let requested_asset_amount = js_u64_to_u64(requested_asset_amount);
        let requested_fungible_asset =
            FungibleAsset::new(requested_asset_faucet_id.into(), requested_asset_amount).map_err(
                |err| js_error_with_context(err, "failed to create requested fungible asset"),
            )?;

        let pswap_transaction_data = PswapTransactionData::new(
            creator_account_id.into(),
            offered_fungible_asset,
            requested_fungible_asset,
        );

        let pswap_transaction_request = {
            let mut guard = self.get_mut_inner().await;
            let client = guard.as_mut().ok_or_else(|| {
                from_str_err("Client not initialized while generating transaction request")
            })?;

            let builder = fee_aware_builder(client, creator_account_id.into()).await?;
            builder
                .build_pswap_create(
                    &pswap_transaction_data,
                    note_type.into(),
                    payback_note_type.into(),
                    // V1 limitation: PSWAP notes always use no attachment — it
                    // is not yet exposed to JS callers. Follow-up: surface an
                    // optional `attachment` field on PswapCreateOptions in a
                    // non-breaking way. Until then, do not change this `None`
                    // without bumping existing PSWAP note compatibility.
                    //
                    // (`NoteAttachment::default()` no longer exists on the
                    // 0.15 surface — `Option::None` is the new way to say
                    // "no attachment".)
                    None,
                    client.rng(),
                )
                .map_err(|err| {
                    js_error_with_context(err, "failed to create PSWAP create transaction request")
                })?
        };

        Ok(pswap_transaction_request.into())
    }

    #[js_export(js_name = "newPswapConsumeTransactionRequest")]
    pub async fn new_pswap_consume_transaction_request(
        &self,
        pswap_note: &Note,
        consumer_account_id: &AccountId,
        account_fill_amount: JsU64,
        note_fill_amount: JsU64,
    ) -> Result<TransactionRequest, JsErr> {
        let native_pswap_note: NativeNote = pswap_note.into();
        let pswap = PswapNote::try_from(&native_pswap_note)
            .map_err(|err| js_error_with_context(err, "invalid PSWAP note"))?;

        let account_fill_amount = AssetAmount::new(js_u64_to_u64(account_fill_amount))
            .map_err(|err| js_error_with_context(err, "invalid account fill amount"))?;
        let note_fill_amount = AssetAmount::new(js_u64_to_u64(note_fill_amount))
            .map_err(|err| js_error_with_context(err, "invalid note fill amount"))?;

        // miden-client 0.16 treats an overfill as a full fill. Keep the web client's existing
        // contract, which rejects fills outside the open order amount, and validate the combined
        // account/note fill before handing it to the native request builder.
        let total_fill_amount = (account_fill_amount + note_fill_amount)
            .map_err(|err| js_error_with_context(err, "invalid total fill amount"))?;
        if total_fill_amount == AssetAmount::ZERO {
            return Err(from_str_err("Fill amount must be greater than 0"));
        }

        let requested_amount = pswap.storage().min_requested_asset().amount();
        if total_fill_amount > requested_amount {
            return Err(from_str_err(&format!(
                "Fill amount {total_fill_amount} exceeds requested amount {requested_amount}"
            )));
        }

        let pswap_transaction_request = {
            let mut guard = self.get_mut_inner().await;
            let client = guard.as_mut().ok_or_else(|| {
                from_str_err("Client not initialized while generating transaction request")
            })?;

            // The consumer executes the fill, so it is the account whose auth procedure reads
            // the conversion info.
            let builder = fee_aware_builder(client, consumer_account_id.into()).await?;
            builder
                .build_pswap_consume(
                    &native_pswap_note,
                    consumer_account_id.into(),
                    account_fill_amount,
                    note_fill_amount,
                )
                .map_err(|err| {
                    js_error_with_context(err, "failed to create PSWAP consume transaction request")
                })?
        };

        Ok(pswap_transaction_request.into())
    }

    #[js_export(js_name = "newPswapCancelTransactionRequest")]
    pub async fn new_pswap_cancel_transaction_request(
        &self,
        pswap_note: &Note,
        creator_account_id: &AccountId,
    ) -> Result<TransactionRequest, JsErr> {
        let native_pswap_note: NativeNote = pswap_note.into();

        let pswap_transaction_request = {
            let mut guard = self.get_mut_inner().await;
            let client = guard.as_mut().ok_or_else(|| {
                from_str_err("Client not initialized while generating transaction request")
            })?;

            // The creator executes the cancellation, so it is the account whose auth procedure
            // reads the conversion info.
            let builder = fee_aware_builder(client, creator_account_id.into()).await?;
            builder
                .build_pswap_cancel(native_pswap_note, creator_account_id.into())
                .map_err(|err| {
                    js_error_with_context(err, "failed to create PSWAP cancel transaction request")
                })?
        };

        Ok(pswap_transaction_request.into())
    }

    /// Executes a transaction specified by the request against the specified account,
    /// proves it, submits it to the network, and updates the local database.
    ///
    /// Uses the prover configured for this client.
    ///
    /// If the transaction utilizes foreign account data, there is a chance that the client doesn't
    /// have the required block header in the local database. In these scenarios, a sync to
    /// the chain tip is performed, and the required block header is retrieved.
    #[js_export(js_name = "submitNewTransaction")]
    pub async fn submit_new_transaction(
        &self,
        account_id: &AccountId,
        transaction_request: &TransactionRequest,
    ) -> Result<TransactionId, JsErr> {
        let transaction_result = self.execute_transaction(account_id, transaction_request).await?;

        let tx_id = transaction_result.id();

        let proven_transaction = self.prove_transaction(&transaction_result, None).await?;

        let submission_height =
            self.submit_proven_transaction(&proven_transaction, &transaction_result).await?;
        self.apply_transaction(&transaction_result, submission_height).await?;

        Ok(tx_id)
    }

    /// Executes a transaction specified by the request against the specified account, proves it
    /// with the user provided prover, submits it to the network, and updates the local database.
    ///
    /// If the transaction utilizes foreign account data, there is a chance that the client doesn't
    /// have the required block header in the local database. In these scenarios, a sync to the
    /// chain tip is performed, and the required block header is retrieved.
    #[js_export(js_name = "submitNewTransactionWithProver")]
    pub async fn submit_new_transaction_with_prover(
        &self,
        account_id: &AccountId,
        transaction_request: &TransactionRequest,
        prover: &TransactionProver,
    ) -> Result<TransactionId, JsErr> {
        let transaction_result = self.execute_transaction(account_id, transaction_request).await?;

        let tx_id = transaction_result.id();

        let proven_transaction =
            self.prove_transaction(&transaction_result, Some(prover.clone())).await?;

        let submission_height =
            self.submit_proven_transaction(&proven_transaction, &transaction_result).await?;
        self.apply_transaction(&transaction_result, submission_height).await?;

        Ok(tx_id)
    }

    /// Executes a batch of transactions against the specified account, proves them individually
    /// and as a batch, submits the batch to the network, and atomically applies the per-tx
    /// updates to the local store. Returns the block number the batch was accepted into.
    ///
    /// All transactions must target the same local account — the `account_id` argument.
    /// Each element of `transaction_requests` is the serialized-bytes form of a
    /// `TransactionRequest` (obtained via `tx_request.serialize()`)
    // TODO V2: support multi-account batches
    #[js_export(js_name = "submitNewTransactionBatch")]
    pub async fn submit_new_transaction_batch(
        &self,
        account_id: &AccountId,
        transaction_requests: Vec<JsBytes>,
    ) -> Result<u32, JsErr> {
        let mut guard = self.get_mut_inner().await;
        let client = guard.as_mut().ok_or_else(|| from_str_err("Client not initialized"))?;
        let native_account_id: miden_client::account::AccountId = account_id.into();

        // Deserialize all requests up front so we fail early on malformed input.
        let mut native_reqs: Vec<NativeTransactionRequest> =
            Vec::with_capacity(transaction_requests.len());
        for bytes in &transaction_requests {
            let req = deserialize_from_bytes::<NativeTransactionRequest>(bytes).map_err(|err| {
                from_str_err(&format!("failed to deserialize transaction request: {err:?}"))
            })?;
            native_reqs.push(req);
        }

        // `new_transaction_batch()` is now a synchronous builder constructor that takes no
        // account id; the target account is supplied per-transaction via `push`. This wrapper
        // keeps its single-account contract by pushing every request against `native_account_id`.
        let mut builder = client.new_transaction_batch();

        for native_req in native_reqs {
            maybe_wrap_send(Box::pin(builder.push(native_account_id, native_req)))
                .await
                .map_err(|err| js_error_with_context(err, "failed to push transaction to batch"))?;
        }

        maybe_wrap_send(Box::pin(builder.submit()))
            .await
            .map(|block_number| block_number.as_u32())
            .map_err(|err| js_error_with_context(err, "failed to submit transaction batch"))
    }

    /// Executes a transaction specified by the request against the specified account but does not
    /// submit it to the network nor update the local database. The returned [`TransactionResult`]
    /// retains the execution artifacts needed to continue with the transaction lifecycle.
    ///
    /// If the transaction utilizes foreign account data, there is a chance that the client doesn't
    /// have the required block header in the local database. In these scenarios, a sync to
    /// the chain tip is performed, and the required block header is retrieved.
    #[js_export(js_name = "executeTransaction")]
    pub async fn execute_transaction(
        &self,
        account_id: &AccountId,
        transaction_request: &TransactionRequest,
    ) -> Result<TransactionResult, JsErr> {
        let mut guard = self.get_mut_inner().await;
        let client = guard.as_mut().ok_or_else(|| from_str_err("Client not initialized"))?;
        let native_request: NativeTransactionRequest = transaction_request.into();
        let fut = Box::pin(client.execute_transaction(account_id.into(), native_request));
        maybe_wrap_send(fut)
            .await
            .map(TransactionResult::from)
            .map_err(|err| js_error_with_context(err, "failed to execute transaction"))
    }

    /// Captures a [`ChainAnchor`] at the client's current sync height, tracking the creation
    /// blocks of the request's authenticated input notes so the request can later execute
    /// against the anchor.
    ///
    /// This is the capture entry point for flows that never see a successful execution at capture
    /// time — e.g. a multisig proposal, where execution intentionally fails with the unauthorized
    /// event to surface the summary for signing. Capture the anchor first, derive the summary
    /// with `executeForSummaryAt`, and ship the anchor alongside the signed data; the same anchor
    /// then reproduces the summary during later verification and execution.
    ///
    /// # Errors
    ///
    /// Fails with code `INVALID_CHAIN_ANCHOR` if the captured block header and blockchain peaks
    /// are inconsistent, which happens when a sync lands mid-capture. Retrying is the fix.
    #[js_export(js_name = "chainAnchorForRequest")]
    pub async fn chain_anchor_for_request(
        &self,
        transaction_request: &TransactionRequest,
    ) -> Result<ChainAnchor, JsErr> {
        let mut guard = self.get_mut_inner().await;
        let client = guard.as_mut().ok_or_else(|| from_str_err("Client not initialized"))?;

        let native_request: NativeTransactionRequest = transaction_request.into();
        let fut = Box::pin(client.chain_anchor_for_request(&native_request));
        maybe_wrap_send(fut)
            .await
            .map(ChainAnchor::from)
            .map_err(|err| map_anchor_err(err, "failed to capture chain anchor"))
    }

    /// Executes a transaction against the specified account using `anchor` as the reference block
    /// instead of the current sync height, without submitting it or updating the local database.
    ///
    /// Since protocol 0.16 the signed transaction summary binds the reference block commitment, so
    /// signatures collected over a summary only authorize an execution whose reference block is
    /// the one the summary was built at. This method makes such an execution reproducible on any
    /// client regardless of its sync height.
    ///
    /// Callers holding an anchor from an untrusted source should first compare
    /// `anchor.commitment()` against an independently trusted value, e.g. the block commitment
    /// bound into the signed transaction summary.
    ///
    /// # Errors
    /// - If an authenticated input note's creation block is not tracked by the anchor.
    /// - If an input note was created after the anchored reference block.
    #[js_export(js_name = "executeTransactionAt")]
    pub async fn execute_transaction_at(
        &self,
        account_id: &AccountId,
        transaction_request: &TransactionRequest,
        anchor: &ChainAnchor,
    ) -> Result<TransactionResult, JsErr> {
        let mut guard = self.get_mut_inner().await;
        let client = guard.as_mut().ok_or_else(|| from_str_err("Client not initialized"))?;
        let native_request: NativeTransactionRequest = transaction_request.into();
        let fut = Box::pin(client.execute_transaction_at(
            account_id.into(),
            native_request,
            anchor.into(),
        ));
        maybe_wrap_send(fut)
            .await
            .map(TransactionResult::from)
            .map_err(|err| map_anchor_err(err, "failed to execute transaction at anchor"))
    }

    /// Executes a transaction at `anchor` and returns the `TransactionSummary` the account is
    /// being asked to authorize — the anchored counterpart of `executeForSummary`.
    ///
    /// This is what lets a co-signer verify a proposal: re-deriving the summary at the proposer's
    /// anchor reproduces it exactly, so it can be compared against the summary they were asked to
    /// sign. Deriving it at the local sync height instead would produce a different summary and
    /// the comparison would always fail.
    ///
    /// # Errors
    /// - If the transaction executes successfully (error code `TRANSACTION_ALREADY_AUTHORIZED`).
    /// - If there is an internal failure during execution.
    #[js_export(js_name = "executeForSummaryAt")]
    pub async fn execute_for_summary_at(
        &self,
        account_id: &AccountId,
        transaction_request: &TransactionRequest,
        anchor: &ChainAnchor,
    ) -> Result<TransactionSummary, JsErr> {
        let mut guard = self.get_mut_inner().await;
        let client = guard.as_mut().ok_or_else(|| from_str_err("Client not initialized"))?;

        let native_request: NativeTransactionRequest = transaction_request.into();
        let fut = Box::pin(client.execute_transaction_at(
            account_id.into(),
            native_request,
            anchor.into(),
        ));
        match maybe_wrap_send(fut).await {
            Ok(_) => Err(from_str_err_with_code(
                "transaction is already fully authorized, so no transaction summary was \
                 produced during execution; submit it with executeTransactionAt against the \
                 same anchor instead",
                "TRANSACTION_ALREADY_AUTHORIZED",
            )),
            Err(ClientError::TransactionExecutorError(TransactionExecutorError::Unauthorized(
                summary,
            ))) => Ok(TransactionSummary::from(*summary)),
            Err(err) => Err(map_anchor_err(err, "failed to execute transaction at anchor")),
        }
    }

    /// Executes a transaction and returns the `TransactionSummary` the account is being asked
    /// to authorize.
    ///
    /// The summary only exists while authorization is pending: when the auth procedure aborts
    /// with the unauthorized event (e.g. a multisig below its signing threshold), the summary
    /// built during execution is returned so it can be signed out-of-band. If the transaction
    /// executes successfully it was already fully authorized, no summary is produced, and this
    /// method returns an error with code `TRANSACTION_ALREADY_AUTHORIZED` — submit the
    /// transaction with `execute` instead.
    ///
    /// # Errors
    /// - If the transaction executes successfully (error code `TRANSACTION_ALREADY_AUTHORIZED`).
    /// - If there is an internal failure during execution.
    #[js_export(js_name = "executeForSummary")]
    pub async fn execute_for_summary(
        &self,
        account_id: &AccountId,
        transaction_request: &TransactionRequest,
    ) -> Result<TransactionSummary, JsErr> {
        let mut guard = self.get_mut_inner().await;
        let client = guard.as_mut().ok_or_else(|| from_str_err("Client not initialized"))?;

        let native_request: NativeTransactionRequest = transaction_request.into();
        let fut = Box::pin(client.execute_transaction(account_id.into(), native_request));
        match maybe_wrap_send(fut).await {
            Ok(_) => Err(from_str_err_with_code(
                "transaction is already fully authorized, so no transaction summary was \
                 produced during execution; submit it with execute instead",
                "TRANSACTION_ALREADY_AUTHORIZED",
            )),
            Err(ClientError::TransactionExecutorError(TransactionExecutorError::Unauthorized(
                summary,
            ))) => Ok(TransactionSummary::from(*summary)),
            Err(err) => Err(js_error_with_context(err, "failed to execute transaction")),
        }
    }

    /// Executes the provided transaction script against the specified account
    /// and returns the resulting stack output. This is a local-only "view call"
    /// that does not submit anything to the network.
    #[js_export(js_name = "executeProgram")]
    pub async fn execute_program(
        &self,
        account_id: &AccountId,
        tx_script: &TransactionScript,
        advice_inputs: &AdviceInputs,
        foreign_accounts: ForeignAccountArray,
    ) -> Result<FeltArray, JsErr> {
        let mut guard = self.get_mut_inner().await;
        let client = guard.as_mut().ok_or_else(|| from_str_err("Client not initialized"))?;
        let foreign_accounts_vec: Vec<crate::models::foreign_account::ForeignAccount> =
            foreign_accounts.into();
        let foreign_accounts_map: BTreeMap<NativeAccountId, NativeForeignAccount> =
            foreign_accounts_vec
                .into_iter()
                .map(|a| {
                    let fa: NativeForeignAccount = a.into();
                    (fa.account_id(), fa)
                })
                .collect();

        let result = client
            .execute_program(
                account_id.into(),
                tx_script.into(),
                advice_inputs.into(),
                foreign_accounts_map,
            )
            .await
            .map_err(|err| js_error_with_context(err, "failed to execute program"))?;

        let felt_vec: Vec<Felt> = result.iter().map(|f| Felt::from(*f)).collect();
        Ok(felt_vec.into())
    }

    /// Generates a transaction proof using either the provided prover or the client's default
    /// prover if none is supplied.
    ///
    /// With an explicit prover this is a pure computation over the `TransactionResult` and does
    /// not touch client state, so it works on a bare `WebClient` that never ran
    /// `createClient()`. "Prover-only" hosts rely on this — e.g. a `chrome.offscreen` document
    /// that proves on its own rayon thread pool. Only the default-prover fallback requires an
    /// initialized client.
    #[js_export(js_name = "proveTransaction")]
    pub async fn prove_transaction(
        &self,
        transaction_result: &TransactionResult,
        prover: Option<TransactionProver>,
    ) -> Result<ProvenTransaction, JsErr> {
        #[cfg(feature = "testing")]
        if prover.is_none() && self.mock_rpc_api.lock().await.is_some() {
            return LocalTransactionProver::default()
                .prove_dummy(transaction_result.native().executed_transaction().clone())
                .map(Into::into)
                .map_err(|err| js_error_with_context(err, "failed to prove transaction"));
        }

        // Resolve the prover up front and release the inner-client lock before the
        // (potentially multi-second) prove: the proof itself needs no client state, so other
        // client calls must not block on it.
        let prover_arc = if let Some(custom_prover) = prover {
            custom_prover.get_prover()
        } else {
            let mut guard = self.get_mut_inner().await;
            let client = guard.as_mut().ok_or_else(|| from_str_err("Client not initialized"))?;
            client.prover()
        };

        let executed_transaction = transaction_result.native().executed_transaction().clone();
        let fut = Box::pin(async move { prover_arc.prove(executed_transaction.into()).await });
        maybe_wrap_send(fut)
            .await
            .map(Into::into)
            .map_err(|err| js_error_with_context(err, "failed to prove transaction"))
    }

    #[js_export(js_name = "submitProvenTransaction")]
    pub async fn submit_proven_transaction(
        &self,
        proven_transaction: &ProvenTransaction,
        transaction_result: &TransactionResult,
    ) -> Result<u32, JsErr> {
        let mut guard = self.get_mut_inner().await;
        let client = guard.as_mut().ok_or_else(|| from_str_err("Client not initialized"))?;
        let native_proven: NativeProvenTransaction = proven_transaction.clone().into();
        client
            .submit_proven_transaction(native_proven, transaction_result.native())
            .await
            .map(|block_number| block_number.as_u32())
            .map_err(|err| js_error_with_context(err, "failed to submit proven transaction"))
    }

    /// Persists a submitted transaction and returns its pre-apply
    /// [`TransactionStoreUpdate`]. Routes through the high-level
    /// `Client::apply_transaction` so registered observers (e.g. PSWAP
    /// tracking) fire.
    #[js_export(js_name = "applyTransaction")]
    pub async fn apply_transaction(
        &self,
        transaction_result: &TransactionResult,
        submission_height: u32,
    ) -> Result<TransactionStoreUpdate, JsErr> {
        let mut guard = self.get_mut_inner().await;
        let client = guard.as_mut().ok_or_else(|| from_str_err("Client not initialized"))?;
        let height = BlockNumber::from(submission_height);

        // Build the pre-apply update for the JS return value.
        let fut =
            Box::pin(client.get_transaction_store_update(transaction_result.native(), height));
        let update = maybe_wrap_send(fut)
            .await
            .map(TransactionStoreUpdate::from)
            .map_err(|err| js_error_with_context(err, "failed to build transaction update"))?;

        // High-level apply fires registered observers (e.g. PSWAP tracking);
        // the low-level `apply_transaction_update` would persist without them.
        let fut = Box::pin(client.apply_transaction(transaction_result.native(), height));
        maybe_wrap_send(fut)
            .await
            .map_err(|err| js_error_with_context(err, "failed to apply transaction result"))?;

        Ok(update)
    }

    /// Builds a request consuming `list_of_notes`, to be executed by `consuming_account_id`.
    ///
    /// The account is required because it is what decides whether the chain's fee conversion info
    /// is committed to the request's auth args. Committing it to a request destined for an account
    /// whose auth procedure does not read it — a no-auth or network account — makes miden-client
    /// reject the request before execution, so there is no default that is right for every caller.
    #[js_export(js_name = "newConsumeTransactionRequest")]
    pub async fn new_consume_transaction_request(
        &self,
        list_of_notes: Vec<Note>,
        consuming_account_id: &AccountId,
    ) -> Result<TransactionRequest, JsErr> {
        // Async only so the chain's fee parameters can be read; the request itself is built the
        // same way it always was. A consume is the one transaction an empty account can afford,
        // because the note's credit lands in the vault before `pay_fee` withdraws from it -- but
        // only if the conversion info is committed, or it never reaches the fee at all.
        let mut guard = self.get_mut_inner().await;
        let client = guard.as_mut().ok_or_else(|| {
            from_str_err("Client not initialized while generating consume transaction request")
        })?;

        let consume_transaction_request = {
            let native_notes = list_of_notes
                .into_iter()
                .map(NativeNote::try_from)
                .collect::<Result<Vec<_>, _>>()
                .map_err(|err| {
                    from_str_err(&format!("Failed to convert note to native note: {err}"))
                })?;

            let builder = fee_aware_builder(client, consuming_account_id.into()).await?;
            builder.build_consume_notes(native_notes).map_err(|err| {
                from_str_err(&format!("Failed to create Consume Transaction Request: {err}"))
            })?
        };

        Ok(consume_transaction_request.into())
    }

    /// A `TransactionRequestBuilder` already declaring a fee conversion salt where `account_id`
    /// needs one to execute.
    ///
    /// Use this instead of `new TransactionRequestBuilder()` whenever the request is assembled by
    /// the caller rather than by one of the convenience constructors, and the executing account is
    /// a multisig: those reuse the fee conversion salt as their transaction summary's replay
    /// guard, so miden-client refuses to invent one and execution fails with
    /// `FeeConversionInfoRequired`.
    ///
    /// For every other account this returns an untouched builder, so it is a safe drop-in: fees
    /// are settled in the chain's native fee asset at rate 1/1 and miden-client commits that
    /// itself, under a fixed default salt, without anything being declared here. It is also a
    /// no-op on a zero-fee chain.
    #[js_export(js_name = "feeAwareTransactionRequestBuilder")]
    pub async fn fee_aware_transaction_request_builder(
        &self,
        account_id: &AccountId,
    ) -> Result<TransactionRequestBuilder, JsErr> {
        let mut guard = self.get_mut_inner().await;
        let client = guard.as_mut().ok_or_else(|| {
            from_str_err("Client not initialized while creating a transaction request builder")
        })?;

        let builder = fee_aware_builder(client, account_id.into()).await?;
        Ok(TransactionRequestBuilder::from_native(builder))
    }
}

/// Maps an anchor-path failure to a JS error, tagging every anchor rejection with a
/// machine-readable code so callers can tell one apart from a generic execution failure.
///
/// Two kinds reach this. A capture-time inconsistency: the anchor is assembled from three separate
/// store reads (sync height, that block's header, the current blockchain peaks) and validated for
/// mutual consistency, so a sync landing from another tab mid-capture yields an anchor whose parts
/// disagree. Retrying the capture is the fix, and saying so is worth doing because nothing in the
/// upstream message does.
///
/// The rest are execution-time rejections of an anchor that is internally consistent — a block the
/// anchor does not track, a reference block that does not match it, an anchor tracking more blocks
/// than a transaction may reference, or an anchored transaction the chain has already expired past.
/// Each already names its own remedy in the upstream message, and for them re-capturing unchanged
/// would loop, so the sync-race hint is deliberately not appended.
fn map_anchor_err(err: ClientError, context: &'static str) -> JsErr {
    match err {
        ClientError::ChainAnchorError(anchor_err) => {
            // Only the two mutual-consistency checks can be lost to a concurrent sync; every other
            // variant describes a property of the anchor that retrying will reproduce.
            let lost_to_concurrent_sync = matches!(
                anchor_err,
                ChainAnchorError::ChainLengthMismatch { .. }
                    | ChainAnchorError::ChainCommitmentMismatch { .. }
            );
            let message = if lost_to_concurrent_sync {
                format!(
                    "{context}: {anchor_err}; a sync may have landed during capture, so retrying \
                     is usually the fix"
                )
            } else {
                format!("{context}: {anchor_err}")
            };
            from_str_err_with_code(&message, "INVALID_CHAIN_ANCHOR")
        },
        err => js_error_with_context(err, context),
    }
}

// FEE CONVERSION INFO
// ================================================================================================

/// The standard auth components installed on `account_id`, or `None` when the account is not in
/// the store.
///
/// An empty vector means the account's auth procedure is one this crate cannot name: either
/// genuinely custom, or standard but compiled from a different miden-standards revision.
///
/// Classification reads the account's code only, and deliberately avoids `AccountInterface`:
/// building one asserts that exactly one auth component is present, and an account carrying a
/// custom auth procedure classifies as `Custom` rather than any auth variant, so the assertion
/// fires. `wasm32` is `panic = "abort"`, which makes that a trap taken while the client borrow is
/// held — poisoning the client for every later call. `from_procedures` cannot panic.
///
/// Matching is by MAST procedure root against the locally pinned miden-standards, so an account
/// whose auth component was compiled from a different revision classifies as `Custom` and yields
/// an empty vector even though its procedure is a standard one. Nothing here can tell that case
/// apart from a genuinely custom auth procedure, so it is a reason to keep this crate's
/// miden-standards pin aligned with the networks it targets rather than something to detect.
async fn standard_auth_components(
    client: &Client<crate::ClientAuth>,
    account_id: NativeAccountId,
) -> Result<Option<Vec<AccountComponentInterface>>, JsErr> {
    let Some(code) = client.get_account_code(account_id).await.map_err(|err| {
        js_error_with_context(
            err,
            &format!(
                "failed to read the code of account {account_id} to classify its auth component"
            ),
        )
    })?
    else {
        return Ok(None);
    };

    Ok(Some(
        AccountComponentInterface::from_procedures(code.procedures())
            .into_iter()
            .filter(|component| {
                matches!(
                    component,
                    AccountComponentInterface::AuthSingleSig
                        | AccountComponentInterface::AuthMultisig
                        | AccountComponentInterface::AuthMultisigSmart
                        | AccountComponentInterface::AuthGuardedMultisig
                        | AccountComponentInterface::AuthNoAuth
                        | AccountComponentInterface::AuthNetworkAccount
                )
            })
            .collect(),
    ))
}

/// Whether `account_id`'s auth component makes the FEE CONVERSION SALT the caller's to choose.
///
/// Fees are always settled in the chain's native fee asset at rate 1/1, so nobody supplies
/// conversion info any more — miden-client builds it and commits it through the auth args itself.
/// The one thing it will not invent is a salt whose value the account gives meaning to. Every
/// multisig flavour (`AuthMultisig`, `AuthMultisigSmart`, `AuthGuardedMultisig`) reuses the salt as
/// its transaction summary's replay guard, so for those the client refuses to guess and execution
/// fails with `FeeConversionInfoRequired` naming the component. Drawing one here is what keeps the
/// convenience constructors working against a multisig account.
///
/// `AuthSingleSig` deliberately answers `false`. It constrains the salt in no way, so the client
/// commits under its own fixed default — fixed precisely because the signed transaction summary
/// covers the auth args, and a fresh salt per execution would change the summary and break any
/// flow that reproduces one to verify a signature over it. Drawing a random salt for it, as this
/// crate did while conversion info was the caller's to supply, would reintroduce exactly that.
///
/// This mirrors miden-client's `FeeAuth::of`, including its PRECEDENCE: a single-sig component
/// decides the answer wherever it sits in the component list, so it is tested first and an account
/// carrying several components is classified rather than rejected. Anything else — an unrecognized
/// auth procedure, or one that pays natively like `AuthNoAuth` and `AuthNetworkAccount` — reads no
/// conversion info at all, and declaring a salt against it is refused upstream with
/// `FeeConversionInfoUnsupported`, so those answer `false` too.
///
/// Answers `false` when the account is not in the store, so the account-not-found error surfaces
/// on its own rather than being preempted by a fee decision about an account nothing knows
/// anything about.
async fn requires_caller_chosen_salt(
    client: &Client<crate::ClientAuth>,
    account_id: NativeAccountId,
) -> Result<bool, JsErr> {
    let Some(components) = standard_auth_components(client, account_id).await? else {
        return Ok(false);
    };

    if components
        .iter()
        .any(|component| matches!(component, AccountComponentInterface::AuthSingleSig))
    {
        return Ok(false);
    }

    Ok(components.iter().any(|component| {
        matches!(
            component,
            AccountComponentInterface::AuthMultisig
                | AccountComponentInterface::AuthMultisigSmart
                | AccountComponentInterface::AuthGuardedMultisig
        )
    }))
}

/// A fresh fee conversion salt for `executing_account_id`, or `None` where the caller should
/// declare none.
///
/// Two gates, both of which keep a request byte-identical to what it would have been when nothing
/// needs declaring. A zero base fee is the first: miden-client skips the whole fee-conversion path
/// when the chain charges nothing AND no salt is declared, so declaring one there would start
/// committing conversion info on chains that do not want it. The second is the executing account's
/// auth component, for the reasons in `requires_caller_chosen_salt`.
///
/// Reads the fee parameters from the store's sync height, while execution reads them from the
/// reference block — the same block only on the unanchored path, since `prepare_transaction` takes
/// the reference header from the anchor when one is supplied. So a request built at a sync height
/// whose base fee is zero and then executed against an anchor whose base fee is not carries no
/// salt, and a multisig account fails with `FeeConversionInfoRequired` at execute time — after the
/// summary has already gone out to co-signers. Build the request and take the anchor at the same
/// sync height.
async fn caller_chosen_fee_conversion_salt(
    client: &mut Client<crate::ClientAuth>,
    executing_account_id: NativeAccountId,
) -> Result<Option<NativeWord>, JsErr> {
    let header = client.get_latest_block_header().await.map_err(|err| {
        js_error_with_context(
            err,
            &format!(
                "failed to read fee parameters from the latest block header while preparing a \
                 request for account {executing_account_id}"
            ),
        )
    })?;
    if header.fee_parameters().verification_base_fee() == 0 {
        return Ok(None);
    }

    if !requires_caller_chosen_salt(client, executing_account_id).await? {
        return Ok(None);
    }

    Ok(Some(client.rng().draw_word()))
}

/// A request builder already carrying a fee conversion salt where the executing account needs one.
///
/// Every convenience constructor that already holds the client starts from this rather than
/// `TransactionRequestBuilder::new()`, and `feeAwareTransactionRequestBuilder` exposes it to
/// callers assembling a request themselves. `executing_account_id` names the account that will
/// execute the request, which is what decides whether a salt has to be declared for it.
///
/// For most accounts this returns an untouched builder: miden-client commits the conversion info
/// itself, under its own fixed default salt, so nothing has to be declared. Only an account that
/// gives the salt its own meaning — the multisig flavours — needs one drawn here.
///
/// One request constructor remains unable to declare a salt: `buildPswapCancelByOrder` delegates
/// request building to miden-client, which builds from a bare `TransactionRequestBuilder`. There is
/// no seam to declare at without an upstream change, because a finished `TransactionRequest` cannot
/// be amended, so a multisig creator's cancel fails with `FeeConversionInfoRequired`. Cancelling by
/// note through `newPswapCancelTransactionRequest` is the alternative.
async fn fee_aware_builder(
    client: &mut Client<crate::ClientAuth>,
    executing_account_id: NativeAccountId,
) -> Result<NativeTransactionRequestBuilder, JsErr> {
    let mut builder = NativeTransactionRequestBuilder::new();
    if let Some(salt) = caller_chosen_fee_conversion_salt(client, executing_account_id).await? {
        builder = builder.fee_conversion_salt(salt);
    }
    Ok(builder)
}