near-kit 0.9.0

A clean, ergonomic Rust client for NEAR 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
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
//! Transaction action types.

use std::collections::BTreeMap;

use base64::{Engine as _, engine::general_purpose::STANDARD};
use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};
use serde_with::base64::Base64;
use serde_with::serde_as;
use sha3::{Digest, Keccak256};

use super::{AccountId, CryptoHash, Gas, NearToken, PublicKey, Signature, TryIntoAccountId};

/// Publish mode for global contracts.
///
/// Determines how a published contract will be identified in the global registry.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PublishMode {
    /// Contract is identified by the signer's account ID.
    /// The signer can update the contract later.
    Updatable,
    /// Contract is identified by its code hash.
    /// The contract cannot be updated after publishing.
    Immutable,
}

/// Trait for types that can identify a global contract.
///
/// This allows `deploy_from` to accept either a `CryptoHash` (for immutable
/// contracts) or an account ID string/`AccountId` (for publisher-updatable contracts).
///
/// # Panics
///
/// String-based implementations (`&str`, `String`, `&String`) panic if the string is not a
/// valid NEAR account ID.
pub trait GlobalContractRef {
    fn into_identifier(self) -> GlobalContractIdentifier;
}

impl GlobalContractRef for CryptoHash {
    fn into_identifier(self) -> GlobalContractIdentifier {
        GlobalContractIdentifier::CodeHash(self)
    }
}

impl GlobalContractRef for AccountId {
    fn into_identifier(self) -> GlobalContractIdentifier {
        GlobalContractIdentifier::AccountId(self)
    }
}

impl GlobalContractRef for &AccountId {
    fn into_identifier(self) -> GlobalContractIdentifier {
        GlobalContractIdentifier::AccountId(self.clone())
    }
}

impl GlobalContractRef for &str {
    fn into_identifier(self) -> GlobalContractIdentifier {
        let account_id: AccountId = self.try_into_account_id().expect("invalid account ID");
        GlobalContractIdentifier::AccountId(account_id)
    }
}

impl GlobalContractRef for String {
    fn into_identifier(self) -> GlobalContractIdentifier {
        let account_id: AccountId = self.try_into_account_id().expect("invalid account ID");
        GlobalContractIdentifier::AccountId(account_id)
    }
}

impl GlobalContractRef for &String {
    fn into_identifier(self) -> GlobalContractIdentifier {
        let account_id: AccountId = self
            .as_str()
            .try_into_account_id()
            .expect("invalid account ID");
        GlobalContractIdentifier::AccountId(account_id)
    }
}

/// NEP-461 prefix for delegate actions (meta-transactions).
/// Value: 2^30 + 366 = 1073742190
///
/// This prefix is prepended to DelegateAction when serializing for signing,
/// ensuring delegate action signatures are always distinguishable from
/// regular transaction signatures.
pub const DELEGATE_ACTION_PREFIX: u32 = 1_073_742_190;

/// Gas key information.
///
/// Gas keys are access keys with a prepaid balance to pay for gas costs.
#[derive(
    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, BorshSerialize, BorshDeserialize,
)]
pub struct GasKeyInfo {
    /// Prepaid gas balance in yoctoNEAR.
    pub balance: NearToken,
    /// Number of nonces allocated for this gas key.
    pub num_nonces: u16,
}

/// Access key permission.
///
/// IMPORTANT: Variant order matters for Borsh serialization!
/// NEAR Protocol defines: 0 = FunctionCall, 1 = FullAccess,
/// 2 = GasKeyFunctionCall, 3 = GasKeyFullAccess
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
pub enum AccessKeyPermission {
    /// Function call access with restrictions. (discriminant = 0)
    FunctionCall(FunctionCallPermission),
    /// Full access to the account. (discriminant = 1)
    FullAccess,
    /// Gas key with function call access. (discriminant = 2)
    GasKeyFunctionCall(GasKeyInfo, FunctionCallPermission),
    /// Gas key with full access. (discriminant = 3)
    GasKeyFullAccess(GasKeyInfo),
}

impl AccessKeyPermission {
    /// Create a function call permission.
    pub fn function_call(
        receiver_id: AccountId,
        method_names: Vec<String>,
        allowance: Option<NearToken>,
    ) -> Self {
        Self::FunctionCall(FunctionCallPermission {
            allowance,
            receiver_id,
            method_names,
        })
    }

    /// Create a full access permission.
    pub fn full_access() -> Self {
        Self::FullAccess
    }
}

/// Function call access key permission details.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
pub struct FunctionCallPermission {
    /// Maximum amount this key can spend (None = unlimited).
    pub allowance: Option<NearToken>,
    /// Contract that can be called.
    pub receiver_id: AccountId,
    /// Methods that can be called (empty = all methods).
    pub method_names: Vec<String>,
}

/// Access key attached to an account.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
pub struct AccessKey {
    /// Nonce for replay protection.
    pub nonce: u64,
    /// Permission level.
    pub permission: AccessKeyPermission,
}

impl AccessKey {
    /// Create a full access key.
    pub fn full_access() -> Self {
        Self {
            nonce: 0,
            permission: AccessKeyPermission::FullAccess,
        }
    }

    /// Create a function call access key.
    pub fn function_call(
        receiver_id: AccountId,
        method_names: Vec<String>,
        allowance: Option<NearToken>,
    ) -> Self {
        Self {
            nonce: 0,
            permission: AccessKeyPermission::function_call(receiver_id, method_names, allowance),
        }
    }
}

/// A transaction action.
///
/// IMPORTANT: Variant order matters for Borsh serialization!
/// The discriminants match NEAR Protocol specification:
/// 0 = CreateAccount, 1 = DeployContract, 2 = FunctionCall, 3 = Transfer,
/// 4 = Stake, 5 = AddKey, 6 = DeleteKey, 7 = DeleteAccount, 8 = Delegate,
/// 9 = DeployGlobalContract, 10 = UseGlobalContract, 11 = DeterministicStateInit,
/// 12 = TransferToGasKey, 13 = WithdrawFromGasKey
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub enum Action {
    /// Create a new account. (discriminant = 0)
    CreateAccount(CreateAccountAction),
    /// Deploy contract code. (discriminant = 1)
    DeployContract(DeployContractAction),
    /// Call a contract function. (discriminant = 2)
    FunctionCall(FunctionCallAction),
    /// Transfer NEAR tokens. (discriminant = 3)
    Transfer(TransferAction),
    /// Stake NEAR for validation. (discriminant = 4)
    Stake(StakeAction),
    /// Add an access key. (discriminant = 5)
    AddKey(AddKeyAction),
    /// Delete an access key. (discriminant = 6)
    DeleteKey(DeleteKeyAction),
    /// Delete the account. (discriminant = 7)
    DeleteAccount(DeleteAccountAction),
    /// Delegate action (for meta-transactions). (discriminant = 8)
    Delegate(Box<SignedDelegateAction>),
    /// Publish a contract to global registry. (discriminant = 9)
    DeployGlobalContract(DeployGlobalContractAction),
    /// Deploy from a previously published global contract. (discriminant = 10)
    UseGlobalContract(UseGlobalContractAction),
    /// NEP-616: Deploy with deterministically derived account ID. (discriminant = 11)
    DeterministicStateInit(DeterministicStateInitAction),
    /// Transfer NEAR to a gas key. (discriminant = 12)
    TransferToGasKey(TransferToGasKeyAction),
    /// Withdraw NEAR from a gas key. (discriminant = 13)
    WithdrawFromGasKey(WithdrawFromGasKeyAction),
}

/// Create a new account.
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct CreateAccountAction;

/// Deploy contract code.
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct DeployContractAction {
    /// WASM code to deploy.
    pub code: Vec<u8>,
}

/// Call a contract function.
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct FunctionCallAction {
    /// Method name to call.
    pub method_name: String,
    /// Arguments (JSON or Borsh encoded).
    pub args: Vec<u8>,
    /// Gas to attach.
    pub gas: Gas,
    /// NEAR tokens to attach.
    pub deposit: NearToken,
}

/// Transfer NEAR tokens.
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct TransferAction {
    /// Amount to transfer.
    pub deposit: NearToken,
}

/// Stake NEAR for validation.
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct StakeAction {
    /// Amount to stake.
    pub stake: NearToken,
    /// Validator public key.
    pub public_key: PublicKey,
}

/// Add an access key.
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct AddKeyAction {
    /// Public key to add.
    pub public_key: PublicKey,
    /// Access key details.
    pub access_key: AccessKey,
}

/// Delete an access key.
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct DeleteKeyAction {
    /// Public key to delete.
    pub public_key: PublicKey,
}

/// Delete the account.
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct DeleteAccountAction {
    /// Account to receive remaining balance.
    pub beneficiary_id: AccountId,
}

// ============================================================================
// Global Contract Actions
// ============================================================================

/// How a global contract is identified in the registry.
///
/// Global contracts can be referenced either by their code hash (immutable)
/// or by the account that published them (updatable).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
pub enum GlobalContractIdentifier {
    /// Reference by code hash (32-byte SHA-256 hash of the WASM code).
    /// This creates an immutable reference - the contract cannot be updated.
    #[serde(rename = "hash")]
    CodeHash(CryptoHash),
    /// Reference by the account ID that published the contract.
    /// The publisher can update the contract, and all users will get the new version.
    #[serde(rename = "account_id")]
    AccountId(AccountId),
}

/// Deploy mode for global contracts.
///
/// Determines how the contract will be identified in the global registry.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
#[repr(u8)]
pub enum GlobalContractDeployMode {
    /// Contract is identified by its code hash (immutable).
    /// Other accounts reference it by the hash.
    CodeHash,
    /// Contract is identified by the signer's account ID (updatable).
    /// The signer can update the contract later.
    AccountId,
}

/// Publish a contract to the global registry.
///
/// Global contracts are deployed once and can be referenced by multiple accounts,
/// saving storage costs. The contract can be identified either by its code hash
/// (immutable) or by the publishing account (updatable).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
pub struct DeployGlobalContractAction {
    /// The WASM code to publish.
    pub code: Vec<u8>,
    /// How the contract will be identified.
    pub deploy_mode: GlobalContractDeployMode,
}

/// Deploy a contract from the global registry.
///
/// Instead of uploading the WASM code, this action references a previously
/// published contract in the global registry.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
pub struct UseGlobalContractAction {
    /// Reference to the published contract.
    pub contract_identifier: GlobalContractIdentifier,
}

// ============================================================================
// NEP-616 Deterministic Account Actions
// ============================================================================

/// State initialization data for NEP-616 deterministic accounts.
///
/// The account ID is derived from: `"0s" + hex(keccak256(borsh(state_init))[12..32])`
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
#[repr(u8)]
pub enum DeterministicAccountStateInit {
    /// Version 1 of the state init format.
    V1(DeterministicAccountStateInitV1),
}

/// Version 1 of deterministic account state initialization.
#[serde_as]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
pub struct DeterministicAccountStateInitV1 {
    /// Reference to the contract code (from global registry).
    pub code: GlobalContractIdentifier,
    /// Initial key-value pairs to populate in the contract's storage.
    /// Keys and values are Borsh-serialized bytes.
    #[serde_as(as = "BTreeMap<Base64, Base64>")]
    pub data: BTreeMap<Vec<u8>, Vec<u8>>,
}

/// Deploy a contract with a deterministically derived account ID (NEP-616).
///
/// This enables creating accounts where the account ID is derived from the
/// contract code and initial state, making them predictable and reproducible.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
pub struct DeterministicStateInitAction {
    /// The state initialization data.
    pub state_init: DeterministicAccountStateInit,
    /// Amount to attach for storage costs.
    pub deposit: NearToken,
}

impl DeterministicAccountStateInit {
    /// Create a state init referencing a global contract by its code hash (immutable).
    pub fn by_hash(code_hash: CryptoHash, data: BTreeMap<Vec<u8>, Vec<u8>>) -> Self {
        Self::V1(DeterministicAccountStateInitV1 {
            code: GlobalContractIdentifier::CodeHash(code_hash),
            data,
        })
    }

    /// Create a state init referencing a global contract by its publisher account (updatable).
    pub fn by_publisher(publisher_id: AccountId, data: BTreeMap<Vec<u8>, Vec<u8>>) -> Self {
        Self::V1(DeterministicAccountStateInitV1 {
            code: GlobalContractIdentifier::AccountId(publisher_id),
            data,
        })
    }

    /// Derive the deterministic account ID from this state init.
    ///
    /// The account ID is derived as: `"0s" + hex(keccak256(borsh(state_init))[12..32])`
    ///
    /// This produces a 42-character account ID that:
    /// - Starts with "0s" prefix (distinguishes from Ethereum implicit accounts "0x")
    /// - Followed by 40 hex characters (20 bytes from the keccak256 hash)
    ///
    /// # Example
    ///
    /// ```rust
    /// use near_kit::types::{DeterministicAccountStateInit, CryptoHash};
    /// use std::collections::BTreeMap;
    ///
    /// let state_init = DeterministicAccountStateInit::by_hash(CryptoHash::default(), BTreeMap::new());
    ///
    /// let account_id = state_init.derive_account_id();
    /// assert!(account_id.as_str().starts_with("0s"));
    /// assert_eq!(account_id.as_str().len(), 42);
    /// ```
    pub fn derive_account_id(&self) -> AccountId {
        // Borsh-serialize the state init
        let serialized = borsh::to_vec(self).expect("StateInit serialization should not fail");

        // Compute keccak256 hash
        let hash = Keccak256::digest(&serialized);

        // Take last 20 bytes (indices 12-32) of the hash
        let suffix = &hash[12..32];

        // Format as "0s" + hex
        let account_str = format!("0s{}", hex::encode(suffix));

        // This is a valid deterministic account ID by construction
        account_str
            .parse()
            .expect("deterministic account ID should always be valid")
    }
}

impl DeterministicStateInitAction {
    /// Derive the deterministic account ID for this action.
    ///
    /// Convenience method that delegates to `DeterministicAccountStateInit::derive_account_id`.
    pub fn derive_account_id(&self) -> AccountId {
        self.state_init.derive_account_id()
    }
}

/// Transfer NEAR to a gas key.
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct TransferToGasKeyAction {
    /// Public key of the gas key to fund.
    pub public_key: PublicKey,
    /// Amount of NEAR to transfer.
    pub deposit: NearToken,
}

/// Withdraw NEAR from a gas key.
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct WithdrawFromGasKeyAction {
    /// Public key of the gas key to withdraw from.
    pub public_key: PublicKey,
    /// Amount of NEAR to withdraw.
    pub amount: NearToken,
}

/// Delegate action for meta-transactions.
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct DelegateAction {
    /// Sender of the delegate action.
    pub sender_id: AccountId,
    /// Receiver of the delegate action.
    pub receiver_id: AccountId,
    /// Actions to delegate.
    pub actions: Vec<NonDelegateAction>,
    /// Nonce for replay protection.
    pub nonce: u64,
    /// Maximum block height for the action.
    pub max_block_height: u64,
    /// Public key authorizing the delegate.
    pub public_key: PublicKey,
}

/// Signed delegate action.
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct SignedDelegateAction {
    /// The delegate action.
    pub delegate_action: DelegateAction,
    /// Signature over the delegate action.
    pub signature: super::Signature,
}

/// Non-delegate action (for use within DelegateAction).
///
/// This is a newtype wrapper around Action that ensures the wrapped action
/// is not a Delegate variant, since delegate actions cannot contain nested
/// delegate actions.
///
/// The newtype wrapper serializes identically to the inner Action, preserving
/// Borsh compatibility with near-primitives.
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct NonDelegateAction(Action);

// Helper constructors for actions
impl Action {
    /// Create a CreateAccount action.
    pub fn create_account() -> Self {
        Self::CreateAccount(CreateAccountAction)
    }

    /// Create a DeployContract action.
    pub fn deploy_contract(code: Vec<u8>) -> Self {
        Self::DeployContract(DeployContractAction { code })
    }

    /// Create a FunctionCall action.
    pub fn function_call(
        method_name: impl Into<String>,
        args: Vec<u8>,
        gas: Gas,
        deposit: NearToken,
    ) -> Self {
        Self::FunctionCall(FunctionCallAction {
            method_name: method_name.into(),
            args,
            gas,
            deposit,
        })
    }

    /// Create a Transfer action.
    pub fn transfer(deposit: NearToken) -> Self {
        Self::Transfer(TransferAction { deposit })
    }

    /// Create a Stake action.
    pub fn stake(stake: NearToken, public_key: PublicKey) -> Self {
        Self::Stake(StakeAction { stake, public_key })
    }

    /// Create an AddKey action for full access.
    pub fn add_full_access_key(public_key: PublicKey) -> Self {
        Self::AddKey(AddKeyAction {
            public_key,
            access_key: AccessKey::full_access(),
        })
    }

    /// Create an AddKey action for function call access.
    pub fn add_function_call_key(
        public_key: PublicKey,
        receiver_id: AccountId,
        method_names: Vec<String>,
        allowance: Option<NearToken>,
    ) -> Self {
        Self::AddKey(AddKeyAction {
            public_key,
            access_key: AccessKey::function_call(receiver_id, method_names, allowance),
        })
    }

    /// Create a DeleteKey action.
    pub fn delete_key(public_key: PublicKey) -> Self {
        Self::DeleteKey(DeleteKeyAction { public_key })
    }

    /// Create a DeleteAccount action.
    pub fn delete_account(beneficiary_id: AccountId) -> Self {
        Self::DeleteAccount(DeleteAccountAction { beneficiary_id })
    }

    /// Create a Delegate action from a signed delegate action.
    pub fn delegate(signed_delegate: SignedDelegateAction) -> Self {
        Self::Delegate(Box::new(signed_delegate))
    }

    /// Publish a contract to the global registry.
    ///
    /// Global contracts are deployed once and can be referenced by multiple accounts,
    /// saving storage costs.
    ///
    /// # Arguments
    ///
    /// * `code` - The WASM code to publish
    /// * `mode` - Whether the contract is updatable (by publisher) or immutable (by hash)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // Publish updatable contract (identified by your account)
    /// near.transaction("alice.near")
    ///     .publish(wasm_code, PublishMode::Updatable)
    ///     .send()
    ///     .await?;
    ///
    /// // Publish immutable contract (identified by its hash)
    /// near.transaction("alice.near")
    ///     .publish(wasm_code, PublishMode::Immutable)
    ///     .send()
    ///     .await?;
    /// ```
    pub fn publish(code: Vec<u8>, mode: PublishMode) -> Self {
        Self::DeployGlobalContract(DeployGlobalContractAction {
            code,
            deploy_mode: match mode {
                PublishMode::Updatable => GlobalContractDeployMode::AccountId,
                PublishMode::Immutable => GlobalContractDeployMode::CodeHash,
            },
        })
    }

    /// Deploy a contract from the global registry by code hash.
    ///
    /// References a previously published immutable contract.
    pub fn deploy_from_hash(code_hash: CryptoHash) -> Self {
        Self::UseGlobalContract(UseGlobalContractAction {
            contract_identifier: GlobalContractIdentifier::CodeHash(code_hash),
        })
    }

    /// Deploy a contract from the global registry by account ID.
    ///
    /// References a contract published by the given account.
    /// The contract can be updated by the publisher.
    pub fn deploy_from_account(account_id: AccountId) -> Self {
        Self::UseGlobalContract(UseGlobalContractAction {
            contract_identifier: GlobalContractIdentifier::AccountId(account_id),
        })
    }

    /// Create a NEP-616 deterministic state init action.
    ///
    /// The account ID is derived from the state init data:
    /// `"0s" + hex(keccak256(borsh(state_init))[12..32])`
    pub fn state_init(state_init: DeterministicAccountStateInit, deposit: NearToken) -> Self {
        Self::DeterministicStateInit(DeterministicStateInitAction {
            state_init,
            deposit,
        })
    }

    /// Transfer NEAR to a gas key.
    pub fn transfer_to_gas_key(public_key: PublicKey, deposit: NearToken) -> Self {
        Self::TransferToGasKey(TransferToGasKeyAction {
            public_key,
            deposit,
        })
    }

    /// Withdraw NEAR from a gas key.
    pub fn withdraw_from_gas_key(public_key: PublicKey, amount: NearToken) -> Self {
        Self::WithdrawFromGasKey(WithdrawFromGasKeyAction { public_key, amount })
    }
}

impl DelegateAction {
    /// Serialize the delegate action for signing.
    ///
    /// Per NEP-461, this prepends a u32 prefix (2^30 + 366) before the delegate action,
    /// ensuring signed delegate actions are never identical to signed transactions.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let bytes = delegate_action.serialize_for_signing();
    /// let hash = CryptoHash::hash(&bytes);
    /// let signature = signer.sign(hash.as_bytes()).await?;
    /// ```
    pub fn serialize_for_signing(&self) -> Vec<u8> {
        let prefix_bytes = DELEGATE_ACTION_PREFIX.to_le_bytes();
        let action_bytes =
            borsh::to_vec(self).expect("delegate action serialization should never fail");

        let mut result = Vec::with_capacity(prefix_bytes.len() + action_bytes.len());
        result.extend_from_slice(&prefix_bytes);
        result.extend_from_slice(&action_bytes);
        result
    }

    /// Get the hash of this delegate action (for signing).
    pub fn get_hash(&self) -> CryptoHash {
        let bytes = self.serialize_for_signing();
        CryptoHash::hash(&bytes)
    }

    /// Sign this delegate action and return a SignedDelegateAction.
    pub fn sign(self, signature: Signature) -> SignedDelegateAction {
        SignedDelegateAction {
            delegate_action: self,
            signature,
        }
    }
}

impl SignedDelegateAction {
    /// Encode the signed delegate action to bytes for transport.
    pub fn to_bytes(&self) -> Vec<u8> {
        borsh::to_vec(self).expect("signed delegate action serialization should never fail")
    }

    /// Encode the signed delegate action to base64 for transport.
    ///
    /// This is the most common format for sending delegate actions via HTTP/JSON.
    pub fn to_base64(&self) -> String {
        STANDARD.encode(self.to_bytes())
    }

    /// Decode a signed delegate action from bytes.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, borsh::io::Error> {
        borsh::from_slice(bytes)
    }

    /// Decode a signed delegate action from base64.
    pub fn from_base64(s: &str) -> Result<Self, DecodeError> {
        let bytes = STANDARD.decode(s).map_err(DecodeError::Base64)?;
        Self::from_bytes(&bytes).map_err(DecodeError::Borsh)
    }

    /// Get the sender account ID.
    pub fn sender_id(&self) -> &AccountId {
        &self.delegate_action.sender_id
    }

    /// Get the receiver account ID.
    pub fn receiver_id(&self) -> &AccountId {
        &self.delegate_action.receiver_id
    }
}

/// Error decoding a signed delegate action.
#[derive(Debug, thiserror::Error)]
pub enum DecodeError {
    /// Base64 decoding failed.
    #[error("base64 decode error: {0}")]
    Base64(#[from] base64::DecodeError),
    /// Borsh deserialization failed.
    #[error("borsh decode error: {0}")]
    Borsh(#[from] borsh::io::Error),
}

impl NonDelegateAction {
    /// Convert from an Action, returning None if it's a Delegate action.
    pub fn from_action(action: Action) -> Option<Self> {
        if matches!(action, Action::Delegate(_)) {
            None
        } else {
            Some(Self(action))
        }
    }

    /// Get a reference to the inner action.
    pub fn inner(&self) -> &Action {
        &self.0
    }

    /// Consume self and return the inner action.
    pub fn into_inner(self) -> Action {
        self.0
    }
}

impl From<NonDelegateAction> for Action {
    fn from(action: NonDelegateAction) -> Self {
        action.0
    }
}

impl TryFrom<Action> for NonDelegateAction {
    type Error = ();

    fn try_from(action: Action) -> Result<Self, Self::Error> {
        Self::from_action(action).ok_or(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{Gas, NearToken, SecretKey};

    fn create_test_delegate_action() -> DelegateAction {
        let sender_id: AccountId = "alice.testnet".parse().unwrap();
        let receiver_id: AccountId = "bob.testnet".parse().unwrap();
        let public_key: PublicKey = "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp"
            .parse()
            .unwrap();

        DelegateAction {
            sender_id,
            receiver_id,
            actions: vec![
                NonDelegateAction::from_action(Action::Transfer(TransferAction {
                    deposit: NearToken::from_near(1),
                }))
                .unwrap(),
            ],
            nonce: 1,
            max_block_height: 1000,
            public_key,
        }
    }

    #[test]
    fn test_delegate_action_prefix() {
        // NEP-461: prefix = 2^30 + 366
        assert_eq!(DELEGATE_ACTION_PREFIX, 1073742190);
        assert_eq!(DELEGATE_ACTION_PREFIX, (1 << 30) + 366);
    }

    #[test]
    fn test_delegate_action_serialize_for_signing() {
        let delegate_action = create_test_delegate_action();
        let bytes = delegate_action.serialize_for_signing();

        // First 4 bytes should be the NEP-461 prefix in little-endian
        let prefix_bytes = &bytes[0..4];
        let prefix = u32::from_le_bytes(prefix_bytes.try_into().unwrap());
        assert_eq!(prefix, DELEGATE_ACTION_PREFIX);

        // Rest should be borsh-serialized DelegateAction
        let action_bytes = &bytes[4..];
        let expected_action_bytes = borsh::to_vec(&delegate_action).unwrap();
        assert_eq!(action_bytes, expected_action_bytes.as_slice());
    }

    #[test]
    fn test_delegate_action_get_hash() {
        let delegate_action = create_test_delegate_action();
        let hash = delegate_action.get_hash();

        // Hash should be SHA-256 of serialize_for_signing bytes
        let bytes = delegate_action.serialize_for_signing();
        let expected_hash = CryptoHash::hash(&bytes);
        assert_eq!(hash, expected_hash);
    }

    #[test]
    fn test_signed_delegate_action_roundtrip_bytes() {
        let delegate_action = create_test_delegate_action();
        let secret_key = SecretKey::generate_ed25519();
        let hash = delegate_action.get_hash();
        let signature = secret_key.sign(hash.as_bytes());
        let signed = delegate_action.sign(signature);

        // Roundtrip through bytes
        let bytes = signed.to_bytes();
        let decoded = SignedDelegateAction::from_bytes(&bytes).unwrap();

        assert_eq!(decoded.sender_id().as_str(), signed.sender_id().as_str());
        assert_eq!(
            decoded.receiver_id().as_str(),
            signed.receiver_id().as_str()
        );
        assert_eq!(decoded.delegate_action.nonce, signed.delegate_action.nonce);
        assert_eq!(
            decoded.delegate_action.max_block_height,
            signed.delegate_action.max_block_height
        );
    }

    #[test]
    fn test_signed_delegate_action_roundtrip_base64() {
        let delegate_action = create_test_delegate_action();
        let secret_key = SecretKey::generate_ed25519();
        let hash = delegate_action.get_hash();
        let signature = secret_key.sign(hash.as_bytes());
        let signed = delegate_action.sign(signature);

        // Roundtrip through base64
        let base64 = signed.to_base64();
        let decoded = SignedDelegateAction::from_base64(&base64).unwrap();

        assert_eq!(decoded.sender_id().as_str(), signed.sender_id().as_str());
        assert_eq!(
            decoded.receiver_id().as_str(),
            signed.receiver_id().as_str()
        );
    }

    #[test]
    fn test_signed_delegate_action_accessors() {
        let delegate_action = create_test_delegate_action();
        let secret_key = SecretKey::generate_ed25519();
        let hash = delegate_action.get_hash();
        let signature = secret_key.sign(hash.as_bytes());
        let signed = delegate_action.sign(signature);

        assert_eq!(signed.sender_id().as_str(), "alice.testnet");
        assert_eq!(signed.receiver_id().as_str(), "bob.testnet");
    }

    #[test]
    fn test_non_delegate_action_from_action() {
        // Transfer should convert
        let transfer = Action::Transfer(TransferAction {
            deposit: NearToken::from_near(1),
        });
        assert!(NonDelegateAction::from_action(transfer).is_some());

        // FunctionCall should convert
        let call = Action::FunctionCall(FunctionCallAction {
            method_name: "test".to_string(),
            args: vec![],
            gas: Gas::default(),
            deposit: NearToken::ZERO,
        });
        assert!(NonDelegateAction::from_action(call).is_some());

        // Delegate should NOT convert (returns None)
        let delegate_action = create_test_delegate_action();
        let secret_key = SecretKey::generate_ed25519();
        let hash = delegate_action.get_hash();
        let signature = secret_key.sign(hash.as_bytes());
        let signed = delegate_action.sign(signature);
        let delegate = Action::delegate(signed);
        assert!(NonDelegateAction::from_action(delegate).is_none());
    }

    #[test]
    fn test_decode_error_display() {
        // Test that DecodeError has proper Display impl
        let base64_err = DecodeError::Base64(base64::DecodeError::InvalidLength(5));
        assert!(format!("{}", base64_err).contains("base64"));

        // Borsh error is harder to construct, but we tested the variant exists
    }

    // ========================================================================
    // Global Contract Action Tests
    // ========================================================================

    #[test]
    fn test_action_discriminants() {
        // Verify action discriminants match NEAR protocol specification
        // 0 = CreateAccount, 1 = DeployContract, 2 = FunctionCall, 3 = Transfer,
        // 4 = Stake, 5 = AddKey, 6 = DeleteKey, 7 = DeleteAccount, 8 = Delegate,
        // 9 = DeployGlobalContract, 10 = UseGlobalContract, 11 = DeterministicStateInit,
        // 12 = TransferToGasKey, 13 = WithdrawFromGasKey

        let create_account = Action::create_account();
        let bytes = borsh::to_vec(&create_account).unwrap();
        assert_eq!(bytes[0], 0, "CreateAccount should have discriminant 0");

        let deploy = Action::deploy_contract(vec![1, 2, 3]);
        let bytes = borsh::to_vec(&deploy).unwrap();
        assert_eq!(bytes[0], 1, "DeployContract should have discriminant 1");

        let transfer = Action::transfer(NearToken::from_near(1));
        let bytes = borsh::to_vec(&transfer).unwrap();
        assert_eq!(bytes[0], 3, "Transfer should have discriminant 3");

        // DeployGlobalContract (discriminant = 9)
        let publish = Action::publish(vec![1, 2, 3], PublishMode::Updatable);
        let bytes = borsh::to_vec(&publish).unwrap();
        assert_eq!(
            bytes[0], 9,
            "DeployGlobalContract should have discriminant 9"
        );

        // UseGlobalContract (discriminant = 10)
        let code_hash = CryptoHash::hash(&[1, 2, 3]);
        let use_global = Action::deploy_from_hash(code_hash);
        let bytes = borsh::to_vec(&use_global).unwrap();
        assert_eq!(
            bytes[0], 10,
            "UseGlobalContract should have discriminant 10"
        );

        // DeterministicStateInit (discriminant = 11)
        let state_init = Action::state_init(
            DeterministicAccountStateInit::by_hash(code_hash, BTreeMap::new()),
            NearToken::from_near(1),
        );
        let bytes = borsh::to_vec(&state_init).unwrap();
        assert_eq!(
            bytes[0], 11,
            "DeterministicStateInit should have discriminant 11"
        );

        // TransferToGasKey (discriminant = 12)
        let pk: PublicKey = "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp"
            .parse()
            .unwrap();
        let transfer_gas = Action::transfer_to_gas_key(pk.clone(), NearToken::from_near(1));
        let bytes = borsh::to_vec(&transfer_gas).unwrap();
        assert_eq!(bytes[0], 12, "TransferToGasKey should have discriminant 12");

        // WithdrawFromGasKey (discriminant = 13)
        let withdraw_gas = Action::withdraw_from_gas_key(pk, NearToken::from_near(1));
        let bytes = borsh::to_vec(&withdraw_gas).unwrap();
        assert_eq!(
            bytes[0], 13,
            "WithdrawFromGasKey should have discriminant 13"
        );
    }

    #[test]
    fn test_global_contract_deploy_mode_serialization() {
        // Verify deploy mode serialization
        let by_hash = GlobalContractDeployMode::CodeHash;
        let bytes = borsh::to_vec(&by_hash).unwrap();
        assert_eq!(bytes, vec![0], "CodeHash mode should serialize to 0");

        let by_account = GlobalContractDeployMode::AccountId;
        let bytes = borsh::to_vec(&by_account).unwrap();
        assert_eq!(bytes, vec![1], "AccountId mode should serialize to 1");
    }

    #[test]
    fn test_global_contract_identifier_serialization() {
        // Verify identifier serialization
        let hash = CryptoHash::hash(&[1, 2, 3]);
        let by_hash = GlobalContractIdentifier::CodeHash(hash);
        let bytes = borsh::to_vec(&by_hash).unwrap();
        assert_eq!(
            bytes[0], 0,
            "CodeHash identifier should have discriminant 0"
        );
        assert_eq!(
            bytes.len(),
            1 + 32,
            "Should be 1 byte discriminant + 32 byte hash"
        );

        let account_id: AccountId = "test.near".parse().unwrap();
        let by_account = GlobalContractIdentifier::AccountId(account_id);
        let bytes = borsh::to_vec(&by_account).unwrap();
        assert_eq!(
            bytes[0], 1,
            "AccountId identifier should have discriminant 1"
        );
    }

    #[test]
    fn test_deploy_global_contract_action_roundtrip() {
        let code = vec![0, 97, 115, 109]; // WASM magic bytes
        let action = DeployGlobalContractAction {
            code: code.clone(),
            deploy_mode: GlobalContractDeployMode::CodeHash,
        };

        let bytes = borsh::to_vec(&action).unwrap();
        let decoded: DeployGlobalContractAction = borsh::from_slice(&bytes).unwrap();

        assert_eq!(decoded.code, code);
        assert_eq!(decoded.deploy_mode, GlobalContractDeployMode::CodeHash);
    }

    #[test]
    fn test_use_global_contract_action_roundtrip() {
        let hash = CryptoHash::hash(&[1, 2, 3, 4]);
        let action = UseGlobalContractAction {
            contract_identifier: GlobalContractIdentifier::CodeHash(hash),
        };

        let bytes = borsh::to_vec(&action).unwrap();
        let decoded: UseGlobalContractAction = borsh::from_slice(&bytes).unwrap();

        assert_eq!(
            decoded.contract_identifier,
            GlobalContractIdentifier::CodeHash(hash)
        );
    }

    #[test]
    fn test_deterministic_state_init_roundtrip() {
        let hash = CryptoHash::hash(&[1, 2, 3, 4]);
        let mut data = BTreeMap::new();
        data.insert(b"key1".to_vec(), b"value1".to_vec());
        data.insert(b"key2".to_vec(), b"value2".to_vec());

        let action = DeterministicStateInitAction {
            state_init: DeterministicAccountStateInit::V1(DeterministicAccountStateInitV1 {
                code: GlobalContractIdentifier::CodeHash(hash),
                data: data.clone(),
            }),
            deposit: NearToken::from_near(5),
        };

        let bytes = borsh::to_vec(&action).unwrap();
        let decoded: DeterministicStateInitAction = borsh::from_slice(&bytes).unwrap();

        assert_eq!(decoded.deposit, NearToken::from_near(5));
        let DeterministicAccountStateInit::V1(v1) = decoded.state_init;
        assert_eq!(v1.code, GlobalContractIdentifier::CodeHash(hash));
        assert_eq!(v1.data, data);
    }

    #[test]
    fn test_action_helper_constructors() {
        // Test publish
        let code = vec![1, 2, 3];
        let action = Action::publish(code.clone(), PublishMode::Immutable);
        if let Action::DeployGlobalContract(inner) = action {
            assert_eq!(inner.code, code);
            assert_eq!(inner.deploy_mode, GlobalContractDeployMode::CodeHash);
        } else {
            panic!("Expected DeployGlobalContract");
        }

        let action = Action::publish(code.clone(), PublishMode::Updatable);
        if let Action::DeployGlobalContract(inner) = action {
            assert_eq!(inner.deploy_mode, GlobalContractDeployMode::AccountId);
        } else {
            panic!("Expected DeployGlobalContract");
        }

        // Test deploy_from_hash
        let hash = CryptoHash::hash(&code);
        let action = Action::deploy_from_hash(hash);
        if let Action::UseGlobalContract(inner) = action {
            assert_eq!(
                inner.contract_identifier,
                GlobalContractIdentifier::CodeHash(hash)
            );
        } else {
            panic!("Expected UseGlobalContract");
        }

        // Test deploy_from_account
        let account_id: AccountId = "publisher.near".parse().unwrap();
        let action = Action::deploy_from_account(account_id.clone());
        if let Action::UseGlobalContract(inner) = action {
            assert_eq!(
                inner.contract_identifier,
                GlobalContractIdentifier::AccountId(account_id)
            );
        } else {
            panic!("Expected UseGlobalContract");
        }
    }

    #[test]
    fn test_derive_account_id_format() {
        // Test that derived account ID has the correct format
        let state_init = DeterministicAccountStateInit::V1(DeterministicAccountStateInitV1 {
            code: GlobalContractIdentifier::CodeHash(CryptoHash::default()),
            data: BTreeMap::new(),
        });

        let account_id = state_init.derive_account_id();
        let account_str = account_id.as_str();

        // Should start with "0s"
        assert!(
            account_str.starts_with("0s"),
            "Derived account should start with '0s', got: {}",
            account_str
        );

        // Should be exactly 42 characters: "0s" + 40 hex chars
        assert_eq!(
            account_str.len(),
            42,
            "Derived account should be 42 chars, got: {}",
            account_str.len()
        );

        // Everything after "0s" should be valid lowercase hex
        let hex_part = &account_str[2..];
        assert!(
            hex_part
                .chars()
                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()),
            "Hex part should be lowercase hex, got: {}",
            hex_part
        );
    }

    #[test]
    fn test_derive_account_id_deterministic() {
        // Same input should produce same output
        let state_init1 = DeterministicAccountStateInit::V1(DeterministicAccountStateInitV1 {
            code: GlobalContractIdentifier::AccountId("publisher.near".parse().unwrap()),
            data: BTreeMap::new(),
        });

        let state_init2 = DeterministicAccountStateInit::V1(DeterministicAccountStateInitV1 {
            code: GlobalContractIdentifier::AccountId("publisher.near".parse().unwrap()),
            data: BTreeMap::new(),
        });

        assert_eq!(
            state_init1.derive_account_id(),
            state_init2.derive_account_id(),
            "Same input should produce same account ID"
        );
    }

    #[test]
    fn test_derive_account_id_different_inputs() {
        // Different code references should produce different account IDs
        let state_init1 = DeterministicAccountStateInit::V1(DeterministicAccountStateInitV1 {
            code: GlobalContractIdentifier::AccountId("publisher1.near".parse().unwrap()),
            data: BTreeMap::new(),
        });

        let state_init2 = DeterministicAccountStateInit::V1(DeterministicAccountStateInitV1 {
            code: GlobalContractIdentifier::AccountId("publisher2.near".parse().unwrap()),
            data: BTreeMap::new(),
        });

        assert_ne!(
            state_init1.derive_account_id(),
            state_init2.derive_account_id(),
            "Different code references should produce different account IDs"
        );
    }

    #[test]
    fn test_access_key_permission_discriminants() {
        let fc = AccessKeyPermission::FunctionCall(FunctionCallPermission {
            allowance: None,
            receiver_id: "test.near".parse().unwrap(),
            method_names: vec![],
        });
        let bytes = borsh::to_vec(&fc).unwrap();
        assert_eq!(bytes[0], 0, "FunctionCall should have discriminant 0");

        let fa = AccessKeyPermission::FullAccess;
        let bytes = borsh::to_vec(&fa).unwrap();
        assert_eq!(bytes[0], 1, "FullAccess should have discriminant 1");

        let gkfc = AccessKeyPermission::GasKeyFunctionCall(
            GasKeyInfo {
                balance: NearToken::from_near(1),
                num_nonces: 5,
            },
            FunctionCallPermission {
                allowance: None,
                receiver_id: "test.near".parse().unwrap(),
                method_names: vec![],
            },
        );
        let bytes = borsh::to_vec(&gkfc).unwrap();
        assert_eq!(bytes[0], 2, "GasKeyFunctionCall should have discriminant 2");

        let gkfa = AccessKeyPermission::GasKeyFullAccess(GasKeyInfo {
            balance: NearToken::from_near(1),
            num_nonces: 5,
        });
        let bytes = borsh::to_vec(&gkfa).unwrap();
        assert_eq!(bytes[0], 3, "GasKeyFullAccess should have discriminant 3");
    }

    #[test]
    fn test_derive_account_id_different_data() {
        // Different data should produce different account IDs
        let mut data = BTreeMap::new();
        data.insert(b"key".to_vec(), b"value".to_vec());

        let state_init1 = DeterministicAccountStateInit::V1(DeterministicAccountStateInitV1 {
            code: GlobalContractIdentifier::AccountId("publisher.near".parse().unwrap()),
            data: BTreeMap::new(),
        });

        let state_init2 = DeterministicAccountStateInit::V1(DeterministicAccountStateInitV1 {
            code: GlobalContractIdentifier::AccountId("publisher.near".parse().unwrap()),
            data,
        });

        assert_ne!(
            state_init1.derive_account_id(),
            state_init2.derive_account_id(),
            "Different data should produce different account IDs"
        );
    }

    // ========================================================================
    // Deterministic Types JSON Serialization Tests
    // ========================================================================

    #[test]
    fn test_deterministic_state_init_json_roundtrip() {
        // Build a DeterministicAccountStateInit with non-trivial data
        let hash = CryptoHash::hash(&[1, 2, 3, 4]);
        let mut data = BTreeMap::new();
        data.insert(b"key1".to_vec(), b"value1".to_vec());
        data.insert(b"key2".to_vec(), b"value2".to_vec());

        let state_init = DeterministicAccountStateInit::V1(DeterministicAccountStateInitV1 {
            code: GlobalContractIdentifier::CodeHash(hash),
            data: data.clone(),
        });

        // Serialize to JSON
        let json = serde_json::to_value(&state_init).unwrap();

        // Verify externally-tagged format: {"V1": {...}} (matching nearcore)
        assert!(
            json.get("V1").is_some(),
            "Expected externally-tagged 'V1' key, got: {json}"
        );
        let v1 = json.get("V1").unwrap();
        assert!(v1.get("code").is_some(), "Expected 'code' field in V1");
        assert!(v1.get("data").is_some(), "Expected 'data' field in V1");

        // Verify data keys/values are base64-encoded
        let data_obj = v1.get("data").unwrap().as_object().unwrap();
        // "key1" in base64 is "a2V5MQ=="
        assert!(
            data_obj.contains_key("a2V5MQ=="),
            "Expected base64-encoded key 'a2V5MQ==', got keys: {:?}",
            data_obj.keys().collect::<Vec<_>>()
        );

        // Round-trip back
        let deserialized: DeterministicAccountStateInit = serde_json::from_value(json).unwrap();
        let DeterministicAccountStateInit::V1(v1_decoded) = deserialized;
        assert_eq!(v1_decoded.code, GlobalContractIdentifier::CodeHash(hash));
        assert_eq!(v1_decoded.data, data);
    }

    #[test]
    fn test_global_contract_identifier_json_roundtrip() {
        // CodeHash variant
        let hash = CryptoHash::hash(&[1, 2, 3]);
        let id = GlobalContractIdentifier::CodeHash(hash);
        let json = serde_json::to_string(&id).unwrap();
        let decoded: GlobalContractIdentifier = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded, id);

        // AccountId variant
        let account_id: AccountId = "test.near".parse().unwrap();
        let id = GlobalContractIdentifier::AccountId(account_id);
        let json = serde_json::to_string(&id).unwrap();
        let decoded: GlobalContractIdentifier = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded, id);
    }

    #[test]
    fn test_deterministic_state_init_action_json_roundtrip() {
        let action = DeterministicStateInitAction {
            state_init: DeterministicAccountStateInit::V1(DeterministicAccountStateInitV1 {
                code: GlobalContractIdentifier::AccountId("publisher.near".parse().unwrap()),
                data: BTreeMap::new(),
            }),
            deposit: NearToken::from_near(5),
        };

        let json = serde_json::to_string(&action).unwrap();
        let decoded: DeterministicStateInitAction = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded, action);
    }
}