miden-client 0.15.2

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
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;

use miden_protocol::account::{
    Account,
    AccountDelta,
    AccountHeader,
    AccountId,
    AccountStorage,
    AccountStorageDelta,
    AccountVaultDelta,
    StorageMapKey,
    StorageSlotName,
};
use miden_protocol::asset::{Asset, AssetVault, AssetVaultKey};
use miden_protocol::block::{BlockHeader, BlockNumber};
use miden_protocol::crypto::merkle::mmr::{InOrderIndex, MmrPeaks};
use miden_protocol::errors::{AccountDeltaError, AccountError};
use miden_protocol::note::{NoteId, Nullifier};
use miden_protocol::transaction::TransactionId;
use miden_protocol::{Felt, Word};

use super::SyncSummary;
use crate::note::{NoteUpdateTracker, NoteUpdateType};
use crate::rpc::domain::account_vault::AccountVaultUpdate;
use crate::rpc::domain::storage_map::StorageMapUpdate;
use crate::rpc::domain::transaction::TransactionRecord as RpcTransactionRecord;
use crate::transaction::{DiscardCause, TransactionRecord, TransactionStatus};

// STATE SYNC UPDATE
// ================================================================================================

/// Contains all information needed to apply the update in the store after syncing with the node.
#[derive(Default)]
pub struct StateSyncUpdate {
    /// The block number of the last block that was synced.
    pub block_num: BlockNumber,
    /// New blocks, authentication nodes and MMR peaks.
    pub partial_blockchain_updates: PartialBlockchainUpdates,
    /// New and updated notes to be upserted in the store.
    pub note_updates: NoteUpdateTracker,
    /// Committed and discarded transactions after the sync.
    pub transaction_updates: TransactionUpdateTracker,
    /// Public account updates and mismatched private accounts after the sync.
    pub account_updates: AccountUpdates,
}

impl From<&StateSyncUpdate> for SyncSummary {
    fn from(value: &StateSyncUpdate) -> Self {
        let new_public_note_ids = value
            .note_updates
            .updated_input_notes()
            .filter_map(|note_update| {
                let note = note_update.inner();
                if let NoteUpdateType::Insert = note_update.update_type() {
                    note.id()
                } else {
                    None
                }
            })
            .collect();

        let committed_note_ids: BTreeSet<NoteId> = value
            .note_updates
            .updated_input_notes()
            .filter_map(|note_update| {
                let note = note_update.inner();
                // `InsertCommitted` is a previously-tracked expected note that just committed, so
                // it counts as committed (not as a newly-discovered note) even though it is
                // persisted via a full-row insert.
                if matches!(
                    note_update.update_type(),
                    NoteUpdateType::Update | NoteUpdateType::InsertCommitted
                ) && note.is_committed()
                {
                    note.id()
                } else {
                    None
                }
            })
            .chain(value.note_updates.updated_output_notes().filter_map(|note_update| {
                let note = note_update.inner();
                if let NoteUpdateType::Update = note_update.update_type() {
                    note.is_committed().then_some(note.id())
                } else {
                    None
                }
            }))
            .collect();

        let consumed_note_ids: BTreeSet<NoteId> =
            value.note_updates.consumed_input_note_ids().collect();

        SyncSummary::new(
            value.block_num,
            new_public_note_ids,
            // Populated by Client::sync_state from the Note Transport Layer fetch.
            Vec::new(),
            committed_note_ids.into_iter().collect(),
            consumed_note_ids.into_iter().collect(),
            value
                .account_updates
                .updated_public_accounts()
                .iter()
                .map(PublicAccountUpdate::id)
                .collect(),
            value
                .account_updates
                .mismatched_private_accounts()
                .iter()
                .map(|(id, _)| *id)
                .collect(),
            value.transaction_updates.committed_transactions().map(|t| t.id).collect(),
        )
    }
}

/// Contains all the partial blockchain information that needs to be added in the client's store
/// after a sync: block headers, authentication nodes and the MMR peaks at the new sync height.
#[derive(Debug, Clone, Default)]
pub struct PartialBlockchainUpdates {
    /// New block headers to be stored, keyed by block number. The value contains the block
    /// header and a flag indicating whether the block contains notes relevant to the client.
    block_headers: BTreeMap<BlockNumber, (BlockHeader, bool)>,
    /// New authentication nodes that are meant to be stored in order to authenticate block
    /// headers.
    new_authentication_nodes: Vec<(InOrderIndex, Word)>,
    /// MMR peaks at the new sync height.
    pub new_peaks: MmrPeaks,
}

impl PartialBlockchainUpdates {
    /// Adds or updates a block header in this [`PartialBlockchainUpdates`].
    ///
    /// If the block header already exists (same block number), the `has_client_notes` flag is
    /// OR-ed. Otherwise a new entry is added.
    pub fn insert(
        &mut self,
        block_header: BlockHeader,
        has_client_notes: bool,
        new_authentication_nodes: Vec<(InOrderIndex, Word)>,
    ) {
        self.block_headers
            .entry(block_header.block_num())
            .and_modify(|(_, existing_has_notes)| {
                *existing_has_notes |= has_client_notes;
            })
            .or_insert((block_header, has_client_notes));

        self.new_authentication_nodes.extend(new_authentication_nodes);
    }

    /// Returns the new block headers to be stored, along with a flag indicating whether the block
    /// contains notes that are relevant to the client.
    pub fn block_headers(&self) -> impl Iterator<Item = &(BlockHeader, bool)> {
        self.block_headers.values()
    }

    /// Returns the new authentication nodes that are meant to be stored in order to authenticate
    /// block headers.
    pub fn new_authentication_nodes(&self) -> &[(InOrderIndex, Word)] {
        &self.new_authentication_nodes
    }
}

/// Contains transaction changes to apply to the store.
#[derive(Default)]
pub struct TransactionUpdateTracker {
    /// Transactions that were committed in the block.
    transactions: BTreeMap<TransactionId, TransactionRecord>,
    /// Nullifier-to-account mappings from external transactions by tracked accounts.
    external_nullifier_accounts: BTreeMap<Nullifier, AccountId>,
}

impl TransactionUpdateTracker {
    /// Creates a new [`TransactionUpdateTracker`]
    pub fn new(transactions: Vec<TransactionRecord>) -> Self {
        let transactions =
            transactions.into_iter().map(|tx| (tx.id, tx)).collect::<BTreeMap<_, _>>();

        Self {
            transactions,
            external_nullifier_accounts: BTreeMap::new(),
        }
    }

    /// Returns a reference to committed transactions.
    pub fn committed_transactions(&self) -> impl Iterator<Item = &TransactionRecord> {
        self.transactions
            .values()
            .filter(|tx| matches!(tx.status, TransactionStatus::Committed { .. }))
    }

    /// Returns a reference to discarded transactions.
    pub fn discarded_transactions(&self) -> impl Iterator<Item = &TransactionRecord> {
        self.transactions
            .values()
            .filter(|tx| matches!(tx.status, TransactionStatus::Discarded(_)))
    }

    /// Returns a mutable reference to pending transactions in the tracker.
    fn mutable_pending_transactions(&mut self) -> impl Iterator<Item = &mut TransactionRecord> {
        self.transactions
            .values_mut()
            .filter(|tx| matches!(tx.status, TransactionStatus::Pending))
    }

    /// Returns transaction IDs of all transactions that have been updated.
    pub fn updated_transaction_ids(&self) -> impl Iterator<Item = TransactionId> {
        self.committed_transactions()
            .chain(self.discarded_transactions())
            .map(|tx| tx.id)
    }

    /// Returns the account ID that consumed the given nullifier in an external transaction, if
    /// available.
    pub fn external_nullifier_account(&self, nullifier: &Nullifier) -> Option<AccountId> {
        self.external_nullifier_accounts.get(nullifier).copied()
    }

    /// Applies the necessary state transitions to the [`TransactionUpdateTracker`] when a
    /// transaction is included in a block.
    pub fn apply_transaction_inclusion(&mut self, record: &RpcTransactionRecord, timestamp: u64) {
        let header = &record.transaction_header;
        let account_id = header.account_id();

        if let Some(transaction) = self.transactions.get_mut(&header.id()) {
            transaction.commit_transaction(record.block_num, timestamp);
            return;
        }

        // Fallback for transactions with unauthenticated input notes: the node
        // authenticates these notes during processing, which changes the transaction
        // ID. Match by account ID and pre-transaction state instead.
        if let Some(transaction) = self.transactions.values_mut().find(|tx| {
            tx.details.account_id == account_id
                && tx.details.init_account_state == header.initial_state_commitment()
        }) {
            transaction.commit_transaction(record.block_num, timestamp);
            return;
        }

        // No local transaction matched. This is an external transaction by a tracked account.
        // Record the nullifier→account mappings so we can attribute note consumption to tracked
        // accounts during nullifier processing.
        for commitment in header.input_notes().iter() {
            self.external_nullifier_accounts.insert(commitment.nullifier(), account_id);
        }
    }

    /// Applies the necessary state transitions to the [`TransactionUpdateTracker`] when a the sync
    /// height of the client is updated. This may result in stale or expired transactions.
    pub fn apply_sync_height_update(
        &mut self,
        new_sync_height: BlockNumber,
        tx_discard_delta: Option<u32>,
    ) {
        if let Some(tx_discard_delta) = tx_discard_delta {
            self.discard_transaction_with_predicate(
                |transaction| {
                    transaction.details.submission_height
                        < new_sync_height.checked_sub(tx_discard_delta).unwrap_or_default()
                },
                DiscardCause::Stale,
            );
        }

        // NOTE: we check for <= new_sync height because at this point we would have committed the
        // transaction otherwise
        self.discard_transaction_with_predicate(
            |transaction| transaction.details.expiration_block_num <= new_sync_height,
            DiscardCause::Expired,
        );
    }

    /// Applies the necessary state transitions to the [`TransactionUpdateTracker`] when a note is
    /// nullified. this may result in transactions being discarded because they were processing the
    /// nullified note.
    pub fn apply_input_note_nullified(&mut self, input_note_nullifier: Nullifier) {
        self.discard_transaction_with_predicate(
            |transaction| {
                // Check if the note was being processed by a local transaction that didn't end up
                // being committed so it should be discarded
                transaction
                    .details
                    .input_note_nullifiers
                    .contains(&input_note_nullifier.as_word())
            },
            DiscardCause::InputConsumed,
        );
    }

    /// Discards the local transaction that produced this now-superseded account state.
    pub fn apply_superseded_account_state(&mut self, superseded_account_state: Word) {
        self.discard_transaction_with_predicate(
            |transaction| transaction.details.final_account_state == superseded_account_state,
            DiscardCause::Superseded,
        );
    }

    /// Discards transactions that have the same initial account state as the provided one.
    pub fn apply_invalid_initial_account_state(&mut self, invalid_account_state: Word) {
        self.discard_transaction_with_predicate(
            |transaction| transaction.details.init_account_state == invalid_account_state,
            DiscardCause::DiscardedInitialState,
        );
    }

    /// Discards transactions that match the predicate and also applies the new invalid account
    /// states
    fn discard_transaction_with_predicate<F>(&mut self, predicate: F, discard_cause: DiscardCause)
    where
        F: Fn(&TransactionRecord) -> bool,
    {
        let mut new_invalid_account_states = vec![];

        for transaction in self.mutable_pending_transactions() {
            // Discard transactions, and also push the invalid account state if the transaction
            // got correctly discarded
            // NOTE: previous updates in a chain of state syncs could have committed a transaction,
            // so we need to check that `discard_transaction` returns `true` here (aka, it got
            // discarded from a valid state)
            if predicate(transaction) && transaction.discard_transaction(discard_cause) {
                new_invalid_account_states.push(transaction.details.final_account_state);
            }
        }

        for state in new_invalid_account_states {
            self.apply_invalid_initial_account_state(state);
        }
    }
}

// PUBLIC ACCOUNT UPDATE
// ================================================================================================

/// Update to a single tracked public account.
///
/// `StateSync` emits one of two variants depending on whether the node could return the account's
/// full state in a single response:
///
/// - [`PublicAccountUpdate::Full`] carries the new [`Account`] state directly (used when no storage
///   map is oversized and the vault fits in the response). The store applies it by replacing the
///   local state — no delta computation needed.
/// - [`PublicAccountUpdate::Delta`] carries a [`PublicAccountDelta`] payload (new header plus
///   incremental updates from `sync_storage_maps` and `sync_account_vault`, used when any part of
///   the account is oversized). The store calls [`PublicAccountDelta::compute_account_delta`] to
///   derive the [`AccountDelta`] to apply.
#[derive(Debug, Clone)]
pub enum PublicAccountUpdate {
    /// The account fits in a single proof response — the new full state is carried as-is.
    Full(Account),
    /// The account is oversized in some dimension. The new state must be reconstructed by
    /// replaying the carried incremental updates against the locally-stored state.
    Delta(PublicAccountDelta),
}

impl PublicAccountUpdate {
    /// Returns the account ID for this update.
    pub fn id(&self) -> AccountId {
        match self {
            Self::Full(account) => account.id(),
            Self::Delta(delta) => delta.id(),
        }
    }

    /// Returns the account nonce that this update advances the local state to.
    pub fn nonce(&self) -> Felt {
        match self {
            Self::Full(account) => account.nonce(),
            Self::Delta(delta) => delta.new_header().nonce(),
        }
    }
}

/// Incremental delta payload for a public account update.
///
/// Carries the new account header plus the per-block updates fetched from the node's incremental
/// endpoints (`sync_storage_maps` and `sync_account_vault`). The store derives the
/// [`AccountDelta`] to apply by replaying these updates against its locally-stored account state
/// via [`Self::compute_account_delta`].
#[derive(Debug, Clone)]
pub struct PublicAccountDelta {
    /// The new account header after applying these updates.
    new_header: AccountHeader,
    /// First block of the synced range (the client's previous sync height).
    block_from: BlockNumber,
    /// Last block of the synced range (the block at which `new_header` is observed).
    block_to: BlockNumber,
    /// New value-slot values from the `get_account` storage header. Value slots are always
    /// small enough to fit in the response.
    value_slot_updates: Vec<(StorageSlotName, Word)>,
    /// Per-block storage map updates from `sync_storage_maps`.
    storage_map_updates: Vec<StorageMapUpdate>,
    /// Per-block vault updates from `sync_account_vault`.
    vault_updates: Vec<AccountVaultUpdate>,
}

impl PublicAccountDelta {
    /// Creates a new [`PublicAccountDelta`].
    pub fn new(
        new_header: AccountHeader,
        block_from: BlockNumber,
        block_to: BlockNumber,
        value_slot_updates: Vec<(StorageSlotName, Word)>,
        storage_map_updates: Vec<StorageMapUpdate>,
        vault_updates: Vec<AccountVaultUpdate>,
    ) -> Self {
        Self {
            new_header,
            block_from,
            block_to,
            value_slot_updates,
            storage_map_updates,
            vault_updates,
        }
    }

    /// Returns the account ID this delta applies to.
    pub fn id(&self) -> AccountId {
        self.new_header.id()
    }

    /// Returns the new account header that this delta advances the local state to.
    pub fn new_header(&self) -> &AccountHeader {
        &self.new_header
    }

    /// Returns the first block of the synced range.
    pub fn block_from(&self) -> BlockNumber {
        self.block_from
    }

    /// Returns the names of the value slots referenced by this delta. The store can use this to
    /// load only the slots needed by [`Self::compute_account_delta`] instead of the full storage.
    pub fn value_slot_names(&self) -> Vec<StorageSlotName> {
        self.value_slot_updates.iter().map(|(name, _)| name.clone()).collect()
    }

    /// Returns the last block of the synced range.
    pub fn block_to(&self) -> BlockNumber {
        self.block_to
    }

    /// Computes the [`AccountDelta`] implied by this payload by replaying the carried
    /// incremental updates against the locally-stored account state.
    // TODO #2171:
    // skip building AccountDelta; have the store accept raw RPC updates directly.
    pub fn compute_account_delta(
        &self,
        local_header: &AccountHeader,
        local_storage: &AccountStorage,
        local_vault: &AssetVault,
    ) -> Result<AccountDelta, AccountDeltaError> {
        let old_nonce = local_header.nonce().as_canonical_u64();
        let new_nonce = self.new_header.nonce().as_canonical_u64();
        if new_nonce <= old_nonce {
            return Err(AccountDeltaError::AccountDeltaApplicationFailed {
                account_id: self.new_header.id(),
                source: AccountError::other(format!(
                    "node returned non-monotonic account nonce: local {old_nonce} >= new {new_nonce}"
                )),
            });
        }

        let storage_delta = replay_storage_updates(
            local_storage,
            &self.value_slot_updates,
            &self.storage_map_updates,
        )?;
        let vault_delta = replay_vault_updates(local_vault, &self.vault_updates)?;

        let nonce_delta = Felt::new(new_nonce - old_nonce).expect(
            "new_nonce was checked to be higher than old_nonce; should return a valid nonce",
        );

        AccountDelta::new(self.new_header.id(), storage_delta, vault_delta, nonce_delta)
    }
}

// DELTA REPLAY HELPERS
// ================================================================================================

/// Computes a storage delta by replaying incremental updates onto the locally-stored state.
fn replay_storage_updates(
    local_storage: &AccountStorage,
    value_slot_updates: &[(StorageSlotName, Word)],
    storage_map_updates: &[StorageMapUpdate],
) -> Result<AccountStorageDelta, AccountDeltaError> {
    let mut storage_delta = AccountStorageDelta::new();

    // Value slots: emit only the slots whose new value differs from local.
    for (slot_name, new_value) in value_slot_updates {
        let local_value = local_storage.get_item(slot_name).ok();
        if local_value.as_ref() != Some(new_value) {
            storage_delta.set_item(slot_name.clone(), *new_value)?;
        }
    }

    // Map slots: dedup updates per (slot, key) keeping the latest value by block number.
    let mut by_slot: BTreeMap<StorageSlotName, BTreeMap<StorageMapKey, Word>> = BTreeMap::new();
    let mut sorted: Vec<&StorageMapUpdate> = storage_map_updates.iter().collect();
    sorted.sort_by_key(|u| u.block_num);
    for update in sorted {
        by_slot
            .entry(update.slot_name.clone())
            .or_default()
            .insert(update.key, update.value);
    }
    for (slot_name, entries) in by_slot {
        for (key, value) in entries {
            storage_delta.set_map_item(slot_name.clone(), key, value)?;
        }
    }

    Ok(storage_delta)
}

/// Computes a vault delta by replaying incremental updates onto the locally-stored vault.
fn replay_vault_updates(
    local_vault: &AssetVault,
    vault_updates: &[AccountVaultUpdate],
) -> Result<AccountVaultDelta, AccountDeltaError> {
    let mut vault_delta = AccountVaultDelta::default();

    let mut final_vault: BTreeMap<AssetVaultKey, Asset> =
        local_vault.assets().map(|asset| (asset.vault_key(), asset)).collect();

    let mut sorted: Vec<&AccountVaultUpdate> = vault_updates.iter().collect();
    sorted.sort_by_key(|u| u.block_num);
    for update in sorted {
        match update.asset {
            Some(asset) => {
                final_vault.insert(update.vault_key, asset);
            },
            None => {
                final_vault.remove(&update.vault_key);
            },
        }
    }

    let local_assets: BTreeMap<AssetVaultKey, Asset> =
        local_vault.assets().map(|a| (a.vault_key(), a)).collect();
    for (key, final_asset) in &final_vault {
        match local_assets.get(key) {
            None => {
                vault_delta.add_asset(*final_asset)?;
            },
            Some(local_asset) if local_asset != final_asset => {
                vault_delta.remove_asset(*local_asset)?;
                vault_delta.add_asset(*final_asset)?;
            },
            _ => {},
        }
    }
    for (key, local_asset) in &local_assets {
        if !final_vault.contains_key(key) {
            vault_delta.remove_asset(*local_asset)?;
        }
    }

    Ok(vault_delta)
}

// ACCOUNT UPDATES
// ================================================================================================

/// Contains account changes to apply to the store after a sync request.
#[derive(Debug, Clone, Default)]
#[allow(clippy::struct_field_names)]
pub struct AccountUpdates {
    /// Updated public accounts, either as full state replacements or incremental deltas.
    updated_public_accounts: Vec<PublicAccountUpdate>,
    /// Account commitments received from the network that don't match the currently
    /// locally-tracked state of the private accounts.
    ///
    /// These updates may represent a stale account commitment (meaning that the latest local state
    /// hasn't been committed). If this is not the case, the account may be locked until the state
    /// is restored manually.
    mismatched_private_accounts: Vec<(AccountId, Word)>,
}

impl AccountUpdates {
    /// Creates a new instance of `AccountUpdates`.
    pub fn new(
        updated_public_accounts: Vec<PublicAccountUpdate>,
        mismatched_private_accounts: Vec<(AccountId, Word)>,
    ) -> Self {
        Self {
            updated_public_accounts,
            mismatched_private_accounts,
        }
    }

    /// Returns the updated public accounts.
    pub fn updated_public_accounts(&self) -> &[PublicAccountUpdate] {
        &self.updated_public_accounts
    }

    /// Returns the mismatched private accounts.
    pub fn mismatched_private_accounts(&self) -> &[(AccountId, Word)] {
        &self.mismatched_private_accounts
    }

    pub fn extend(&mut self, other: AccountUpdates) {
        self.updated_public_accounts.extend(other.updated_public_accounts);
        self.mismatched_private_accounts.extend(other.mismatched_private_accounts);
    }
}

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

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

    use miden_protocol::account::{StorageMapKey, StorageSlot};
    use miden_protocol::asset::{Asset, AssetVault, FungibleAsset};
    use miden_protocol::testing::account_id::{
        ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET,
        ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE,
    };

    use super::*;

    fn account_id() -> AccountId {
        ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE.try_into().unwrap()
    }

    fn faucet_id() -> AccountId {
        ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET.try_into().unwrap()
    }

    fn slot_name(name: &str) -> StorageSlotName {
        StorageSlotName::new(name).unwrap()
    }

    fn map_key(n: u64) -> StorageMapKey {
        StorageMapKey::from_raw(word(n))
    }

    fn word(n: u64) -> Word {
        Word::from([
            Felt::new_unchecked(n),
            Felt::new_unchecked(0),
            Felt::new_unchecked(0),
            Felt::new_unchecked(0),
        ])
    }

    fn fungible(amount: u64) -> Asset {
        Asset::Fungible(FungibleAsset::new(faucet_id(), amount).unwrap())
    }

    fn header_with_nonce(nonce: u64) -> AccountHeader {
        AccountHeader::new(
            account_id(),
            Felt::new(nonce).expect("test nonce must be a valid Felt"),
            Word::default(),
            Word::default(),
            Word::default(),
        )
    }

    fn empty_payload(new_header: AccountHeader) -> PublicAccountDelta {
        PublicAccountDelta::new(
            new_header,
            BlockNumber::from(0u32),
            BlockNumber::from(1u32),
            vec![],
            vec![],
            vec![],
        )
    }

    // REPLAY STORAGE UPDATES
    // --------------------------------------------------------------------------------------------

    #[test]
    fn replay_storage_empty_inputs_returns_empty_delta() {
        let storage = AccountStorage::new(vec![]).unwrap();
        let delta = replay_storage_updates(&storage, &[], &[]).unwrap();
        assert!(delta.is_empty());
    }

    #[test]
    fn replay_storage_value_slot_changed_emits_delta() {
        let value_slot = slot_name("miden::test::value");
        let storage =
            AccountStorage::new(vec![StorageSlot::with_value(value_slot.clone(), word(1))])
                .unwrap();

        let delta =
            replay_storage_updates(&storage, &[(value_slot.clone(), word(2))], &[]).unwrap();

        let entry = delta.get(&value_slot).expect("delta should contain value slot");
        assert_eq!(entry.clone().unwrap_value(), word(2));
    }

    #[test]
    fn replay_storage_value_slot_unchanged_is_skipped() {
        let value_slot = slot_name("miden::test::value");
        let storage =
            AccountStorage::new(vec![StorageSlot::with_value(value_slot.clone(), word(1))])
                .unwrap();

        let delta =
            replay_storage_updates(&storage, &[(value_slot.clone(), word(1))], &[]).unwrap();

        assert!(delta.is_empty());
    }

    #[test]
    fn replay_storage_map_dedup_keeps_latest_block_per_key() {
        let map_slot = slot_name("miden::test::map");
        let storage =
            AccountStorage::new(vec![StorageSlot::with_empty_map(map_slot.clone())]).unwrap();

        let key = map_key(42);
        let updates = vec![
            StorageMapUpdate {
                block_num: BlockNumber::from(1u32),
                slot_name: map_slot.clone(),
                key,
                value: word(100),
            },
            StorageMapUpdate {
                block_num: BlockNumber::from(3u32),
                slot_name: map_slot.clone(),
                key,
                value: word(300),
            },
            StorageMapUpdate {
                block_num: BlockNumber::from(2u32),
                slot_name: map_slot.clone(),
                key,
                value: word(200),
            },
        ];

        let delta = replay_storage_updates(&storage, &[], &updates).unwrap();

        let map_delta = delta.get(&map_slot).expect("delta should contain map slot").clone();
        let map = map_delta.unwrap_map();
        assert_eq!(map.entries().len(), 1);
        assert_eq!(*map.entries().values().next().unwrap(), word(300));
    }

    #[test]
    fn replay_storage_map_multiple_keys_in_same_slot_all_kept() {
        let map_slot = slot_name("miden::test::map");
        let storage =
            AccountStorage::new(vec![StorageSlot::with_empty_map(map_slot.clone())]).unwrap();

        let updates = vec![
            StorageMapUpdate {
                block_num: BlockNumber::from(1u32),
                slot_name: map_slot.clone(),
                key: map_key(1),
                value: word(100),
            },
            StorageMapUpdate {
                block_num: BlockNumber::from(2u32),
                slot_name: map_slot.clone(),
                key: map_key(2),
                value: word(200),
            },
        ];

        let delta = replay_storage_updates(&storage, &[], &updates).unwrap();
        let map = delta.get(&map_slot).unwrap().clone().unwrap_map();
        assert_eq!(map.entries().len(), 2);
    }

    // REPLAY VAULT UPDATES
    // --------------------------------------------------------------------------------------------

    #[test]
    fn replay_vault_empty_inputs_returns_empty_delta() {
        let vault = AssetVault::new(&[]).unwrap();
        let delta = replay_vault_updates(&vault, &[]).unwrap();
        assert!(delta.is_empty());
    }

    #[test]
    fn replay_vault_added_asset_emits_add() {
        let vault = AssetVault::new(&[]).unwrap();
        let asset = fungible(100);
        let updates = vec![AccountVaultUpdate {
            block_num: BlockNumber::from(1u32),
            asset: Some(asset),
            vault_key: asset.vault_key(),
        }];

        let delta = replay_vault_updates(&vault, &updates).unwrap();
        let added: Vec<_> = delta.added_assets().collect();
        assert_eq!(added, vec![asset]);
        assert_eq!(delta.removed_assets().count(), 0);
    }

    #[test]
    fn replay_vault_removed_asset_emits_remove() {
        let asset = fungible(100);
        let vault = AssetVault::new(&[asset]).unwrap();
        let updates = vec![AccountVaultUpdate {
            block_num: BlockNumber::from(1u32),
            asset: None,
            vault_key: asset.vault_key(),
        }];

        let delta = replay_vault_updates(&vault, &updates).unwrap();
        let removed: Vec<_> = delta.removed_assets().collect();
        assert_eq!(removed, vec![asset]);
        assert_eq!(delta.added_assets().count(), 0);
    }

    #[test]
    fn replay_vault_replace_asset_emits_net_diff() {
        let asset_a = fungible(100);
        let asset_b = fungible(150);
        let vault = AssetVault::new(&[asset_a]).unwrap();
        let updates = vec![AccountVaultUpdate {
            block_num: BlockNumber::from(1u32),
            asset: Some(asset_b),
            vault_key: asset_b.vault_key(),
        }];

        let delta = replay_vault_updates(&vault, &updates).unwrap();
        let added: Vec<_> = delta.added_assets().collect();
        assert_eq!(added, vec![fungible(50)]);
        assert_eq!(delta.removed_assets().count(), 0);
    }

    #[test]
    fn replay_vault_dedup_keeps_latest_block_per_key() {
        let vault = AssetVault::new(&[]).unwrap();
        let asset_v1 = fungible(100);
        let asset_v2 = fungible(200);
        let asset_v3 = fungible(300);
        let key = asset_v1.vault_key();

        let updates = vec![
            AccountVaultUpdate {
                block_num: BlockNumber::from(1u32),
                asset: Some(asset_v1),
                vault_key: key,
            },
            AccountVaultUpdate {
                block_num: BlockNumber::from(3u32),
                asset: Some(asset_v3),
                vault_key: key,
            },
            AccountVaultUpdate {
                block_num: BlockNumber::from(2u32),
                asset: Some(asset_v2),
                vault_key: key,
            },
        ];

        let delta = replay_vault_updates(&vault, &updates).unwrap();
        let added: Vec<_> = delta.added_assets().collect();
        assert_eq!(added, vec![asset_v3]);
    }

    #[test]
    fn replay_vault_added_then_removed_is_noop() {
        let vault = AssetVault::new(&[]).unwrap();
        let asset = fungible(100);
        let key = asset.vault_key();

        let updates = vec![
            AccountVaultUpdate {
                block_num: BlockNumber::from(1u32),
                asset: Some(asset),
                vault_key: key,
            },
            AccountVaultUpdate {
                block_num: BlockNumber::from(2u32),
                asset: None,
                vault_key: key,
            },
        ];

        let delta = replay_vault_updates(&vault, &updates).unwrap();
        assert!(delta.is_empty());
    }

    // COMPUTE ACCOUNT DELTA
    // --------------------------------------------------------------------------------------------

    #[test]
    fn compute_delta_happy_path_emits_nonce_delta() {
        let local_header = header_with_nonce(1);
        let local_storage = AccountStorage::new(vec![]).unwrap();
        let local_vault = AssetVault::new(&[]).unwrap();
        let payload = empty_payload(header_with_nonce(4));

        let delta = payload
            .compute_account_delta(&local_header, &local_storage, &local_vault)
            .unwrap();

        assert_eq!(delta.nonce_delta(), Felt::new_unchecked(3));
        assert!(delta.storage().is_empty());
        assert!(delta.vault().is_empty());
    }

    #[test]
    fn compute_delta_rejects_equal_nonce() {
        let local_header = header_with_nonce(5);
        let local_storage = AccountStorage::new(vec![]).unwrap();
        let local_vault = AssetVault::new(&[]).unwrap();
        let payload = empty_payload(header_with_nonce(5));

        let err = payload
            .compute_account_delta(&local_header, &local_storage, &local_vault)
            .unwrap_err();

        assert!(matches!(
            err,
            AccountDeltaError::AccountDeltaApplicationFailed {
                source: AccountError::Other { .. },
                ..
            }
        ));
    }

    #[test]
    fn compute_delta_rejects_decreasing_nonce() {
        let local_header = header_with_nonce(10);
        let local_storage = AccountStorage::new(vec![]).unwrap();
        let local_vault = AssetVault::new(&[]).unwrap();
        let payload = empty_payload(header_with_nonce(9));

        let err = payload
            .compute_account_delta(&local_header, &local_storage, &local_vault)
            .unwrap_err();

        assert!(matches!(
            err,
            AccountDeltaError::AccountDeltaApplicationFailed {
                source: AccountError::Other { .. },
                ..
            }
        ));
    }
}