miden-client 0.16.0-rc.1

Client library that facilitates interaction with the Miden network
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
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
//! Provides APIs for creating, executing, proving, and submitting transactions to the Miden
//! network.
//!
//! ## Overview
//!
//! This module enables clients to:
//!
//! - Build transaction requests using the [`TransactionRequestBuilder`].
//!   - [`TransactionRequestBuilder`] contains simple builders for standard transaction types, such
//!     as `p2id` (pay-to-id)
//! - Execute transactions via the local transaction executor and generate a [`TransactionResult`]
//!   that includes execution details and relevant notes for state tracking.
//! - Prove transactions (locally or remotely) using a [`TransactionProver`] and submit the proven
//!   transactions to the network.
//! - Track and update the state of transactions, including their status (e.g., `Pending`,
//!   `Committed`, or `Discarded`).
//!
//! ## Example
//!
//! The following example demonstrates how to create and submit a transaction:
//!
//! ```rust
//! use miden_client::Client;
//! use miden_client::auth::TransactionAuthenticator;
//! use miden_client::crypto::FeltRng;
//! use miden_client::transaction::{PaymentNoteDescription, TransactionRequestBuilder};
//! use miden_protocol::account::AccountId;
//! use miden_protocol::asset::FungibleAsset;
//! use miden_protocol::note::NoteType;
//! # use std::error::Error;
//!
//! /// Executes, proves and submits a P2ID transaction.
//! ///
//! /// This transaction is executed by `sender_id`, and creates an output note
//! /// containing 100 tokens of `faucet_id`'s fungible asset.
//! async fn create_and_submit_transaction<
//!     R: rand::Rng,
//!     AUTH: TransactionAuthenticator + Sync + 'static,
//! >(
//!     client: &mut Client<AUTH>,
//!     sender_id: AccountId,
//!     target_id: AccountId,
//!     faucet_id: AccountId,
//! ) -> Result<(), Box<dyn Error>> {
//!     // Create an asset representing the amount to be transferred.
//!     let asset = FungibleAsset::new(faucet_id, 100)?;
//!
//!     // Build a transaction request for a pay-to-id transaction.
//!     let tx_request = TransactionRequestBuilder::new().build_pay_to_id(
//!         PaymentNoteDescription::new(vec![asset.into()], sender_id, target_id),
//!         NoteType::Private,
//!         client.rng(),
//!     )?;
//!
//!     // Execute, prove, and submit the transaction in a single call.
//!     let _tx_id = client.submit_new_transaction(sender_id, tx_request).await?;
//!
//!     Ok(())
//! }
//! ```
//!
//! For more detailed information about each function and error type, refer to the specific API
//! documentation.

use alloc::boxed::Box;
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::sync::Arc;
use alloc::vec::Vec;

use miden_protocol::account::{Account, AccountCode, AccountId};
use miden_protocol::asset::{Asset, NonFungibleAsset};
use miden_protocol::block::{BlockHeader, BlockNumber};
use miden_protocol::errors::AssetError;
use miden_protocol::note::{
    Note,
    NoteAttachments,
    NoteDetails,
    NoteId,
    NoteRecipient,
    NoteScript,
    NoteTag,
};
use miden_protocol::transaction::AccountInputs;
use miden_protocol::vm::MIN_STACK_DEPTH;
use miden_protocol::{Felt, Word};
use miden_standards::account::faucets::FungibleFaucet;
use miden_standards::account::interface::AccountInterfaceExt;
use miden_tx::{DataStore, NoteConsumptionChecker, TransactionExecutor};
use tracing::info;

use super::Client;
use crate::ClientError;
use crate::note::{NoteScreenerError, NoteUpdateTracker, StandardNote};
use crate::rpc::domain::account::{
    AccountStorageRequirements,
    GetAccountRequest,
    StorageMapFetch,
    VaultFetch,
};
use crate::rpc::encryption::{TransactionEncryptionKey, seal_transaction_inputs};
use crate::rpc::{AccountStateAt, NodeRpcClient, RpcError};
use crate::store::data_store::ClientDataStore;
use crate::store::input_note_states::ExpectedNoteState;
use crate::store::{
    AccountRecord,
    InputNoteRecord,
    InputNoteState,
    NoteFilter,
    NoteRecordError,
    OutputNoteRecord,
    Store,
    StoreError,
    TransactionFilter,
};
use crate::sync::NoteTagRecord;
use crate::transaction::batch::InMemoryBatchDataStore;

pub mod batch;
pub use batch::{BatchBuilder, BatchBuilderError};

#[cfg(feature = "dap")]
mod dap_executor;
mod prover;
pub use prover::TransactionProver;

mod record;
pub use record::{
    DiscardCause,
    TransactionDetails,
    TransactionRecord,
    TransactionStatus,
    TransactionStatusVariant,
};

mod store_update;
pub use store_update::TransactionStoreUpdate;

mod request;
pub use request::{
    ForeignAccount,
    NoteArgs,
    PaymentNoteDescription,
    PswapTransactionData,
    SwapTransactionData,
    TransactionRequest,
    TransactionRequestBuilder,
    TransactionRequestError,
    TransactionScriptTemplate,
};

mod observer;
pub use observer::TransactionObserver;

mod result;
// RE-EXPORTS
// ================================================================================================
pub use miden_protocol::transaction::{
    ExecutedTransaction,
    InputNote,
    InputNotes,
    OutputNote,
    OutputNotes,
    ProvenTransaction,
    PublicOutputNote,
    RawOutputNote,
    RawOutputNotes,
    TransactionArgs,
    TransactionId,
    TransactionInputs,
    TransactionKernel,
    TransactionScript,
    TransactionScriptRoot,
    TransactionSummary,
};
pub use miden_protocol::vm::{AdviceInputs, AdviceMap};
pub use miden_standards::account::interface::{AccountComponentInterface, AccountInterface};
pub use miden_standards::tx_script::{
    ExpirationTransactionScript,
    SendNotesTransactionScriptError,
};
pub use miden_tx::auth::TransactionAuthenticator;
pub use miden_tx::{
    DataStoreError,
    LocalTransactionProver,
    ProvingOptions,
    TransactionExecutorError,
    TransactionProverError,
};
pub use result::TransactionResult;

/// Transaction management methods
impl<AUTH> Client<AUTH>
where
    AUTH: TransactionAuthenticator + Sync + 'static,
{
    // TRANSACTION DATA RETRIEVAL
    // --------------------------------------------------------------------------------------------

    /// Retrieves tracked transactions, filtered by [`TransactionFilter`].
    pub async fn get_transactions(
        &self,
        filter: TransactionFilter,
    ) -> Result<Vec<TransactionRecord>, ClientError> {
        self.store.get_transactions(filter).await.map_err(Into::into)
    }

    // TRANSACTION BATCH
    // --------------------------------------------------------------------------------------------

    /// Open a new [`BatchBuilder`] for accumulating transactions across one or more local
    /// accounts.
    ///
    /// See [`crate::transaction::batch`] for usage and constraints.
    pub fn new_transaction_batch(&mut self) -> BatchBuilder<'_, AUTH> {
        let inner_data_store = ClientDataStore::new(self.store.clone(), self.rpc_api.clone());
        BatchBuilder {
            client: self,
            data_store: InMemoryBatchDataStore::new(inner_data_store),
            pushed_txs: Vec::new(),
            consumed_input_notes: BTreeSet::new(),
        }
    }

    // TRANSACTION
    // --------------------------------------------------------------------------------------------

    /// 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 client's default prover (configured via
    /// [`crate::builder::ClientBuilder::prover`]).
    pub async fn submit_new_transaction(
        &mut self,
        account_id: AccountId,
        transaction_request: TransactionRequest,
    ) -> Result<TransactionId, ClientError> {
        let prover = self.tx_prover.clone();
        self.submit_new_transaction_with_prover(account_id, transaction_request, prover)
            .await
    }

    /// Executes a transaction specified by the request against the specified account,
    /// proves it with the provided prover, submits it to the network, and updates the local
    /// database.
    ///
    /// This is useful for falling back to a different prover (e.g., local) when the default
    /// prover (e.g., remote) fails with a [`ClientError::TransactionProvingError`].
    pub async fn submit_new_transaction_with_prover(
        &mut self,
        account_id: AccountId,
        transaction_request: TransactionRequest,
        tx_prover: Arc<dyn TransactionProver>,
    ) -> Result<TransactionId, ClientError> {
        // Register any missing NTX scripts before the main transaction.
        // The registration path contains its own full execute -> prove -> submit pipeline.
        if !transaction_request.expected_ntx_scripts().is_empty() {
            Box::pin(self.ensure_ntx_scripts_registered(
                account_id,
                transaction_request.expected_ntx_scripts(),
                tx_prover.clone(),
            ))
            .await?;
        }

        let tx_result = self.execute_transaction(account_id, transaction_request).await?;
        let tx_id = tx_result.executed_transaction().id();

        let proven_transaction = self.prove_transaction_with(&tx_result, tx_prover).await?;
        let submission_height =
            self.submit_proven_transaction(proven_transaction, &tx_result).await?;

        // The transaction has been accepted by the node; the local store update
        // is a separate step that can fail independently. On failure, return a
        // distinct error carrying the pending update so the caller can decide
        // how to recover (re-apply later via `apply_transaction_update`,
        // persist for the next session, etc.).
        //
        // The update is boxed so it does not inflate the enclosing future
        // across await points (triggers clippy::large_futures).
        let tx_update =
            Box::new(self.get_transaction_store_update(&tx_result, submission_height).await?);

        if let Err(apply_err) = self.apply_transaction_update((*tx_update).clone()).await {
            info!(
                "apply_transaction_update failed for submitted tx {tx_id}; returning \
                 ApplyTransactionAfterSubmitFailed with the pending update attached: {apply_err}"
            );
            return Err(ClientError::ApplyTransactionAfterSubmitFailed {
                pending_update: tx_update,
                source: Box::new(apply_err),
            });
        }

        // Fire transaction observers (mirrors `apply_transaction`). Per-observer failures are
        // logged and never propagate — they're feature-specific side-channels, not part of the
        // submit contract.
        for observer in &self.transaction_observers {
            crate::errors::log_observer_failure(
                observer.name(),
                "TransactionObserver::apply",
                observer.apply(&tx_result).await,
            );
        }

        Ok(tx_id)
    }

    /// Creates and executes a transaction specified by the request against the specified account,
    /// but doesn't change the local database.
    ///
    /// # Errors
    ///
    /// - Returns [`ClientError::MissingOutputRecipients`] if the [`TransactionRequest`] output
    ///   notes are not a subset of executor's output notes.
    /// - Returns a [`ClientError::TransactionExecutorError`] if the execution fails.
    /// - Returns a [`ClientError::TransactionRequestError`] if the request is invalid.
    pub async fn execute_transaction(
        &mut self,
        account_id: AccountId,
        transaction_request: TransactionRequest,
    ) -> Result<TransactionResult, ClientError> {
        self.execute_transaction_with_mode(
            account_id,
            transaction_request,
            TransactionExecutionMode::Standard,
        )
        .await
    }

    /// Executes `transaction_request` (e.g. consuming a note) through the DAP program executor,
    /// so a DAP client can attach and step through the whole transaction — kernel, note scripts,
    /// and account code — instead of only a standalone transaction script.
    ///
    /// This is a debugging entry point: it runs the transaction interactively under the debug
    /// adapter and does not prove, submit, or apply the result. The listen address (and optional
    /// replay-snapshot path) are taken from the globally installed
    /// [`DapConfig`](miden_debug::DapConfig).
    ///
    /// # Errors
    ///
    /// This applies the same request preparation and output-recipient validation as
    /// [`Self::execute_transaction`], and returns the corresponding [`ClientError`] on failure.
    #[cfg(feature = "dap")]
    pub async fn execute_transaction_with_dap(
        &mut self,
        account_id: AccountId,
        transaction_request: TransactionRequest,
    ) -> Result<TransactionResult, ClientError> {
        self.execute_transaction_with_mode(
            account_id,
            transaction_request,
            TransactionExecutionMode::Dap,
        )
        .await
    }

    /// Executes a prepared transaction with the selected program executor while keeping request
    /// preparation, data-store population, note filtering, and result validation identical across
    /// execution modes.
    async fn execute_transaction_with_mode(
        &mut self,
        account_id: AccountId,
        transaction_request: TransactionRequest,
        execution_mode: TransactionExecutionMode,
    ) -> Result<TransactionResult, ClientError> {
        let account: Account = self.get_native_account_record(account_id).await?.try_into()?;

        let prep = self.prepare_transaction(&account, transaction_request).await?;

        let data_store = ClientDataStore::new(self.store.clone(), self.rpc_api.clone());
        data_store.register_note_scripts(prep.output_note_scripts());
        for fpi_account in &prep.foreign_account_inputs {
            data_store.mast_store().load_account_code(fpi_account.code());
        }
        data_store.register_foreign_account_inputs(prep.foreign_account_inputs);

        data_store.mast_store().load_account_code(account.code());

        let mut notes = prep.notes;
        if prep.ignore_invalid_notes {
            notes = self
                .get_valid_input_notes(
                    &account,
                    notes,
                    prep.tx_args.clone(),
                    &prep.output_recipients,
                )
                .await?;
        }

        let executed_transaction = match execution_mode {
            TransactionExecutionMode::Standard => {
                self.build_executor(&data_store)?
                    .execute_transaction(account_id, prep.block_num, notes, prep.tx_args)
                    .await?
            },
            #[cfg(feature = "dap")]
            TransactionExecutionMode::Dap => {
                self.build_dap_executor(&data_store)?
                    .execute_transaction(account_id, prep.block_num, notes, prep.tx_args)
                    .await?
            },
        };

        validate_executed_transaction(&executed_transaction, &prep.output_recipients)?;
        TransactionResult::new(executed_transaction, prep.future_notes)
    }

    /// Performs the data-store-independent setup shared by `execute_transaction` and
    /// `execute_transaction_for_batch`: validates the request against the supplied
    /// `account`, loads/filters input notes, builds the transaction script and args,
    /// retrieves foreign-account inputs, and computes the reference block number.
    ///
    /// This method does not write to the store: any state produced by the transaction is
    /// persisted only after the transaction executes successfully.
    ///
    /// `account` is the state validation runs against — for a single transaction this is
    /// the persisted account; inside [`crate::transaction::BatchBuilder::push`] it is the
    /// in-batch (stacked) state, so balances reflect prior pushes.
    pub(crate) async fn prepare_transaction(
        &self,
        account: &Account,
        transaction_request: TransactionRequest,
    ) -> Result<PreparedTransaction, ClientError> {
        self.validate_recency().await?;
        validate_account_request(&transaction_request, account)?;

        // Retrieve all input notes from the store.
        let mut stored_note_records = self
            .store
            .get_input_notes(NoteFilter::List(transaction_request.input_note_ids().collect()))
            .await?;

        // Verify that none of the authenticated input notes are already consumed.
        for note in &stored_note_records {
            if note.is_consumed() {
                let id = note.id().expect(
                    "stored note records reaching this check carry metadata so id() is Some",
                );
                return Err(ClientError::TransactionRequestError(
                    TransactionRequestError::InputNoteAlreadyConsumed(id),
                ));
            }
        }

        // Only keep authenticated input notes from the store.
        stored_note_records.retain(InputNoteRecord::is_authenticated);

        let notes = transaction_request.build_input_notes(stored_note_records)?;

        let output_recipients =
            transaction_request.expected_output_recipients().cloned().collect::<Vec<_>>();

        let future_notes: Vec<(NoteDetails, NoteTag)> =
            transaction_request.expected_future_notes().cloned().collect();

        let tx_script = transaction_request.build_transaction_script(&account.code_interface())?;

        let foreign_accounts = transaction_request.foreign_accounts().clone();

        let (fpi_block_num, foreign_account_inputs) =
            self.retrieve_foreign_account_inputs(foreign_accounts).await?;

        let ignore_invalid_notes = transaction_request.ignore_invalid_input_notes();

        let block_num = if let Some(block_num) = fpi_block_num {
            block_num
        } else {
            self.store.get_sync_height().await?
        };

        let tx_args = transaction_request.into_transaction_args(tx_script);

        Ok(PreparedTransaction {
            notes,
            output_recipients,
            future_notes,
            tx_args,
            foreign_account_inputs,
            block_num,
            ignore_invalid_notes,
        })
    }

    /// Proves the specified transaction using the prover configured for this client.
    pub async fn prove_transaction(
        &self,
        tx_result: &TransactionResult,
    ) -> Result<ProvenTransaction, ClientError> {
        self.prove_transaction_with(tx_result, self.tx_prover.clone()).await
    }

    /// Proves the specified transaction using the provided prover.
    ///
    /// # Errors
    ///
    /// - Returns a [`ClientError::TransactionProvingError`] if the prover fails to produce a proof.
    /// - Returns a [`ClientError::MismatchedProvenTransaction`] if the prover returns a proof of a
    ///   transaction other than the requested one.
    pub async fn prove_transaction_with(
        &self,
        tx_result: &TransactionResult,
        tx_prover: Arc<dyn TransactionProver>,
    ) -> Result<ProvenTransaction, ClientError> {
        info!("Proving transaction...");

        let executed_transaction = tx_result.executed_transaction();
        let proven_transaction = tx_prover.prove(executed_transaction.clone().into()).await?;

        // A prover is trusted with the witness, but not with choosing which transaction gets
        // submitted. Everything downstream (submission, the local store update, the returned
        // id) is derived from `tx_result`, so a proof of anything else would be submitted
        // while the local state recorded the transaction that never reached the network.
        //
        // The id commits to the initial and final account commitments and to the input and
        // output note commitments; the account commitments in turn commit to the account id,
        // so a matching id covers the account as well.
        if proven_transaction.id() != executed_transaction.id() {
            return Err(ClientError::MismatchedProvenTransaction {
                requested: executed_transaction.id(),
                returned: proven_transaction.id(),
            });
        }

        info!("Transaction proven.");

        Ok(proven_transaction)
    }

    /// Submits a previously proven transaction to the RPC endpoint and returns the node’s chain tip
    /// upon mempool admission.
    pub async fn submit_proven_transaction(
        &mut self,
        proven_transaction: ProvenTransaction,
        transaction_inputs: impl Into<TransactionInputs>,
    ) -> Result<BlockNumber, ClientError> {
        info!("Submitting transaction to the network...");
        let tx_id = proven_transaction.id();
        let key = self.transaction_encryption_key().await?;
        let sealed_inputs =
            seal_transaction_inputs(&mut self.rng, &key, tx_id, &transaction_inputs.into())?;
        let result =
            self.rpc_api.submit_proven_transaction(proven_transaction, sealed_inputs).await;
        if let Err(err) = &result {
            self.forget_stale_transaction_encryption_key(err).await;
        }
        let block_num = result?;
        info!("Transaction submitted.");

        Ok(block_num)
    }

    /// Returns the validator set's transaction encryption key, fetching and verifying it on first
    /// use.
    ///
    /// The key is public data shared by the whole validator set, so it is cached in the store and
    /// reused across submissions and restarts. A freshly fetched key is verified against the
    /// validator set committed in the chain tip before it is cached or used: the endpoint is served
    /// by the RPC operator, which is the party the encryption keeps out.
    pub(crate) async fn transaction_encryption_key(
        &self,
    ) -> Result<TransactionEncryptionKey, ClientError> {
        if let Some(key) = self.store.get_transaction_encryption_key().await? {
            return Ok(key);
        }

        let attested = self.rpc_api.get_transaction_encryption_key().await?;

        // The genesis commitment scopes the attestation to this chain, and the chain tip carries
        // the validator set currently entitled to attest. Both come from the local store, so a
        // response cannot supply its own trust anchor.
        let genesis_commitment =
            self.trusted_block_header(BlockNumber::GENESIS).await?.commitment();
        let chain_tip = self.store.get_sync_height().await?;
        let validator_keys = self.trusted_block_header(chain_tip).await?.validator_keys().clone();

        let key = attested.verify(genesis_commitment, &validator_keys)?;
        self.store.set_transaction_encryption_key(&key).await?;

        Ok(key)
    }

    /// Installs the transaction encryption key that submission seals against, skipping the fetch
    /// and its attestation check.
    #[cfg(feature = "testing")]
    pub async fn seed_transaction_encryption_key(
        &self,
        key: TransactionEncryptionKey,
    ) -> Result<(), ClientError> {
        Ok(self.store.set_transaction_encryption_key(&key).await?)
    }

    /// Evicts the cached encryption key when a submission was rejected for having been sealed
    /// against a key the validator does not hold, so the next submission fetches a fresh one.
    ///
    /// An eviction failure is logged rather than returned: the caller is already reporting the
    /// submission error, which the store error must not mask.
    pub(crate) async fn forget_stale_transaction_encryption_key(&self, err: &RpcError) {
        if err.is_stale_transaction_encryption_key()
            && let Err(err) = self.store.remove_transaction_encryption_key().await
        {
            tracing::warn!("failed to evict the stale transaction encryption key: {err}");
        }
    }

    /// Returns a locally stored block header, which the client has already authenticated during
    /// sync.
    ///
    /// # Errors
    /// Returns an error if the header is not stored locally, which means the client has not synced
    /// far enough to have a trust anchor.
    async fn trusted_block_header(
        &self,
        block_num: BlockNumber,
    ) -> Result<BlockHeader, ClientError> {
        self.store.get_block_header_by_num(block_num).await?.map(|(header, _)| header).ok_or_else(
            || {
                ClientError::ChainValidationError(alloc::format!(
                    "block header {block_num} is not tracked locally; sync the client before it can verify data against the chain"
                ))
            },
        )
    }

    /// Builds a [`TransactionStoreUpdate`] for the provided transaction result at the specified
    /// submission height.
    pub async fn get_transaction_store_update(
        &self,
        tx_result: &TransactionResult,
        submission_height: BlockNumber,
    ) -> Result<TransactionStoreUpdate, TransactionStoreUpdateError> {
        let note_updates = self.get_note_updates(submission_height, tx_result).await?;

        // Only expected input notes need tags; output notes are committed (with proofs)
        // via account-matched transaction sync.
        let new_tags: Vec<NoteTagRecord> = note_updates
            .updated_input_notes()
            .filter_map(|note| {
                let note = note.inner();

                if let InputNoteState::Expected(ExpectedNoteState { tag: Some(tag), .. }) =
                    note.state()
                {
                    Some(NoteTagRecord::with_note_source(*tag, note.details_commitment()))
                } else {
                    None
                }
            })
            .collect();

        Ok(TransactionStoreUpdate::new(
            tx_result.executed_transaction().clone(),
            submission_height,
            note_updates,
            tx_result.future_notes().to_vec(),
            new_tags,
        ))
    }

    /// Persists the effects of a submitted transaction into the local store,
    /// updating account data, note metadata, and future note tracking.
    pub async fn apply_transaction(
        &self,
        tx_result: &TransactionResult,
        submission_height: BlockNumber,
    ) -> Result<(), ClientError> {
        let tx_update = self.get_transaction_store_update(tx_result, submission_height).await?;

        self.apply_transaction_update(tx_update).await?;

        // Fire transaction observers. Per-observer failures are logged.
        for observer in &self.transaction_observers {
            if let Err(err) = observer.apply(tx_result).await {
                tracing::warn!(
                    observer = observer.name(),
                    error = ?err,
                    "TransactionObserver::apply failed; continuing with remaining observers",
                );
            }
        }

        Ok(())
    }

    pub async fn apply_transaction_update(
        &self,
        tx_update: TransactionStoreUpdate,
    ) -> Result<(), ClientError> {
        // Transaction was proven and submitted to the node correctly, persist note details and
        // update account
        info!("Applying transaction to the local store...");

        let executed_transaction = tx_update.executed_transaction();
        let account_id = executed_transaction.account_id();

        if self.account_reader(account_id).status().await?.is_locked() {
            return Err(ClientError::AccountLocked(account_id));
        }

        self.store.apply_transaction(tx_update).await?;
        info!("Transaction stored.");
        Ok(())
    }

    /// Executes the provided transaction script against the specified account, and returns the
    /// resulting stack. Advice inputs and foreign accounts can be provided for the execution.
    ///
    /// The transaction will use the current sync height as the block reference.
    pub async fn execute_program(
        &mut self,
        account_id: AccountId,
        tx_script: TransactionScript,
        advice_inputs: AdviceInputs,
        foreign_accounts: BTreeMap<AccountId, ForeignAccount>,
    ) -> Result<[Felt; MIN_STACK_DEPTH], ClientError> {
        let (data_store, block_ref) =
            self.prepare_program_execution(account_id, foreign_accounts).await?;

        Ok(self
            .build_executor(&data_store)?
            .execute_tx_view_script(account_id, block_ref, tx_script, advice_inputs)
            .await?)
    }

    /// Executes the provided transaction script with a DAP debug adapter listening for
    /// connections, allowing interactive debugging via any DAP-compatible client.
    #[cfg(feature = "dap")]
    pub async fn execute_program_with_dap(
        &mut self,
        account_id: AccountId,
        tx_script: TransactionScript,
        advice_inputs: AdviceInputs,
        foreign_accounts: BTreeMap<AccountId, ForeignAccount>,
    ) -> Result<[Felt; MIN_STACK_DEPTH], ClientError> {
        let (data_store, block_ref) =
            self.prepare_program_execution(account_id, foreign_accounts).await?;

        Ok(self
            .build_dap_executor(&data_store)?
            .execute_tx_view_script(account_id, block_ref, tx_script, advice_inputs)
            .await?)
    }

    // HELPERS
    // --------------------------------------------------------------------------------------------

    /// Validates that the specified transaction request can be executed by the specified account.
    ///
    /// This does't guarantee that the transaction will succeed, but it's useful to avoid submitting
    /// transactions that are guaranteed to fail. Some of the validations include:
    /// - That the account has enough balance to cover the outgoing assets.
    /// - That the client is not too far behind the chain tip.
    pub async fn validate_request(
        &self,
        account_id: AccountId,
        transaction_request: &TransactionRequest,
    ) -> Result<(), ClientError> {
        self.validate_recency().await?;
        validate_output_note_senders(transaction_request, account_id)?;
        let account = self.try_get_account(account_id).await?;
        validate_account_request(transaction_request, &account)
    }

    async fn validate_recency(&self) -> Result<(), ClientError> {
        if let Some(max_block_number_delta) = self.max_block_number_delta {
            let current_chain_tip =
                self.rpc_api.get_block_header_by_number(None, false).await?.0.block_num();

            if current_chain_tip > self.store.get_sync_height().await? + max_block_number_delta {
                return Err(ClientError::RecencyConditionError(
                    "The client is too far behind the chain tip to execute the transaction",
                ));
            }
        }
        Ok(())
    }

    /// Checks whether the node's `note_scripts` registry already has each of the expected NTX
    /// scripts. For any script that is missing, creates and submits a registration transaction
    /// that produces a public note carrying that script.
    ///
    /// `account_id` is the account that will execute the registration transaction.
    ///
    /// Standard note scripts are skipped — the NTX builder resolves those directly, so they
    /// never need registering. A missing non-standard script is registered, not an error.
    ///
    /// This method is called automatically by [`Self::submit_new_transaction_with_prover`] when the
    /// [`TransactionRequest`] contains expected NTX scripts. It can also be called directly if
    /// you want to register scripts ahead of time.
    pub async fn ensure_ntx_scripts_registered(
        &mut self,
        account_id: AccountId,
        scripts: &[NoteScript],
        tx_prover: Arc<dyn TransactionProver>,
    ) -> Result<(), ClientError> {
        let mut missing_scripts = Vec::new();

        for script in scripts {
            // Standard scripts are resolved by the NTX builder directly; no registration needed.
            if StandardNote::from_script(script).is_some() {
                continue;
            }

            let script_root = script.root();

            // Scripts the node doesn't have are queued for registration; only RPC errors abort.
            match self.rpc_api.get_note_script_by_root(script_root.into()).await {
                Ok(Some(_)) => {},
                Ok(None) => missing_scripts.push(script.clone()),
                Err(source) => {
                    return Err(ClientError::NtxScriptRegistrationFailed {
                        script_root: script_root.into(),
                        source,
                    });
                },
            }
        }

        if missing_scripts.is_empty() {
            return Ok(());
        }

        let registration_request = TransactionRequestBuilder::new().build_register_note_scripts(
            account_id,
            missing_scripts,
            self.rng(),
        )?;

        let tx_result = self.execute_transaction(account_id, registration_request).await?;
        let proven = self.prove_transaction_with(&tx_result, tx_prover).await?;
        let submission_height = self.submit_proven_transaction(proven, &tx_result).await?;
        self.apply_transaction(&tx_result, submission_height).await?;

        Ok(())
    }

    /// Filters the provided input notes down to the subset that can be consumed by the account.
    ///
    /// `output_recipients` are the request's expected output recipients; their scripts are
    /// registered on the consumption-check data store so output note creation can resolve them
    /// without them being present in the store.
    pub(crate) async fn get_valid_input_notes(
        &self,
        account: &Account,
        mut input_notes: InputNotes<InputNote>,
        tx_args: TransactionArgs,
        output_recipients: &[NoteRecipient],
    ) -> Result<InputNotes<InputNote>, ClientError> {
        loop {
            let data_store = ClientDataStore::new(self.store.clone(), self.rpc_api.clone());
            data_store.register_note_scripts(output_recipients.iter().map(|r| r.script().clone()));

            data_store.mast_store().load_account_code(account.code());
            let execution = NoteConsumptionChecker::new(&self.build_executor(&data_store)?)
                .check_notes_consumability(
                    account.id(),
                    self.store.get_sync_height().await?,
                    input_notes.iter().map(|n| n.clone().into_note()).collect(),
                    tx_args.clone(),
                )
                .await?;

            if execution.failed().is_empty() {
                break;
            }

            let failed_note_ids: BTreeSet<NoteId> =
                execution.failed().iter().map(|n| n.note().id()).collect();
            let filtered_input_notes = InputNotes::new(
                input_notes
                    .into_iter()
                    .filter(|note| !failed_note_ids.contains(&note.id()))
                    .collect(),
            )
            .expect("Created from a valid input notes list");

            input_notes = filtered_input_notes;
        }

        Ok(input_notes)
    }

    /// Returns foreign account inputs for the required foreign accounts specified by the
    /// transaction request.
    ///
    /// For any [`ForeignAccount::Public`] in `foreign_accounts`, these pieces of data are retrieved
    /// from the network. For any [`ForeignAccount::Private`] account, inner data is used and only
    /// a proof of the account's existence on the network is fetched.
    async fn retrieve_foreign_account_inputs(
        &self,
        foreign_accounts: BTreeMap<AccountId, ForeignAccount>,
    ) -> Result<(Option<BlockNumber>, Vec<AccountInputs>), ClientError> {
        if foreign_accounts.is_empty() {
            return Ok((None, Vec::new()));
        }

        let block_num = self.store.get_sync_height().await?;
        let mut return_foreign_account_inputs = Vec::with_capacity(foreign_accounts.len());

        for foreign_account in foreign_accounts.into_values() {
            let foreign_account_inputs = match foreign_account {
                ForeignAccount::Public(account_id, storage_requirements) => {
                    fetch_public_account_inputs(
                        &self.store,
                        &self.rpc_api,
                        account_id,
                        storage_requirements,
                        AccountStateAt::Block(block_num),
                    )
                    .await?
                },
                ForeignAccount::Private(partial_account) => {
                    let account_id = partial_account.id();
                    let (_, account_proof) = self
                        .rpc_api
                        .get_account(
                            account_id,
                            GetAccountRequest::new().at(AccountStateAt::Block(block_num)),
                        )
                        .await?;
                    let (witness, _) = account_proof.into_parts();
                    AccountInputs::new(partial_account, witness)
                },
            };

            return_foreign_account_inputs.push(foreign_account_inputs);
        }

        Ok((Some(block_num), return_foreign_account_inputs))
    }

    /// Prepares the data store and block reference for program execution.
    ///
    /// This is shared setup for both `execute_program` and `execute_program_with_dap`.
    async fn prepare_program_execution(
        &mut self,
        account_id: AccountId,
        foreign_accounts: BTreeMap<AccountId, ForeignAccount>,
    ) -> Result<(ClientDataStore, BlockNumber), ClientError> {
        let (fpi_block_number, foreign_account_inputs) =
            self.retrieve_foreign_account_inputs(foreign_accounts).await?;

        let block_ref = if let Some(block_number) = fpi_block_number {
            block_number
        } else {
            self.get_sync_height().await?
        };

        let account_code = self
            .store
            .get_account_code(account_id)
            .await?
            .ok_or(ClientError::AccountDataNotFound(account_id))?;

        let data_store = ClientDataStore::new(self.store.clone(), self.rpc_api.clone());

        // Ensure code is loaded on MAST store
        data_store.mast_store().load_account_code(&account_code);

        for fpi_account in &foreign_account_inputs {
            data_store.mast_store().load_account_code(fpi_account.code());
        }

        data_store.register_foreign_account_inputs(foreign_account_inputs);

        Ok((data_store, block_ref))
    }

    /// Creates a transaction executor configured with the client's runtime options,
    /// authenticator, and source manager.
    pub(crate) fn build_executor<'store, 'auth, STORE: DataStore + Sync>(
        &'auth self,
        data_store: &'store STORE,
    ) -> Result<TransactionExecutor<'store, 'auth, STORE, AUTH>, TransactionExecutorError> {
        let mut executor = TransactionExecutor::new(data_store)
            .with_options(self.exec_options)?
            .with_source_manager(self.source_manager.clone());
        if let Some(authenticator) = self.authenticator.as_deref() {
            executor = executor.with_authenticator(authenticator);
        }
        Ok(executor)
    }

    /// Loads an [`AccountRecord`] for an account that must be usable as a transaction's native
    /// account. Errors out if the account is not tracked or if it is watched.
    async fn get_native_account_record(
        &self,
        account_id: AccountId,
    ) -> Result<AccountRecord, ClientError> {
        let account_record = self
            .store
            .get_account(account_id)
            .await?
            .ok_or(ClientError::AccountDataNotFound(account_id))?;
        if account_record.is_watched() {
            return Err(ClientError::AccountIsWatched(account_id));
        }
        Ok(account_record)
    }

    /// Creates a transaction executor configured for DAP (Debug Adapter Protocol) debugging.
    #[cfg(feature = "dap")]
    pub(crate) fn build_dap_executor<'store, 'auth, STORE: DataStore + Sync>(
        &'auth self,
        data_store: &'store STORE,
    ) -> Result<
        TransactionExecutor<'store, 'auth, STORE, AUTH, dap_executor::DapProgramExecutor>,
        TransactionExecutorError,
    > {
        Ok(self
            .build_executor(data_store)?
            .with_program_executor::<dap_executor::DapProgramExecutor>())
    }

    /// Returns [`NoteUpdateTracker`] containing the note updates generated by an executed
    /// transaction.
    async fn get_note_updates(
        &self,
        submission_height: BlockNumber,
        tx_result: &TransactionResult,
    ) -> Result<NoteUpdateTracker, TransactionStoreUpdateError> {
        let executed_tx = tx_result.executed_transaction();
        let current_timestamp = self.store.get_current_timestamp();
        let current_block_num = self.store.get_sync_height().await?;

        // New output notes
        let new_output_notes = executed_tx
            .output_notes()
            .iter()
            .cloned()
            .filter_map(|output_note| {
                OutputNoteRecord::try_from_output_note(output_note, submission_height).ok()
            })
            .collect::<Vec<_>>();

        // New relevant input notes
        let mut new_input_notes = vec![];
        let output_notes: Vec<Note> =
            notes_from_output(executed_tx.output_notes()).cloned().collect();
        let note_screener = self.note_screener().clone();
        let output_note_relevances = note_screener.get_batch_consumability(&output_notes).await?;

        for note in output_notes {
            if output_note_relevances.contains_key(&note.id()) {
                let metadata = *note.metadata();
                let tag = metadata.tag();
                let attachments = note.attachments().clone();

                new_input_notes.push(InputNoteRecord::new(
                    note.into(),
                    attachments,
                    current_timestamp,
                    ExpectedNoteState {
                        metadata: Some(metadata),
                        after_block_num: submission_height,
                        tag: Some(tag),
                    }
                    .into(),
                ));
            }
        }

        // Track future input notes described in the transaction result.
        new_input_notes.extend(tx_result.future_notes().iter().map(|(note_details, tag)| {
            InputNoteRecord::new(
                note_details.clone(),
                NoteAttachments::empty(),
                None,
                ExpectedNoteState {
                    metadata: None,
                    after_block_num: current_block_num,
                    tag: Some(*tag),
                }
                .into(),
            )
        }));

        // Locally consumed notes. Notes already tracked by the store only need their state
        // advanced; the rest (the request's unauthenticated notes, which are not persisted
        // before the transaction succeeds) are tracked from this point on, so records for them
        // are built from the executed transaction's inputs.
        let consumed_note_ids =
            executed_tx.tx_inputs().input_notes().iter().map(InputNote::id).collect();

        let consumed_notes =
            self.store.get_input_notes(NoteFilter::List(consumed_note_ids)).await?;

        let tracked_note_ids =
            consumed_notes.iter().filter_map(InputNoteRecord::id).collect::<BTreeSet<_>>();

        for input_note in executed_tx.tx_inputs().input_notes() {
            if !tracked_note_ids.contains(&input_note.id()) {
                let mut input_note_record = InputNoteRecord::from(input_note.clone());
                input_note_record.consumed_locally(
                    executed_tx.account_id(),
                    executed_tx.id(),
                    current_timestamp,
                )?;
                new_input_notes.push(input_note_record);
            }
        }

        let mut updated_input_notes = vec![];

        for mut input_note_record in consumed_notes {
            if input_note_record.consumed_locally(
                executed_tx.account_id(),
                executed_tx.id(),
                current_timestamp,
            )? {
                updated_input_notes.push(input_note_record);
            }
        }

        Ok(NoteUpdateTracker::for_transaction_updates(
            new_input_notes,
            updated_input_notes,
            new_output_notes,
        ))
    }
}

// TRANSACTION STORE UPDATE ERROR
// ================================================================================================

/// Error returned by [`Client::get_transaction_store_update`] when building the store update
/// for a submitted transaction fails.
#[derive(Debug, thiserror::Error)]
pub enum TransactionStoreUpdateError {
    #[error("store error")]
    Store(#[from] StoreError),
    #[error("note screener error")]
    NoteScreener(#[from] NoteScreenerError),
    #[error("note record error")]
    NoteRecord(#[from] NoteRecordError),
}

// HELPERS
// ================================================================================================

#[derive(Clone, Copy, Debug)]
enum TransactionExecutionMode {
    Standard,
    #[cfg(feature = "dap")]
    Dap,
}

/// Data-store-independent state produced during transaction preparation.
pub(crate) struct PreparedTransaction {
    pub(crate) notes: InputNotes<InputNote>,
    pub(crate) output_recipients: Vec<NoteRecipient>,
    pub(crate) future_notes: Vec<(NoteDetails, NoteTag)>,
    pub(crate) tx_args: TransactionArgs,
    pub(crate) foreign_account_inputs: Vec<AccountInputs>,
    pub(crate) block_num: BlockNumber,
    pub(crate) ignore_invalid_notes: bool,
}

impl PreparedTransaction {
    /// Returns the scripts of the request's expected output notes. These must be registered on
    /// the executor's data store so output note creation can resolve them during execution.
    pub(crate) fn output_note_scripts(&self) -> impl Iterator<Item = NoteScript> + '_ {
        self.output_recipients.iter().map(|recipient| recipient.script().clone())
    }
}

/// Helper to get the account outgoing assets.
///
/// Any outgoing assets resulting from executing note scripts but not present in expected output
/// notes wouldn't be included.
fn get_outgoing_assets(
    transaction_request: &TransactionRequest,
) -> (BTreeMap<AccountId, u64>, Vec<NonFungibleAsset>) {
    // Get own notes assets
    let mut own_notes_assets = match transaction_request.script_template() {
        Some(TransactionScriptTemplate::SendNotes(notes)) => notes
            .iter()
            .map(|note| (note.id(), note.assets().clone()))
            .collect::<BTreeMap<_, _>>(),
        _ => BTreeMap::default(),
    };
    // Get transaction output notes assets
    let mut output_notes_assets = transaction_request
        .expected_output_own_notes()
        .into_iter()
        .map(|note| (note.id(), note.assets().clone()))
        .collect::<BTreeMap<_, _>>();

    // Merge with own notes assets and delete duplicates
    output_notes_assets.append(&mut own_notes_assets);

    // Create a map of the fungible and non-fungible assets in the output notes
    let outgoing_assets = output_notes_assets.values().flat_map(|note_assets| note_assets.iter());

    request::collect_assets(outgoing_assets)
}

/// Validates a transaction request against the supplied `account`. Faucets are currently
/// skipped; for non-faucets, defers to [`validate_basic_account_request`] for asset-balance
/// checks.
pub(super) fn validate_account_request(
    transaction_request: &TransactionRequest,
    account: &Account,
) -> Result<(), ClientError> {
    validate_fee_conversion_info_support(transaction_request, account)?;

    if account.code_interface().contains([FungibleFaucet::mint_and_send_root()]) {
        // TODO(SantiagoPittella): Add faucet validations.
        Ok(())
    } else {
        validate_basic_account_request(transaction_request, account)
    }
}

/// Verifies that the account can consume fee conversion info passed through the auth args.
///
/// Only the signature-based auth components read the auth args as conversion info (through
/// `miden::standards::fee`). On any other auth component the declared asset and rate would be
/// silently ignored and the fee paid in the chain's native asset, so the request is rejected here
/// instead.
fn validate_fee_conversion_info_support(
    transaction_request: &TransactionRequest,
    account: &Account,
) -> Result<(), ClientError> {
    if !transaction_request.declares_fee_conversion_info() {
        return Ok(());
    }

    let interface = AccountInterface::from_account(account);
    let auth_component = interface.auth_component();
    if matches!(
        auth_component,
        AccountComponentInterface::AuthSingleSig | AccountComponentInterface::AuthMultisig
    ) {
        return Ok(());
    }

    Err(ClientError::TransactionRequestError(
        TransactionRequestError::FeeConversionInfoUnsupported(auth_component.name()),
    ))
}

/// Verifies that every output note emitted directly by the transaction declares `account_id` as
/// its sender.
///
/// A note's sender is bound by the kernel to the account that emits it, and note scripts (e.g.
/// P2IDE reclaim) authorize on that field, so an output note declaring a foreign sender can never
/// be executed. Catching it here yields a clear, immediate error instead of a cryptic failure deep
/// in transaction script building.
fn validate_output_note_senders(
    transaction_request: &TransactionRequest,
    account_id: AccountId,
) -> Result<(), ClientError> {
    for note in transaction_request.expected_output_own_notes() {
        let sender = note.metadata().sender();
        if sender != account_id {
            return Err(ClientError::TransactionRequestError(
                TransactionRequestError::OutputNoteSenderMismatch {
                    expected: account_id,
                    actual: sender,
                },
            ));
        }
    }

    Ok(())
}

/// Ensures a transaction request is compatible with the current account state,
/// primarily by checking asset balances against the requested transfers.
fn validate_basic_account_request(
    transaction_request: &TransactionRequest,
    account: &Account,
) -> Result<(), ClientError> {
    // Get outgoing assets
    let (fungible_balance_map, non_fungible_set) = get_outgoing_assets(transaction_request);

    // Get incoming assets
    let (incoming_fungible_balance_map, incoming_non_fungible_balance_set) =
        transaction_request.incoming_assets();

    // Aggregate the account's fungible balance per faucet in one pass. A faucet's fungible asset
    // may occupy more than one callback-flag vault key, so all matching entries are summed.
    let mut available_fungible: BTreeMap<AccountId, u64> = BTreeMap::new();
    for asset in account.vault().assets() {
        if let Asset::Fungible(fungible) = asset {
            let balance = available_fungible.entry(fungible.faucet_id()).or_default();
            *balance = balance.saturating_add(fungible.amount().as_u64());
        }
    }

    // Check if the account balance plus incoming assets is greater than or equal to the
    // outgoing fungible assets
    for (faucet_id, amount) in fungible_balance_map {
        let account_asset_amount = available_fungible.get(&faucet_id).copied().unwrap_or(0);
        let incoming_balance = incoming_fungible_balance_map.get(&faucet_id).unwrap_or(&0);
        if account_asset_amount + incoming_balance < amount {
            return Err(ClientError::AssetError(AssetError::FungibleAssetAmountNotSufficient {
                minuend: account_asset_amount,
                subtrahend: amount,
            }));
        }
    }

    // Check if the account balance plus incoming assets is greater than or equal to the
    // outgoing non fungible assets
    for non_fungible in &non_fungible_set {
        match account.vault().has_non_fungible_asset(*non_fungible) {
            Ok(true) => (),
            Ok(false) => {
                // Check if the non fungible asset is in the incoming assets
                if !incoming_non_fungible_balance_set.contains(non_fungible) {
                    return Err(ClientError::TransactionRequestError(
                        TransactionRequestError::MissingNonFungibleAsset(non_fungible.faucet_id()),
                    ));
                }
            },
            _ => {
                return Err(ClientError::TransactionRequestError(
                    TransactionRequestError::MissingNonFungibleAsset(non_fungible.faucet_id()),
                ));
            },
        }
    }

    Ok(())
}

/// Fetches a foreign account's proof and details from the network, converts them into
/// [`AccountInputs`], and caches the returned code in the store for future requests.
///
/// # Errors
/// Fails if the account is private: the RPC does not return account details for them, causing
/// [`TransactionRequestError::ForeignAccountDataMissing`].
pub(crate) async fn fetch_public_account_inputs(
    store: &Arc<dyn Store>,
    rpc_api: &Arc<dyn NodeRpcClient>,
    account_id: AccountId,
    storage_requirements: AccountStorageRequirements,
    account_state_at: AccountStateAt,
) -> Result<AccountInputs, ClientError> {
    let known_code: Option<AccountCode> =
        store.get_foreign_account_code(vec![account_id]).await?.into_values().next();

    let vault = store
        .get_account_header(account_id)
        .await?
        .map_or(VaultFetch::Always, |(header, ..)| {
            VaultFetch::IfChangedFrom(header.vault_root())
        });

    let (block_num, mut account_proof) = rpc_api
        .get_account(
            account_id,
            GetAccountRequest::new()
                .with_storage(StorageMapFetch::Slots(storage_requirements.clone()))
                .at(account_state_at)
                .with_known_code(known_code)
                .with_vault(vault),
        )
        .await?;

    if let Some(details) = account_proof.details_mut() {
        rpc_api.resolve_oversize_vault(account_id, block_num, details).await?;
        rpc_api.resolve_oversize_storage_maps(account_id, block_num, details).await?;
    }

    let account_inputs = request::account_proof_into_inputs(account_proof, &storage_requirements)?;

    let _ = store
        .upsert_foreign_account_code(account_id, account_inputs.code().clone())
        .await
        .inspect_err(|err| {
            tracing::warn!(
                %account_id,
                %err,
                "Failed to persist foreign account code to store"
            );
        });

    Ok(account_inputs)
}

/// Extracts notes from [`RawOutputNotes`].
/// Used for:
/// - Checking the relevance of notes to save them as input notes.
/// - Validate hashes versus expected output notes after a transaction is executed.
pub fn notes_from_output(output_notes: &RawOutputNotes) -> impl Iterator<Item = &Note> {
    output_notes.iter().filter_map(|n| match n {
        RawOutputNote::Full(n) => Some(n),
        RawOutputNote::Partial(_) => None,
    })
}

/// Validates that the executed transaction's output recipients match what was expected in the
/// transaction request.
pub(crate) fn validate_executed_transaction(
    executed_transaction: &ExecutedTransaction,
    expected_output_recipients: &[NoteRecipient],
) -> Result<(), ClientError> {
    let tx_output_recipient_digests = executed_transaction
        .output_notes()
        .iter()
        .filter_map(|n| n.recipient().map(NoteRecipient::digest))
        .collect::<Vec<_>>();

    let missing_recipient_digest: Vec<Word> = expected_output_recipients
        .iter()
        .filter_map(|recipient| {
            (!tx_output_recipient_digests.contains(&recipient.digest()))
                .then_some(recipient.digest())
        })
        .collect();

    if !missing_recipient_digest.is_empty() {
        return Err(ClientError::MissingOutputRecipients(missing_recipient_digest));
    }

    Ok(())
}

// TESTS
// ================================================================================================

#[cfg(test)]
mod tests {
    use alloc::vec;

    use miden_protocol::Word;
    use miden_protocol::account::auth::AuthSecretKey;
    use miden_protocol::account::{AccountBuilder, AccountComponent, AccountId, AccountType};
    use miden_protocol::asset::FungibleAsset;
    use miden_protocol::crypto::rand::RandomCoin;
    use miden_protocol::note::{Note, NoteType};
    use miden_protocol::testing::account_id::{
        ACCOUNT_ID_PRIVATE_FUNGIBLE_FAUCET,
        ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE,
        ACCOUNT_ID_SENDER,
    };
    use miden_standards::account::AccountBuilderSchemaCommitmentExt;
    use miden_standards::account::auth::{Approver, AuthSingleSig, FeeConversionInfo, NoAuth};
    use miden_standards::account::wallets::BasicWallet;
    use miden_standards::note::P2idNote;

    use super::{
        Account,
        AccountComponentInterface,
        TransactionRequest,
        TransactionRequestBuilder,
        validate_fee_conversion_info_support,
        validate_output_note_senders,
    };
    use crate::ClientError;
    use crate::auth::AuthSchemeId;
    use crate::transaction::TransactionRequestError;

    fn own_note_with_sender(sender: AccountId) -> Note {
        let faucet_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_FUNGIBLE_FAUCET).unwrap();
        let target_id =
            AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE).unwrap();
        let mut rng = RandomCoin::new(Word::default());

        P2idNote::builder()
            .sender(sender)
            .target(target_id)
            .asset(FungibleAsset::new(faucet_id, 100).unwrap())
            .note_type(NoteType::Public)
            .generate_serial_number(&mut rng)
            .build()
            .expect("note creation failed")
            .into()
    }

    #[test]
    fn output_note_with_foreign_sender_is_rejected() {
        let account_id =
            AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE).unwrap();
        let foreign_sender = AccountId::try_from(ACCOUNT_ID_SENDER).unwrap();
        assert_ne!(account_id, foreign_sender);

        let request = TransactionRequestBuilder::new()
            .own_output_notes(vec![own_note_with_sender(foreign_sender)])
            .build()
            .unwrap();

        let err = validate_output_note_senders(&request, account_id).unwrap_err();
        match err {
            ClientError::TransactionRequestError(
                TransactionRequestError::OutputNoteSenderMismatch { expected, actual },
            ) => {
                assert_eq!(expected, account_id);
                assert_eq!(actual, foreign_sender);
            },
            other => panic!("expected OutputNoteSenderMismatch, got {other:?}"),
        }
    }

    #[test]
    fn output_note_with_matching_sender_is_accepted() {
        let account_id =
            AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE).unwrap();

        let request = TransactionRequestBuilder::new()
            .own_output_notes(vec![own_note_with_sender(account_id)])
            .build()
            .unwrap();

        validate_output_note_senders(&request, account_id).unwrap();
    }

    #[test]
    fn request_without_own_output_notes_is_accepted() {
        let account_id =
            AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE).unwrap();
        let faucet_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_FUNGIBLE_FAUCET).unwrap();

        // A consume-only request (input note, no own output notes) must pass the sender check.
        let request = TransactionRequestBuilder::new()
            .input_notes(vec![(own_note_with_sender(faucet_id), None)])
            .build()
            .unwrap();

        validate_output_note_senders(&request, account_id).unwrap();
    }

    /// Builds an account carrying `auth_component` and a basic wallet.
    fn account_with_auth(auth_component: impl Into<AccountComponent>) -> Account {
        AccountBuilder::new([7u8; 32])
            .account_type(AccountType::Public)
            .with_component(auth_component)
            .with_component(BasicWallet)
            .build_with_schema_commitment()
            .expect("account creation failed")
    }

    fn fee_conversion_request() -> TransactionRequest {
        let faucet_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_FUNGIBLE_FAUCET).unwrap();

        TransactionRequestBuilder::new()
            .fee_conversion_info(FeeConversionInfo::one_to_one(faucet_id), Word::default())
            .build()
            .unwrap()
    }

    #[test]
    fn fee_conversion_info_is_accepted_by_a_signature_authenticated_account() {
        let key = AuthSecretKey::new_falcon512_poseidon2();
        let auth = AuthSingleSig::new(Approver::new(
            key.public_key().to_commitment(),
            AuthSchemeId::Falcon512Poseidon2,
        ));

        validate_fee_conversion_info_support(&fee_conversion_request(), &account_with_auth(auth))
            .unwrap();
    }

    #[test]
    fn fee_conversion_info_is_rejected_by_an_account_that_cannot_read_it() {
        let account = account_with_auth(NoAuth);

        let err = validate_fee_conversion_info_support(&fee_conversion_request(), &account)
            .expect_err("NoAuth does not read the auth args");
        match err {
            ClientError::TransactionRequestError(
                TransactionRequestError::FeeConversionInfoUnsupported(auth_component),
            ) => assert_eq!(auth_component, AccountComponentInterface::AuthNoAuth.name()),
            other => panic!("expected FeeConversionInfoUnsupported, got {other:?}"),
        }
    }

    #[test]
    fn a_request_without_fee_conversion_info_skips_the_auth_component_check() {
        // `NoAuth` cannot read conversion info, but a request that declares none is unaffected.
        validate_fee_conversion_info_support(
            &TransactionRequestBuilder::new().build().unwrap(),
            &account_with_auth(NoAuth),
        )
        .unwrap();
    }
}