near-primitives-core 0.37.3

This crate provides the core set of primitives used by other nearcore crates including near-primitives
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
use crate::hash::CryptoHash;
use crate::types::{Balance, Nonce, NonceIndex, StorageUsage};
use borsh::{BorshDeserialize, BorshSerialize};
pub use near_account_id as id;
use near_account_id::AccountId;
use near_schema_checker_lib::ProtocolSchema;
use std::borrow::Cow;
use std::io;

#[derive(
    BorshSerialize,
    BorshDeserialize,
    PartialEq,
    PartialOrd,
    Eq,
    Clone,
    Copy,
    Debug,
    Default,
    serde::Serialize,
    serde::Deserialize,
    ProtocolSchema,
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum AccountVersion {
    #[default]
    V1,
    V2,
}

/// Per account information stored in the state.
/// When introducing new version:
/// - introduce new AccountV[NewVersion] struct
/// - add new Account enum option V[NewVersion](AccountV[NewVersion])
/// - add new BorshVersionedAccount enum option V[NewVersion](AccountV[NewVersion])
/// - update SerdeAccount with newly added fields
/// - update serde ser/deser to properly handle conversions
#[derive(PartialEq, Eq, Debug, Clone, ProtocolSchema)]
pub enum Account {
    V1(AccountV1),
    V2(AccountV2),
}

// Original representation of the account.
#[derive(
    BorshSerialize,
    serde::Serialize,
    serde::Deserialize,
    PartialEq,
    Eq,
    Debug,
    Clone,
    ProtocolSchema,
)]
pub struct AccountV1 {
    /// The total not locked tokens.
    amount: Balance,
    /// The amount locked due to staking.
    locked: Balance,
    /// Hash of the code stored in the storage for this account.
    code_hash: CryptoHash,
    /// Storage used by the given account, includes account id, this struct, access keys and other data.
    storage_usage: StorageUsage,
}

#[allow(dead_code)]
impl AccountV1 {
    fn to_v2(&self) -> AccountV2 {
        AccountV2 {
            amount: self.amount,
            locked: self.locked,
            storage_usage: self.storage_usage,
            contract: AccountContract::from_local_code_hash(self.code_hash),
        }
    }
}

#[derive(
    BorshSerialize,
    BorshDeserialize,
    serde::Serialize,
    serde::Deserialize,
    PartialEq,
    Eq,
    Debug,
    Clone,
    ProtocolSchema,
)]
pub enum AccountContract {
    None,
    Local(CryptoHash),
    Global(CryptoHash),
    GlobalByAccount(AccountId),
}

impl AccountContract {
    pub fn local_code(&self) -> Option<CryptoHash> {
        match self {
            AccountContract::None
            | AccountContract::GlobalByAccount(_)
            | AccountContract::Global(_) => None,
            AccountContract::Local(hash) => Some(*hash),
        }
    }

    pub fn from_local_code_hash(code_hash: CryptoHash) -> AccountContract {
        if code_hash == CryptoHash::default() {
            AccountContract::None
        } else {
            AccountContract::Local(code_hash)
        }
    }

    pub fn is_none(&self) -> bool {
        matches!(self, Self::None)
    }

    pub fn is_some(&self) -> bool {
        !self.is_none()
    }

    pub fn is_local(&self) -> bool {
        matches!(self, Self::Local(_))
    }

    pub fn identifier_storage_usage(&self) -> u64 {
        match self {
            AccountContract::None | AccountContract::Local(_) => 0u64,
            AccountContract::Global(_) => 32u64,
            AccountContract::GlobalByAccount(id) => id.len() as u64,
        }
    }
}

#[derive(
    BorshSerialize,
    BorshDeserialize,
    serde::Serialize,
    serde::Deserialize,
    PartialEq,
    Eq,
    Debug,
    Clone,
    ProtocolSchema,
)]
pub struct AccountV2 {
    /// The total not locked tokens.
    amount: Balance,
    /// The amount locked due to staking.
    locked: Balance,
    /// Storage used by the given account, includes account id, this struct, access keys and other data.
    storage_usage: StorageUsage,
    /// Type of contract deployed to this account, if any.
    contract: AccountContract,
}

impl Account {
    /// Max number of bytes an account can have in its state (excluding contract code)
    /// before it is infeasible to delete.
    pub const MAX_ACCOUNT_DELETION_STORAGE_USAGE: u64 = 10_000;
    /// HACK: Using u128::MAX as a sentinel value, there are not enough tokens
    /// in total supply which makes it an invalid value. We use it to
    /// differentiate AccountVersion V1 from newer versions.
    const SERIALIZATION_SENTINEL: Balance = Balance::MAX;

    pub fn new(
        amount: Balance,
        locked: Balance,
        contract: AccountContract,
        storage_usage: StorageUsage,
    ) -> Self {
        match contract {
            AccountContract::None => Self::V1(AccountV1 {
                amount,
                locked,
                code_hash: CryptoHash::default(),
                storage_usage,
            }),
            AccountContract::Local(code_hash) => {
                Self::V1(AccountV1 { amount, locked, code_hash, storage_usage })
            }
            _ => Self::V2(AccountV2 { amount, locked, storage_usage, contract }),
        }
    }

    #[inline]
    pub fn amount(&self) -> Balance {
        match self {
            Self::V1(account) => account.amount,
            Self::V2(account) => account.amount,
        }
    }

    #[inline]
    pub fn locked(&self) -> Balance {
        match self {
            Self::V1(account) => account.locked,
            Self::V2(account) => account.locked,
        }
    }

    #[inline]
    pub fn contract(&self) -> Cow<'_, AccountContract> {
        match self {
            Self::V1(account) => {
                Cow::Owned(AccountContract::from_local_code_hash(account.code_hash))
            }
            Self::V2(account) => Cow::Borrowed(&account.contract),
        }
    }

    #[inline]
    pub fn storage_usage(&self) -> StorageUsage {
        match self {
            Self::V1(account) => account.storage_usage,
            Self::V2(account) => account.storage_usage,
        }
    }

    #[inline]
    pub fn version(&self) -> AccountVersion {
        match self {
            Self::V1(_) => AccountVersion::V1,
            Self::V2(_) => AccountVersion::V2,
        }
    }

    #[inline]
    pub fn global_contract_hash(&self) -> Option<CryptoHash> {
        match self {
            Self::V2(AccountV2 { contract: AccountContract::Global(hash), .. }) => Some(*hash),
            Self::V1(_) | Self::V2(_) => None,
        }
    }

    #[inline]
    pub fn global_contract_account_id(&self) -> Option<&AccountId> {
        match self {
            Self::V2(AccountV2 { contract: AccountContract::GlobalByAccount(account), .. }) => {
                Some(account)
            }
            Self::V1(_) | Self::V2(_) => None,
        }
    }

    #[inline]
    pub fn local_contract_hash(&self) -> Option<CryptoHash> {
        match self {
            Self::V1(account) => {
                AccountContract::from_local_code_hash(account.code_hash).local_code()
            }
            Self::V2(AccountV2 { contract: AccountContract::Local(hash), .. }) => Some(*hash),
            Self::V2(AccountV2 { contract: AccountContract::None, .. })
            | Self::V2(AccountV2 { contract: AccountContract::Global(_), .. })
            | Self::V2(AccountV2 { contract: AccountContract::GlobalByAccount(_), .. }) => None,
        }
    }

    #[inline]
    pub fn set_amount(&mut self, amount: Balance) {
        match self {
            Self::V1(account) => account.amount = amount,
            Self::V2(account) => account.amount = amount,
        }
    }

    #[inline]
    pub fn set_locked(&mut self, locked: Balance) {
        match self {
            Self::V1(account) => account.locked = locked,
            Self::V2(account) => account.locked = locked,
        }
    }

    #[inline]
    pub fn set_contract(&mut self, contract: AccountContract) {
        match self {
            Self::V1(account) => match contract {
                AccountContract::None | AccountContract::Local(_) => {
                    account.code_hash = contract.local_code().unwrap_or_default();
                }
                _ => {
                    let mut account_v2 = account.to_v2();
                    account_v2.contract = contract;
                    *self = Self::V2(account_v2);
                }
            },
            Self::V2(account) => {
                account.contract = contract;
            }
        }
    }

    #[inline]
    pub fn set_storage_usage(&mut self, storage_usage: StorageUsage) {
        match self {
            Self::V1(account) => account.storage_usage = storage_usage,
            Self::V2(account) => account.storage_usage = storage_usage,
        }
    }
}

/// Account representation for serde ser/deser that maintains both backward
/// and forward compatibility.
#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, Debug, Clone, ProtocolSchema)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
struct SerdeAccount {
    amount: Balance,
    locked: Balance,
    code_hash: CryptoHash,
    storage_usage: StorageUsage,
    /// Version of Account in re migrations and similar.
    #[serde(default)]
    version: AccountVersion,
    /// Global contracts fields
    #[serde(default, skip_serializing_if = "Option::is_none")]
    global_contract_hash: Option<CryptoHash>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    global_contract_account_id: Option<AccountId>,
}

impl<'de> serde::Deserialize<'de> for Account {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let account_data = SerdeAccount::deserialize(deserializer)?;
        if account_data.code_hash != CryptoHash::default()
            && (account_data.global_contract_hash.is_some()
                || account_data.global_contract_account_id.is_some())
        {
            return Err(serde::de::Error::custom(
                "An Account can't contain both a local and global contract",
            ));
        }
        if account_data.global_contract_hash.is_some()
            && account_data.global_contract_account_id.is_some()
        {
            return Err(serde::de::Error::custom(
                "An Account can't contain both types of global contracts",
            ));
        }

        match account_data.version {
            AccountVersion::V1 => Ok(Account::V1(AccountV1 {
                amount: account_data.amount,
                locked: account_data.locked,
                code_hash: account_data.code_hash,
                storage_usage: account_data.storage_usage,
            })),
            AccountVersion::V2 => {
                let contract = match account_data.global_contract_account_id {
                    Some(account_id) => AccountContract::GlobalByAccount(account_id),
                    None => match account_data.global_contract_hash {
                        Some(hash) => AccountContract::Global(hash),
                        None => AccountContract::from_local_code_hash(account_data.code_hash),
                    },
                };

                Ok(Account::V2(AccountV2 {
                    amount: account_data.amount,
                    locked: account_data.locked,
                    storage_usage: account_data.storage_usage,
                    contract,
                }))
            }
        }
    }
}

impl serde::Serialize for Account {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let version = self.version();
        let code_hash = self.local_contract_hash().unwrap_or_default();
        let repr = SerdeAccount {
            amount: self.amount(),
            locked: self.locked(),
            code_hash,
            storage_usage: self.storage_usage(),
            version,
            global_contract_hash: self.global_contract_hash(),
            global_contract_account_id: self.global_contract_account_id().cloned(),
        };
        repr.serialize(serializer)
    }
}

#[cfg(feature = "schemars")]
impl schemars::JsonSchema for Account {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "Account".to_string().into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        SerdeAccount::json_schema(generator)
    }
}

#[derive(BorshSerialize, BorshDeserialize)]
#[borsh(use_discriminant = true)]
#[repr(u8)]
enum BorshVersionedAccount {
    // V1 is not included since it is serialized directly without being wrapped in enum
    V2(AccountV2) = 0,
}

impl BorshDeserialize for Account {
    fn deserialize_reader<R: io::Read>(rd: &mut R) -> io::Result<Self> {
        // The first value of all Account serialization formats is a u128,
        // either a sentinel or a balance.
        let sentinel_or_amount = Balance::deserialize_reader(rd)?;
        if sentinel_or_amount == Account::SERIALIZATION_SENTINEL {
            let versioned_account = BorshVersionedAccount::deserialize_reader(rd)?;
            let account = match versioned_account {
                BorshVersionedAccount::V2(account_v2) => Account::V2(account_v2),
            };
            Ok(account)
        } else {
            // Legacy unversioned representation of Account
            let locked = Balance::deserialize_reader(rd)?;
            let code_hash = CryptoHash::deserialize_reader(rd)?;
            let storage_usage = StorageUsage::deserialize_reader(rd)?;

            Ok(Account::V1(AccountV1 {
                amount: sentinel_or_amount,
                locked,
                code_hash,
                storage_usage,
            }))
        }
    }
}

impl BorshSerialize for Account {
    fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
        let versioned_account = match self {
            Account::V1(account_v1) => return account_v1.serialize(writer),
            Account::V2(account_v2) => BorshVersionedAccount::V2(account_v2.clone()),
        };
        let sentinel = Account::SERIALIZATION_SENTINEL;
        BorshSerialize::serialize(&sentinel, writer)?;
        BorshSerialize::serialize(&versioned_account, writer)
    }
}

/// Access key provides limited access to an account. Each access key belongs to some account and
/// is identified by a unique (within the account) public key. One account may have large number of
/// access keys. Access keys allow to act on behalf of the account by restricting transactions
/// that can be issued.
/// `account_id,public_key` is a key in the state
#[derive(
    BorshSerialize,
    BorshDeserialize,
    PartialEq,
    Eq,
    Hash,
    Clone,
    Debug,
    serde::Serialize,
    serde::Deserialize,
    ProtocolSchema,
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct AccessKey {
    /// Nonce for this access key, used for tx nonce generation. When access key is created, nonce
    /// is set to `(block_height - 1) * 1e6` to avoid tx hash collision on access key re-creation.
    /// See <https://github.com/near/nearcore/issues/3779> for more details.
    pub nonce: Nonce,

    /// Defines permissions for this access key.
    pub permission: AccessKeyPermission,
}

impl AccessKey {
    pub const ACCESS_KEY_NONCE_RANGE_MULTIPLIER: u64 = 1_000_000;

    /// Borsh-serialized size of a Nonce value (u64), stored as gas key nonce trie values.
    pub const NONCE_VALUE_LEN: usize = std::mem::size_of::<Nonce>();

    /// Minimum borsh-serialized size of an AccessKey with a gas key permission.
    /// This is the size for GasKeyFullAccess (the smallest gas key variant).
    pub fn min_gas_key_borsh_len() -> usize {
        borsh::object_length(&Self::gas_key_full_access(0)).unwrap()
    }

    pub fn full_access() -> Self {
        Self { nonce: 0, permission: AccessKeyPermission::FullAccess }
    }

    pub fn gas_key_full_access(num_nonces: NonceIndex) -> Self {
        Self {
            nonce: 0,
            permission: AccessKeyPermission::GasKeyFullAccess(GasKeyInfo {
                balance: Balance::from_yoctonear(0),
                num_nonces,
            }),
        }
    }

    pub fn gas_key_function_call(
        num_nonces: NonceIndex,
        function_call_permission: FunctionCallPermission,
    ) -> Self {
        Self {
            nonce: 0,
            permission: AccessKeyPermission::GasKeyFunctionCall(
                GasKeyInfo { balance: Balance::from_yoctonear(0), num_nonces },
                function_call_permission,
            ),
        }
    }

    pub fn gas_key_info(&self) -> Option<&GasKeyInfo> {
        match &self.permission {
            AccessKeyPermission::GasKeyFunctionCall(gas_key_info, _)
            | AccessKeyPermission::GasKeyFullAccess(gas_key_info) => Some(gas_key_info),
            _ => None,
        }
    }

    pub fn gas_key_info_mut(&mut self) -> Option<&mut GasKeyInfo> {
        match &mut self.permission {
            AccessKeyPermission::GasKeyFunctionCall(gas_key_info, _)
            | AccessKeyPermission::GasKeyFullAccess(gas_key_info) => Some(gas_key_info),
            _ => None,
        }
    }
}

#[derive(
    BorshSerialize,
    BorshDeserialize,
    PartialEq,
    Eq,
    Hash,
    Clone,
    Debug,
    serde::Serialize,
    serde::Deserialize,
    ProtocolSchema,
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct GasKeyInfo {
    pub balance: Balance,
    pub num_nonces: NonceIndex,
}

impl GasKeyInfo {
    /// Maximum gas key balance that can be burned during key or account deletion.
    /// Deletion fails if the (sum of) gas key balance(s) exceeds this threshold.
    pub const MAX_BALANCE_TO_BURN: Balance = Balance::from_near(1);

    pub fn borsh_len() -> usize {
        borsh::object_length(&Self { balance: Balance::from_yoctonear(0), num_nonces: 0 }).unwrap()
    }
}

/// Defines permissions for AccessKey
#[derive(
    BorshSerialize,
    BorshDeserialize,
    PartialEq,
    Eq,
    Hash,
    Clone,
    Debug,
    serde::Serialize,
    serde::Deserialize,
    ProtocolSchema,
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum AccessKeyPermission {
    FunctionCall(FunctionCallPermission),
    /// Grants full access to the account.
    /// NOTE: It's used to replace account-level public keys.
    FullAccess,
    /// Gas key with limited permission to make transactions with FunctionCallActions
    /// Gas keys are a kind of access keys with a prepaid balance to pay for gas.
    GasKeyFunctionCall(GasKeyInfo, FunctionCallPermission),
    /// Gas key with full access to the account.
    /// Gas keys are a kind of access keys with a prepaid balance to pay for gas.
    GasKeyFullAccess(GasKeyInfo),
}

impl AccessKeyPermission {
    pub const MAX_NONCES_FOR_GAS_KEY: NonceIndex = 1024;

    pub fn function_call_permission(&self) -> Option<&FunctionCallPermission> {
        match self {
            AccessKeyPermission::FunctionCall(permission)
            | AccessKeyPermission::GasKeyFunctionCall(_, permission) => Some(permission),
            _ => None,
        }
    }

    pub fn function_call_permission_mut(&mut self) -> Option<&mut FunctionCallPermission> {
        match self {
            AccessKeyPermission::FunctionCall(permission)
            | AccessKeyPermission::GasKeyFunctionCall(_, permission) => Some(permission),
            _ => None,
        }
    }
}

/// Grants limited permission to make transactions with FunctionCallActions
/// The permission can limit the allowed balance to be spent on the prepaid gas.
/// It also restrict the account ID of the receiver for this function call.
/// It also can restrict the method name for the allowed function calls.
#[derive(
    BorshSerialize,
    BorshDeserialize,
    serde::Serialize,
    serde::Deserialize,
    PartialEq,
    Eq,
    Hash,
    Clone,
    Debug,
    ProtocolSchema,
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct FunctionCallPermission {
    /// Allowance is a balance limit to use by this access key to pay for function call gas and
    /// transaction fees. When this access key is used, both account balance and the allowance is
    /// decreased by the same value.
    /// `None` means unlimited allowance.
    /// NOTE: To change or increase the allowance, the old access key needs to be deleted and a new
    /// access key should be created.
    pub allowance: Option<Balance>,

    // This isn't an AccountId because already existing records in testnet genesis have invalid
    // values for this field (see: https://github.com/near/nearcore/pull/4621#issuecomment-892099860)
    // we accommodate those by using a string, allowing us to read and parse genesis.
    /// The access key only allows transactions with the given receiver's account id.
    pub receiver_id: String,

    /// A list of method names that can be used. The access key only allows transactions with the
    /// function call of one of the given method names.
    /// Empty list means any method name can be used.
    pub method_names: Vec<String>,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_serde_account(
        code_hash: CryptoHash,
        global_contract_hash: Option<CryptoHash>,
        global_contract_account_id: Option<AccountId>,
    ) -> SerdeAccount {
        SerdeAccount {
            amount: Balance::from_yoctonear(10_000_000),
            locked: Balance::from_yoctonear(100_000),
            code_hash,
            storage_usage: 1000,
            version: AccountVersion::V2,
            global_contract_hash,
            global_contract_account_id,
        }
    }

    #[test]
    fn test_v1_account_serde_serialization() {
        let old_account = AccountV1 {
            amount: Balance::from_yoctonear(1_000_000),
            locked: Balance::from_yoctonear(1_000_000),
            code_hash: CryptoHash::hash_bytes(&[42]),
            storage_usage: 100,
        };

        let serialized_account = serde_json::to_string(&old_account).unwrap();
        let expected_serde_repr = SerdeAccount {
            amount: old_account.amount,
            locked: old_account.locked,
            code_hash: old_account.code_hash,
            storage_usage: old_account.storage_usage,
            version: AccountVersion::V1,
            global_contract_hash: None,
            global_contract_account_id: None,
        };
        let actual_serde_repr: SerdeAccount = serde_json::from_str(&serialized_account).unwrap();
        assert_eq!(actual_serde_repr, expected_serde_repr);

        let new_account: Account = serde_json::from_str(&serialized_account).unwrap();
        assert_eq!(new_account, Account::V1(old_account));

        let new_serialized_account = serde_json::to_string(&new_account).unwrap();
        let deserialized_account: Account = serde_json::from_str(&new_serialized_account).unwrap();
        assert_eq!(deserialized_account, new_account);
    }

    #[test]
    fn test_v1_account_borsh_serialization() {
        let old_account = AccountV1 {
            amount: Balance::from_yoctonear(100),
            locked: Balance::from_yoctonear(200),
            code_hash: CryptoHash::hash_bytes(&[42]),
            storage_usage: 300,
        };
        let old_bytes = borsh::to_vec(&old_account).unwrap();
        let new_account = <Account as BorshDeserialize>::deserialize(&mut &old_bytes[..]).unwrap();
        assert_eq!(new_account, Account::V1(old_account));

        let new_bytes = borsh::to_vec(&new_account).unwrap();
        assert_eq!(new_bytes, old_bytes);
        let deserialized_account =
            <Account as BorshDeserialize>::deserialize(&mut &new_bytes[..]).unwrap();
        assert_eq!(deserialized_account, new_account);
    }

    #[test]
    fn test_account_v2_serde_serialization() {
        let account_v2 = AccountV2 {
            amount: Balance::from_yoctonear(10_000_000),
            locked: Balance::from_yoctonear(100_000),
            storage_usage: 1000,
            contract: AccountContract::Local(CryptoHash::hash_bytes(&[42])),
        };
        let account = Account::V2(account_v2.clone());

        let serialized_account = serde_json::to_string(&account).unwrap();
        let expected_serde_repr = SerdeAccount {
            amount: account_v2.amount,
            locked: account_v2.locked,
            code_hash: account_v2.contract.local_code().unwrap_or_default(),
            storage_usage: account_v2.storage_usage,
            version: AccountVersion::V2,
            global_contract_hash: None,
            global_contract_account_id: None,
        };
        let actual_serde_repr: SerdeAccount = serde_json::from_str(&serialized_account).unwrap();
        assert_eq!(actual_serde_repr, expected_serde_repr);

        let deserialized_account: Account = serde_json::from_str(&serialized_account).unwrap();
        assert_eq!(deserialized_account, account);
    }

    #[test]
    fn test_account_v2_borsh_serialization() {
        let account_v2 = AccountV2 {
            amount: Balance::from_yoctonear(10_000_000),
            locked: Balance::from_yoctonear(100_000),
            storage_usage: 1000,
            contract: AccountContract::Global(CryptoHash::hash_bytes(&[42])),
        };
        let account = Account::V2(account_v2);
        let serialized_account = borsh::to_vec(&account).unwrap();
        let deserialized_account =
            <Account as BorshDeserialize>::deserialize(&mut &serialized_account[..]).unwrap();
        assert_eq!(deserialized_account, account);
    }

    #[test]
    fn test_account_v2_serde_deserialization_fails_with_local_hash_and_global_account_id() {
        let id = AccountId::try_from("test.near".to_string()).unwrap();
        let code_hash = CryptoHash::hash_bytes(&[42]);

        let serde_repr = create_serde_account(code_hash, None, Some(id));

        let serde_string = serde_json::to_string(&serde_repr).unwrap();
        let deserialization_attempt: Result<Account, _> = serde_json::from_str(&serde_string);
        assert!(deserialization_attempt.is_err());
    }

    #[test]
    fn test_account_v2_serde_deserialization_fails_with_local_and_global_hashes() {
        let code_hash = CryptoHash::hash_bytes(&[42]);

        let serde_repr = create_serde_account(code_hash, Some(code_hash), None);

        let serde_string = serde_json::to_string(&serde_repr).unwrap();
        let deserialization_attempt: Result<Account, _> = serde_json::from_str(&serde_string);
        assert!(deserialization_attempt.is_err());
    }

    #[test]
    fn test_account_v2_serde_deserialization_fails_if_both_types_of_global_contract_are_present() {
        let id = AccountId::try_from("test.near".to_string()).unwrap();
        let serde_repr = create_serde_account(
            CryptoHash::default(),
            Some(CryptoHash::hash_bytes(&[42])),
            Some(id),
        );

        let serde_string = serde_json::to_string(&serde_repr).unwrap();
        let deserialization_attempt: Result<Account, _> = serde_json::from_str(&serde_string);
        assert!(deserialization_attempt.is_err());
    }

    #[test]
    fn test_account_version_upgrade_behaviour() {
        let account_v1 = AccountV1 {
            amount: Balance::from_yoctonear(100),
            locked: Balance::from_yoctonear(200),
            code_hash: CryptoHash::hash_bytes(&[42]),
            storage_usage: 300,
        };
        let mut account = Account::V1(account_v1);
        let contract = AccountContract::Local(CryptoHash::hash_bytes(&[42]));
        account.set_contract(contract);
        assert!(matches!(account, Account::V1(_)));

        let contract = AccountContract::None;
        account.set_contract(contract);
        assert!(matches!(account, Account::V1(_)));

        let contract = AccountContract::Global(CryptoHash::hash_bytes(&[42]));
        account.set_contract(contract);
        assert!(matches!(account, Account::V2(_)));
    }
}