miden-protocol 0.16.0-alpha.4

Core components of the Miden protocol
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
mod vault;

mod storage;
mod update_details;
use alloc::string::ToString;
use alloc::vec::Vec;

pub use storage::{
    AccountStoragePatch,
    StorageMapPatch,
    StorageMapPatchEntries,
    StoragePatchOperation,
    StorageSlotPatch,
    StorageValuePatch,
};
pub use update_details::AccountUpdateDetails;
pub use vault::AccountVaultPatch;

use crate::account::{Account, AccountCode, AccountId, AccountStorage};
use crate::asset::AssetVault;
use crate::crypto::SequentialCommit;
use crate::errors::{AccountError, AccountPatchError};
use crate::utils::serde::{
    ByteReader,
    ByteWriter,
    Deserializable,
    DeserializationError,
    Serializable,
};
use crate::{Felt, Word};

/// An [`AccountPatch`] describes the new absolute state of an account after one or more
/// transactions, in contrast to an [`AccountDelta`](crate::account::AccountDelta), which describes
/// the relative change.
///
/// For example, where a delta might say "remove 50 USDC from the vault", a patch says "the new
/// USDC balance is 100". This means a patch can be applied to compute the new account state
/// without loading the previous state and without invoking any custom asset compose logic (e.g.
/// merge/split procedures defined by the issuing faucet).
///
/// ## Full and Partial State Patches
///
/// The presence of the code in a patch signals if the patch is a _full state_ or _partial state_
/// patch. A full state patch must be converted into an [`Account`] object, while a partial state
/// patch must be applied to an existing [`Account`]. Because a full state patch reconstructs the
/// account from empty storage, its storage patch may only create slots, never update or remove
/// them; [`AccountPatch::new`] enforces this. A full state patch can only be the base of a
/// [`merge`](AccountPatch::merge), never the incoming patch (see its docs for the permutation
/// rules).
///
/// The patch represents updates to the account as follows:
/// - storage: an [`AccountStoragePatch`] containing the new values of changed storage slots and map
///   entries. Storage updates are already absolute per changed entry, so no dedicated patch type is
///   required for storage.
/// - vault: an [`AccountVaultPatch`] containing the new values of changed vault entries.
/// - nonce: the new (absolute) nonce of the account, in contrast to
///   [`AccountDelta::nonce_delta`](crate::account::AccountDelta::nonce_delta) which stores the
///   increment.
/// - code: an [`AccountCode`] for new accounts and `None` for others, with the same semantics as in
///   [`AccountDelta`](crate::account::AccountDelta).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountPatch {
    /// The ID of the account to which this patch applies.
    account_id: AccountId,
    /// The new values of changed storage slots and map entries.
    storage: AccountStoragePatch,
    /// The new values of changed vault entries.
    vault: AccountVaultPatch,
    /// The code of a new account (`Some`) or `None` for existing accounts.
    code: Option<AccountCode>,
    /// The new (absolute) nonce of the account.
    ///
    /// Should be set to `None` if the nonce wasn't updated.
    final_nonce: Option<Felt>,
}

impl AccountPatch {
    // CONSTANTS
    // --------------------------------------------------------------------------------------------

    /// Domain separator for the account patch commitment header.
    const DOMAIN: Felt = Felt::new_unchecked(2);

    // CONSTRUCTOR
    // --------------------------------------------------------------------------------------------

    /// Returns a new [`AccountPatch`] instantiated from the provided components.
    ///
    /// `final_nonce` must be `Some(non_zero_nonce)` if `storage` or `vault` contain any updates,
    /// and can be `None` only for empty patches.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `final_nonce` is `Some(Felt::ZERO)`. The tx kernel guarantees that an updated nonce is at
    ///   least one, so a zero nonce is never a valid post-tx-state. Empty patches must be
    ///   constructed with `None` instead.
    /// - `storage` or `vault` contain updates or code is present but `final_nonce` is `None`. The
    ///   tx kernel mandates that the nonce is incremented whenever account state changes.
    /// - `final_nonce` is 1 but `code` is not `Some`. Such a patch describes a new account and
    ///   should be convertible into a full [`Account`], so account code is required.
    pub fn new(
        account_id: AccountId,
        storage: AccountStoragePatch,
        vault: AccountVaultPatch,
        code: Option<AccountCode>,
        final_nonce: Option<Felt>,
    ) -> Result<Self, AccountPatchError> {
        // New nonce should never be zero as the tx kernel requires that the nonce must be
        // incremented to at least 1 in the account-creating transaction.
        // Patches that do not change the account (and the nonce) should pass `None`.
        if final_nonce.is_some_and(|final_nonce| final_nonce == Felt::ZERO) {
            return Err(AccountPatchError::FinalNonceIsZero);
        }

        // If account storage or vault were updated or code is present, the patch represents a state
        // change and so the nonce cannot be zero. The tx kernel mandates this (except it does not
        // consider code yet).
        if (!storage.is_empty() || !vault.is_empty() || code.is_some()) && final_nonce.is_none() {
            return Err(AccountPatchError::StateChangeRequiresNonceUpdate);
        }

        // Code must be provided for new accounts to be able to reconstruct the full Account.
        // New accounts are defined with nonce 0, but here we have the post-creation
        // final nonce, so we define new accounts as having final_nonce = 1.
        if final_nonce.is_some_and(|final_nonce| final_nonce == Felt::ONE) && code.is_none() {
            return Err(AccountPatchError::CodeMustBeProvidedForNewAccounts);
        }

        // A full state patch (carrying code) must reconstruct the account from empty storage, so it
        // may only create slots. An `Update` or `Remove` assumes the slot already exists and would
        // make reconstruction impossible.
        //
        // It is not required that the vault patch contains no remove operations, since valid
        // patches could be merged that add and remove an asset and so even a full state
        // patch can validly end up with remove operations.
        if code.is_some() && storage.contains_non_create_ops() {
            return Err(AccountPatchError::FullStatePatchContainsNonCreateStorageOp);
        }

        Ok(Self {
            account_id,
            storage,
            vault,
            code,
            final_nonce,
        })
    }

    /// Returns an empty patch for the provided account ID.
    pub fn empty(account_id: AccountId) -> Self {
        AccountPatch::new(
            account_id,
            AccountStoragePatch::default(),
            AccountVaultPatch::default(),
            None,
            None,
        )
        .expect("empty patch should be valid")
    }

    // PUBLIC MUTATORS
    // --------------------------------------------------------------------------------------------

    /// Merges the `other` [`AccountPatch`] into this one with patch semantics: entries present in
    /// `other` overwrite their counterparts in `self`, and `other.final_nonce`, if present,
    /// becomes the new final nonce.
    ///
    /// Both patches must apply to the same account, and `other.final_nonce` must be exactly one
    /// greater than `self.final_nonce` whenever both are set. The exact `+1` requirement reflects
    /// the tx kernel invariants that (a) a state-changing transaction must increment the nonce,
    /// and (b) the nonce can be incremented at most once per transaction. As a consequence
    /// the patch of the next transaction always lands at `self.final_nonce + 1`. The same nonce in
    /// both patches represents a fork and a nonce delta larger than 1 means a missed transaction.
    ///
    /// ## Full and Partial State
    ///
    /// The patches' full/partial state determines whether the merge is allowed. In short, the
    /// incoming patch (`other`) must never be a full state patch. In more detail:
    /// - `full_state + partial_state`: allowed. The full state (account-creation) patch is the base
    ///   and later partial patches layer on top of it.
    /// - `partial_state + partial_state`: allowed. Both are incremental updates.
    /// - `partial_state + full_state`: disallowed. A full state patch describes the account's
    ///   initial state, so it cannot follow an earlier (partial) patch.
    /// - `full_state + full_state`: disallowed. An account is created once, so two creation patches
    ///   cannot both apply.
    ///
    /// Empty patches are neutral and handled before this rule: merging into an empty `self` adopts
    /// `other`, and merging an empty `other` is a no-op.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - the two patches apply to different accounts.
    /// - both patches carry a final nonce and the nonce in `other` is not exactly one greater than
    ///   the nonce in `self`.
    /// - the incoming patch (`other`) is a full state patch (see permutations above).
    /// - a storage slot is used as different slot types in the two patches.
    pub fn merge(&mut self, other: Self) -> Result<(), AccountPatchError> {
        if self.account_id != other.account_id {
            return Err(AccountPatchError::AccountIdMismatch {
                expected: self.account_id,
                actual: other.account_id,
            });
        }

        match (self.final_nonce, other.final_nonce) {
            // Both patches are empty, nothing to merge.
            (None, None) => return Ok(()),

            // `self` is empty, so `other` becomes the merged result.
            (None, Some(_)) => {
                *self = other;
                return Ok(());
            },

            // `other` is empty, nothing to merge.
            (Some(_), None) => return Ok(()),

            (Some(current), Some(new)) => {
                if new != current + Felt::ONE {
                    return Err(AccountPatchError::NonceMustIncrementByOne { current, new });
                }
                self.final_nonce = Some(new);
            },
        }

        // A full state patch describes account creation and can only be the merge base (`self`),
        // never the incoming patch.
        if other.is_full_state() {
            return Err(AccountPatchError::MergeIncomingFullStatePatch);
        }

        self.storage.merge(other.storage)?;
        self.vault.merge(other.vault);

        // A full state `self` contains all of its slots as `Create`, so merging a partial patch
        // only ever updates a created slot (staying `Create`) or removes it (dropping the patch
        // entirely), preserving the invariant that full state patches contain only `Create`s.
        // Check that we have either a partial patch or only storage creates.
        debug_assert!(
            !self.is_full_state() || !self.storage.contains_non_create_ops(),
            "merging should never add storage updates or removals to a full state patch",
        );

        Ok(())
    }

    // PUBLIC ACCESSORS
    // --------------------------------------------------------------------------------------------

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

    /// Returns the storage updates of this patch.
    pub fn storage(&self) -> &AccountStoragePatch {
        &self.storage
    }

    /// Returns the vault updates of this patch.
    pub fn vault(&self) -> &AccountVaultPatch {
        &self.vault
    }

    /// Returns a reference to the account code of this patch, if present.
    pub fn code(&self) -> Option<&AccountCode> {
        self.code.as_ref()
    }

    /// Returns the new (absolute) nonce of the account after this patch is applied, or `None` if
    /// the nonce wasn't updated.
    pub fn final_nonce(&self) -> Option<Felt> {
        self.final_nonce
    }

    /// Returns `true` if this patch is a "full state" patch, `false` otherwise, i.e. if it is a
    /// "partial state" patch.
    ///
    /// See the type-level docs for more on this distinction.
    pub fn is_full_state(&self) -> bool {
        // TODO(code_upgrades): Change this to another detection mechanism once we have code upgrade
        // support, at which point the presence of code may not be enough of an indication that a
        // patch can be converted to a full account.
        //
        // The presence of code alone is sufficient to identify a full state patch: the constructor
        // enforces that `code.is_some()` implies `final_nonce.is_some()` and that the storage patch
        // contains only `Create` ops, and `merge` preserves both, so a code-carrying patch always
        // reconstructs a full account.
        self.code.is_some()
    }

    /// Returns true if this account patch does not contain any vault or storage updates and the
    /// nonce wasn't updated.
    pub fn is_empty(&self) -> bool {
        // The check can be implemented by checking only the nonce, since the constructor validates
        // that non-empty storage or vault patches must increment the nonce.
        self.final_nonce.is_none()
    }

    /// Computes the commitment to the account patch.
    ///
    /// This is very similar to
    /// [`AccountDelta::to_commitment`](crate::account::AccountDelta::to_commitment). See its docs
    /// for the rationale, security aspects, and other details. The only differences between
    /// these are:
    /// - the patch includes the new nonce rather than the nonce delta.
    /// - The patch includes the new absolute asset values ([`AccountVaultPatch`]) while the delta
    ///   includes the relative asset changes
    ///   ([`AccountVaultDelta`](crate::account::AccountVaultDelta)).
    ///
    /// ## Computation
    ///
    /// The patch commitment is a sequential hash over a vector of field elements which starts out
    /// empty and is appended to in the following way. Whenever sorting is expected, it is that
    /// of a [`Word`].
    ///
    /// - Append `[[domain = 2, final_nonce, account_id_suffix, account_id_prefix], EMPTY_WORD]`,
    ///   where `account_id_{prefix,suffix}` are the prefix and suffix felts of the native account
    ///   id, `final_nonce` is the new nonce of the account, and `domain = 2` identifies the header
    ///   as the start of an account patch commitment (distinguishing it from a delta commitment,
    ///   which uses `domain = 1`).
    /// - Asset Patch
    ///   - For each asset whose value has changed compared to the initial state of the transaction,
    ///     including if it was removed, sorted by its asset ID:
    ///     - Append `[ASSET_ID, ASSET_VALUE_OR_EMPTY_WORD]` which are the key and either the value
    ///       of the asset (for updates) or the empty word (for removals).
    ///     - Append `[[domain = 4, num_changed_assets, 0, 0], 0, 0, 0, 0]`, where
    ///       `num_changed_assets` is the number of assets that were appended. Note that this is a
    ///       distinct domain from the delta asset domain (`3`), so an asset delta and an asset
    ///       patch can never produce the same commitment.
    /// - Storage Slots are sorted by slot ID and are iterated in this order. `patch_op` is the
    ///   [`StoragePatchOperation`](crate::account::StoragePatchOperation) of the slot patch and
    ///   `slot_id_{suffix, prefix}` is the identifier of the slot. For each slot, depending on its
    ///   slot type:
    ///   - Value Slot
    ///     - Append `[[domain = 5, patch_op, slot_id_suffix, slot_id_prefix], NEW_VALUE]` where
    ///       `NEW_VALUE` is the new value of the slot.
    ///   - Map Slot
    ///     - For each key-value pair, sorted by key, whose new value is different from the previous
    ///       value in the map:
    ///       - Append `[KEY, NEW_VALUE]`.
    ///     - The map trailer is constructed as `[[domain = 6, patch_op, slot_id_suffix,
    ///       slot_id_prefix], [num_changed_entries, 0, 0, 0]]`, where `num_changed_entries` is the
    ///       number of key-value pairs appended above. Whether the trailer is included depends on
    ///       `patch_op`:
    ///         - For
    ///           [`StoragePatchOperation::Create`](crate::account::StoragePatchOperation::Create),
    ///           the trailer is always included, since the slot's creation must be committed to even
    ///           when the map is created empty (`num_changed_entries == 0`).
    ///         - For
    ///           [`StoragePatchOperation::Update`](crate::account::StoragePatchOperation::Update),
    ///           the trailer is included only if `num_changed_entries != 0`. An update that changes
    ///           no entries is a no-op and is omitted entirely.
    ///         - For
    ///           [`StoragePatchOperation::Remove`](crate::account::StoragePatchOperation::Remove),
    ///           the trailer is always included with `num_changed_entries` set to zero, since the
    ///           number of removed entries is unknown.
    ///
    /// Headers for storage map slots and asset patches are appended rather than prepended since the
    /// tx kernel cannot efficiently get the number of changed entries before the iteration.
    pub fn to_commitment(&self) -> Word {
        <Self as SequentialCommit>::to_commitment(self)
    }
}

impl TryFrom<&AccountPatch> for Account {
    type Error = AccountError;

    /// Converts an [`AccountPatch`] into an [`Account`].
    ///
    /// Conceptually, this applies the patch onto an empty account. Only patches that fully
    /// describe an account (i.e. carry account code and a final nonce) can be converted; see
    /// [`AccountPatch`] for details.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The patch does not carry account code or a final nonce.
    /// - Applying the vault patch to an empty vault fails.
    /// - Applying the storage patch to empty storage fails.
    fn try_from(patch: &AccountPatch) -> Result<Self, Self::Error> {
        if !patch.is_full_state() {
            return Err(AccountError::PartialStatePatchToAccount);
        }

        // The constructor guarantees that a full state patch carries both code and a final nonce.
        let code = patch.code().cloned().expect("full state patch must carry code");
        let nonce = patch.final_nonce().expect("full state patch must carry final nonce");

        let mut vault = AssetVault::default();
        vault.apply_patch(patch.vault()).map_err(AccountError::AssetVaultUpdateError)?;

        // A full state patch consists of `Create` slot patches, so applying it to empty storage
        // reconstructs the account's full storage.
        let mut storage = AccountStorage::default();
        storage.apply_patch(patch.storage())?;

        Account::new(patch.id(), vault, storage, code, nonce, None)
    }
}

impl SequentialCommit for AccountPatch {
    type Commitment = Word;

    /// Reduces the patch to a sequence of field elements.
    ///
    /// See [AccountPatch::to_commitment()] for more details.
    fn to_elements(&self) -> Vec<Felt> {
        // The commitment to an empty patch is defined as the empty word.
        if self.is_empty() {
            return Vec::new();
        }

        // Minor optimization: At least 8 elements are always added.
        let mut elements = Vec::with_capacity(8);

        // ID and Nonce
        let final_nonce = self.final_nonce.expect("non-empty patches should have a new nonce set");
        elements.extend_from_slice(&[
            Self::DOMAIN,
            final_nonce,
            self.account_id.suffix(),
            self.account_id.prefix().as_felt(),
        ]);
        elements.extend_from_slice(Word::empty().as_elements());

        // Vault patch
        self.vault.append_patch_elements(&mut elements);

        // Storage Patch
        self.storage.append_patch_elements(&mut elements);

        debug_assert!(
            elements.len() % (2 * crate::WORD_SIZE) == 0,
            "expected elements to contain an even number of words, but it contained {} elements",
            elements.len()
        );

        elements
    }
}

impl Serializable for AccountPatch {
    fn write_into<W: ByteWriter>(&self, target: &mut W) {
        self.account_id.write_into(target);
        self.storage.write_into(target);
        self.vault.write_into(target);
        self.code.write_into(target);
        self.final_nonce.write_into(target);
    }

    fn get_size_hint(&self) -> usize {
        self.account_id.get_size_hint()
            + self.storage.get_size_hint()
            + self.vault.get_size_hint()
            + self.code.get_size_hint()
            + self.final_nonce.get_size_hint()
    }
}

impl Deserializable for AccountPatch {
    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
        let account_id = AccountId::read_from(source)?;
        let storage = AccountStoragePatch::read_from(source)?;
        let vault = AccountVaultPatch::read_from(source)?;
        let code = <Option<AccountCode>>::read_from(source)?;
        let final_nonce = <Option<Felt>>::read_from(source)?;

        Self::new(account_id, storage, vault, code, final_nonce)
            .map_err(|err| DeserializationError::InvalidValue(err.to_string()))
    }
}

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

#[cfg(test)]
mod tests {
    use assert_matches::assert_matches;
    use miden_core::serde::Deserializable;
    use rstest::rstest;

    use super::{AccountPatch, AccountVaultPatch};
    use crate::account::{
        Account,
        AccountCode,
        AccountId,
        AccountStoragePatch,
        StorageMapKey,
        StorageMapPatch,
        StorageSlotName,
        StorageSlotPatch,
        StorageValuePatch,
    };
    use crate::asset::{Asset, FungibleAsset, NonFungibleAsset};
    use crate::errors::{AccountError, AccountPatchError};
    use crate::testing::account_id::{
        ACCOUNT_ID_PRIVATE_SENDER,
        ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE,
    };
    use crate::utils::serde::Serializable;
    use crate::{Felt, Word};

    fn patch_id() -> AccountId {
        AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER).unwrap()
    }

    #[test]
    fn account_patch_serde() -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER).unwrap();
        let asset_0 = FungibleAsset::mock(100);
        let asset_1 = FungibleAsset::new(ACCOUNT_ID_PRIVATE_SENDER.try_into()?, 500_000)?.into();
        let asset_2 = NonFungibleAsset::mock(&[10]);
        let asset_3 = NonFungibleAsset::mock(&[20]);
        let vault_patch = AccountVaultPatch::with_assets([asset_0, asset_1, asset_2, asset_3]);

        let storage_patch = AccountStoragePatch::from_iters(
            [StorageSlotName::mock(1)],
            [
                (StorageSlotName::mock(2), Word::from([1, 1, 1, 1u32])),
                (StorageSlotName::mock(3), Word::from([1, 1, 0, 1u32])),
            ],
            [(
                StorageSlotName::mock(4),
                StorageMapPatch::from_iters(
                    [
                        StorageMapKey::from_array([1, 1, 1, 0]),
                        StorageMapKey::from_array([0, 1, 1, 1]),
                    ],
                    [(StorageMapKey::from_array([1, 1, 1, 1]), Word::from([1, 1, 1, 1u32]))],
                ),
            )],
        );

        assert_eq!(storage_patch.to_bytes().len(), storage_patch.get_size_hint());
        assert_eq!(vault_patch.to_bytes().len(), vault_patch.get_size_hint());

        let account_patch =
            AccountPatch::new(account_id, storage_patch, vault_patch, None, Some(Felt::from(5u8)))?;
        assert_eq!(AccountPatch::read_from_bytes(&account_patch.to_bytes())?, account_patch);
        assert_eq!(account_patch.to_bytes().len(), account_patch.get_size_hint());

        Ok(())
    }

    /// A `final_nonce` set to `Some(Felt::ZERO)` is rejected: the tx kernel guarantees the nonce of
    /// an updated account is at least one, so empty patches must pass `None` instead.
    #[test]
    fn account_patch_final_nonce_is_zero() -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;

        let error = AccountPatch::new(
            account_id,
            AccountStoragePatch::new(),
            AccountVaultPatch::default(),
            None,
            Some(Felt::ZERO),
        )
        .unwrap_err();

        assert_matches!(error, AccountPatchError::FinalNonceIsZero);

        Ok(())
    }

    /// A patch that updates storage, the vault, or carries code but leaves `final_nonce` as `None`
    /// is rejected, since any account state change requires the nonce to be incremented.
    #[rstest::rstest]
    #[case::non_empty_storage(
        AccountStoragePatch::from_iters([StorageSlotName::mock(1)], [], []),
        AccountVaultPatch::default(),
        None,
    )]
    #[case::non_empty_vault(
        AccountStoragePatch::new(),
        AccountVaultPatch::with_assets([FungibleAsset::mock(100)]),
        None,
    )]
    #[case::present_code(
        AccountStoragePatch::new(),
        AccountVaultPatch::default(),
        Some(AccountCode::mock())
    )]
    #[test]
    fn account_patch_with_state_change_requires_nonce_update(
        #[case] storage: AccountStoragePatch,
        #[case] vault: AccountVaultPatch,
        #[case] code: Option<AccountCode>,
    ) -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;

        let error = AccountPatch::new(account_id, storage, vault, code, None).unwrap_err();
        assert_matches!(error, AccountPatchError::StateChangeRequiresNonceUpdate);

        Ok(())
    }

    /// A patch for a newly created account (`final_nonce = Some(Felt::ONE)`) must include the
    /// account code, since otherwise the full account cannot be reconstructed from the patch.
    #[test]
    fn account_patch_new_account_requires_code() -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;

        let error = AccountPatch::new(
            account_id,
            AccountStoragePatch::new(),
            AccountVaultPatch::default(),
            None,
            Some(Felt::ONE),
        )
        .unwrap_err();
        assert_matches!(error, AccountPatchError::CodeMustBeProvidedForNewAccounts);

        // With the code provided, the same patch should succeed.
        AccountPatch::new(
            account_id,
            AccountStoragePatch::new(),
            AccountVaultPatch::default(),
            Some(AccountCode::mock()),
            Some(Felt::ONE),
        )?;

        Ok(())
    }

    /// A patch carrying account code and a final nonce can be converted to an [`Account`] and back,
    /// preserving all components.
    #[test]
    fn account_patch_roundtrip() -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;
        let code = AccountCode::mock();
        let asset = FungibleAsset::mock(42);

        let slot_name = StorageSlotName::mock(4);
        let slot_value = Word::from([1, 2, 3, 4u32]);

        // A full state patch is composed of `Create` slot patches.
        let storage_patch = AccountStoragePatch::from_entries([(
            slot_name.clone(),
            StorageSlotPatch::Value(StorageValuePatch::Create { value: slot_value }),
        )])?;

        let patch = AccountPatch::new(
            account_id,
            storage_patch,
            AccountVaultPatch::with_assets([asset]),
            Some(code.clone()),
            Some(Felt::ONE),
        )?;

        let account = Account::try_from(&patch)?;

        assert_eq!(account.id(), account_id);
        assert_eq!(account.code(), &code);
        assert_eq!(account.nonce(), Felt::ONE);
        assert_eq!(account.storage().get_item(&slot_name)?, slot_value);
        assert_eq!(account.vault().get(asset.id()), Some(asset));

        // Roundtrip back to a patch should reproduce the original.
        let roundtripped_patch = AccountPatch::try_from(account)?;
        assert_eq!(roundtripped_patch, patch);

        Ok(())
    }

    /// A patch lacking code cannot be converted to an [`Account`], whether or not a final nonce
    /// is present.
    #[rstest::rstest]
    #[case::missing_code(Some(Felt::from(2_u32)))]
    #[case::empty_patch(None)]
    #[test]
    fn account_try_from_partial_patch_fails(
        #[case] final_nonce: Option<Felt>,
    ) -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;

        let patch = AccountPatch::new(
            account_id,
            AccountStoragePatch::new(),
            AccountVaultPatch::default(),
            None,
            final_nonce,
        )?;
        assert_matches!(
            Account::try_from(&patch).unwrap_err(),
            AccountError::PartialStatePatchToAccount
        );

        Ok(())
    }

    /// A full state patch (carrying code) must only contain `Create` storage ops, since an `Update`
    /// or `Remove` could not be applied to the empty storage of a new account.
    #[rstest]
    #[case::update(
        AccountStoragePatch::builder().update_value(StorageSlotName::mock(1), Word::empty()).build()
    )]
    #[case::remove(
        AccountStoragePatch::builder().remove_value(StorageSlotName::mock(1)).build()
    )]
    fn account_patch_new_rejects_full_state_with_non_create_op(
        #[case] storage: AccountStoragePatch,
    ) -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;

        let error = AccountPatch::new(
            account_id,
            storage,
            AccountVaultPatch::default(),
            Some(AccountCode::mock()),
            Some(Felt::ONE),
        )
        .unwrap_err();
        assert_matches!(error, AccountPatchError::FullStatePatchContainsNonCreateStorageOp);

        Ok(())
    }

    /// A full state patch whose storage only creates slots can be reconstructed into an account.
    #[test]
    fn account_patch_full_state_with_create_reconstructs() -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;
        let code = AccountCode::mock();
        let created_slot = StorageSlotName::mock(1);
        let created_value = Word::from([7u32, 0, 0, 0]);

        let storage = AccountStoragePatch::builder()
            .create_value(created_slot.clone(), created_value)
            .build();

        let patch = AccountPatch::new(
            account_id,
            storage,
            AccountVaultPatch::default(),
            Some(code.clone()),
            Some(Felt::ONE),
        )?;

        assert!(patch.is_full_state());

        let account = Account::try_from(&patch)?;
        assert_eq!(account.code(), &code);
        assert_eq!(account.storage().get_item(&created_slot)?, created_value);

        Ok(())
    }

    // MERGE TESTS
    // ============================================================================================

    /// Returns a full-state patch with a single created value slot and the provided final
    /// nonce.
    fn full_patch(account_id: AccountId, final_nonce: u32) -> anyhow::Result<AccountPatch> {
        let storage_patch = AccountStoragePatch::builder()
            .create_value(StorageSlotName::mock(1), Word::from([1u32, 0, 0, 0]))
            .build();

        AccountPatch::new(
            account_id,
            storage_patch,
            AccountVaultPatch::default(),
            Some(AccountCode::mock()),
            Some(Felt::from(final_nonce)),
        )
        .map_err(Into::into)
    }

    /// Returns a partial-state patch with a single updated value slot and the provided final
    /// nonce.
    fn partial_patch(account_id: AccountId, final_nonce: u32) -> anyhow::Result<AccountPatch> {
        let storage = AccountStoragePatch::from_iters(
            [],
            [(StorageSlotName::mock(1), Word::from([1u32, 0, 0, 0]))],
            [],
        );
        AccountPatch::new(
            account_id,
            storage,
            AccountVaultPatch::default(),
            None,
            Some(Felt::from(final_nonce)),
        )
        .map_err(Into::into)
    }

    #[test]
    fn account_patch_merge_rejects_id_mismatch() -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;
        let other_account_id =
            AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE)?;

        let mut patch = partial_patch(account_id, 2)?;
        let other = partial_patch(other_account_id, 3)?;

        assert_matches!(
            patch.merge(other).unwrap_err(),
            AccountPatchError::AccountIdMismatch { expected, actual } => {
                assert_eq!(expected, account_id);
                assert_eq!(actual, other_account_id);
            }
        );

        Ok(())
    }

    /// A full state patch describes account creation and can only be the merge base, never the
    /// incoming patch, so merging it into a partial or full patch is rejected.
    #[rstest]
    #[case::partial_state_plus_full_state(
        partial_patch(patch_id(), 3)?
    )]
    #[case::full_state_plus_full_state(
        full_patch(patch_id(), 3)?
    )]
    fn account_patch_merge_rejects_incoming_full_state(
        #[case] mut patch: AccountPatch,
    ) -> anyhow::Result<()> {
        let other = full_patch(patch_id(), 4)?;
        assert_matches!(
            patch.merge(other).unwrap_err(),
            AccountPatchError::MergeIncomingFullStatePatch
        );

        Ok(())
    }

    #[rstest::rstest]
    #[case::equal(3, 3)]
    #[case::smaller(3, 2)]
    #[case::gap(3, 5)]
    fn account_patch_merge_rejects_non_incrementing_nonce(
        #[case] self_nonce: u32,
        #[case] other_nonce: u32,
    ) -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;
        let mut patch = partial_patch(account_id, self_nonce)?;
        let other = partial_patch(account_id, other_nonce)?;

        assert_matches!(
            patch.merge(other).unwrap_err(),
            AccountPatchError::NonceMustIncrementByOne { current, new } => {
                assert_eq!(current, Felt::from(self_nonce));
                assert_eq!(new, Felt::from(other_nonce));
            }
        );

        Ok(())
    }

    #[test]
    fn account_patch_merge_rejects_storage_slot_type_conflict() -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;
        let shared_slot = StorageSlotName::mock(7);

        let value_storage = AccountStoragePatch::from_iters(
            [],
            [(shared_slot.clone(), Word::from([9u32, 0, 0, 0]))],
            [],
        );
        let map_storage = AccountStoragePatch::from_iters(
            [],
            [],
            [(shared_slot.clone(), StorageMapPatch::from_iters([], []))],
        );

        let mut patch = AccountPatch::new(
            account_id,
            value_storage,
            AccountVaultPatch::default(),
            None,
            Some(Felt::from(2u32)),
        )?;
        let other = AccountPatch::new(
            account_id,
            map_storage,
            AccountVaultPatch::default(),
            None,
            Some(Felt::from(3u32)),
        )?;

        assert_matches!(
            patch.merge(other).unwrap_err(),
            AccountPatchError::StorageSlotUsedAsDifferentTypes(slot) => {
                assert_eq!(slot, shared_slot);
            }
        );

        Ok(())
    }

    #[test]
    fn account_patch_merge_overrides_vault_entry() -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;
        let asset_initial: Asset = FungibleAsset::mock(100);
        let asset_updated: Asset = FungibleAsset::mock(250);
        assert_eq!(asset_initial.id(), asset_updated.id());

        let mut patch = AccountPatch::new(
            account_id,
            AccountStoragePatch::new(),
            AccountVaultPatch::with_assets([asset_initial]),
            None,
            Some(Felt::from(2u32)),
        )?;
        let other = AccountPatch::new(
            account_id,
            AccountStoragePatch::new(),
            AccountVaultPatch::with_assets([asset_updated]),
            None,
            Some(Felt::from(3u32)),
        )?;

        patch.merge(other)?;

        assert_eq!(patch.vault().num_assets(), 1);
        assert_eq!(
            patch.vault().as_map().get(&asset_updated.id()).copied(),
            Some(asset_updated.to_value_word())
        );

        Ok(())
    }

    #[test]
    fn account_patch_merge_overrides_storage_value() -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;
        let slot_name = StorageSlotName::mock(1);
        let initial_value = Word::from([1u32, 0, 0, 0]);
        let updated_value = Word::from([2u32, 0, 0, 0]);

        let mut patch = AccountPatch::new(
            account_id,
            AccountStoragePatch::from_iters([], [(slot_name.clone(), initial_value)], []),
            AccountVaultPatch::default(),
            None,
            Some(Felt::from(2u32)),
        )?;
        let other = AccountPatch::new(
            account_id,
            AccountStoragePatch::from_iters([], [(slot_name.clone(), updated_value)], []),
            AccountVaultPatch::default(),
            None,
            Some(Felt::from(3u32)),
        )?;

        patch.merge(other)?;

        assert_eq!(patch.storage().num_slots(), 1);
        assert_eq!(patch.storage().updated_value(&slot_name), Some(updated_value));

        Ok(())
    }

    #[test]
    fn account_patch_merge_extends_storage_map() -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;
        let map_slot = StorageSlotName::mock(1);
        let key_self = StorageMapKey::from_array([1, 0, 0, 0]);
        let value_self = Word::from([10u32, 0, 0, 0]);
        let key_other = StorageMapKey::from_array([2, 0, 0, 0]);
        let value_other = Word::from([20u32, 0, 0, 0]);

        let mut patch = AccountPatch::new(
            account_id,
            AccountStoragePatch::from_iters(
                [],
                [],
                [(map_slot.clone(), StorageMapPatch::from_iters([], [(key_self, value_self)]))],
            ),
            AccountVaultPatch::default(),
            None,
            Some(Felt::from(2u32)),
        )?;
        let other = AccountPatch::new(
            account_id,
            AccountStoragePatch::from_iters(
                [],
                [],
                [(map_slot.clone(), StorageMapPatch::from_iters([], [(key_other, value_other)]))],
            ),
            AccountVaultPatch::default(),
            None,
            Some(Felt::from(3u32)),
        )?;

        patch.merge(other)?;

        assert_eq!(patch.storage().num_slots(), 1);
        assert_eq!(patch.storage().updated_map(&map_slot).unwrap().num_entries(), 2);
        assert_eq!(patch.storage().updated_map_item(&map_slot, &key_self), Some(value_self));
        assert_eq!(patch.storage().updated_map_item(&map_slot, &key_other), Some(value_other));

        Ok(())
    }

    /// A full state patch as the merge base, with a partial patch updating one of its created
    /// slots, stays a full state patch carrying only `Create` ops.
    #[test]
    fn account_patch_merge_full_base_with_partial_stays_full_state() -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;
        let code = AccountCode::mock();
        let slot_name = StorageSlotName::mock(1);
        let created_value = Word::from([1u32, 0, 0, 0]);
        let updated_value = Word::from([2u32, 0, 0, 0]);

        // Full state base: a created value slot, code and the account-creation nonce of 1.
        let mut patch = AccountPatch::new(
            account_id,
            AccountStoragePatch::builder()
                .create_value(slot_name.clone(), created_value)
                .build(),
            AccountVaultPatch::default(),
            Some(code.clone()),
            Some(Felt::ONE),
        )?;

        // Partial patch updating the same slot in the next transaction.
        let other = AccountPatch::new(
            account_id,
            AccountStoragePatch::builder()
                .update_value(slot_name.clone(), updated_value)
                .build(),
            AccountVaultPatch::default(),
            None,
            Some(Felt::from(2u32)),
        )?;

        patch.merge(other)?;

        assert!(patch.is_full_state());
        assert_eq!(patch.code(), Some(&code));
        assert_eq!(patch.final_nonce(), Some(Felt::from(2u32)));
        assert!(!patch.storage().contains_non_create_ops());
        assert_eq!(patch.storage().created_value(&slot_name), Some(updated_value));

        Ok(())
    }

    /// A + B_empty = A
    #[test]
    fn account_patch_merge_empty_other_is_noop() -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;
        let mut patch = partial_patch(account_id, 4)?;
        let snapshot = patch.clone();

        let empty = AccountPatch::empty(account_id);

        patch.merge(empty)?;
        assert_eq!(patch, snapshot);

        Ok(())
    }

    /// A_empty + B = B
    #[test]
    fn account_patch_merge_empty_self_adopts_other() -> anyhow::Result<()> {
        let account_id = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER)?;
        let mut empty = AccountPatch::empty(account_id);
        let other = partial_patch(account_id, 7)?;
        let expected = other.clone();

        empty.merge(other)?;
        assert_eq!(empty, expected);

        Ok(())
    }
}