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
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
//! RPC response types.

use std::collections::BTreeMap;

use base64::{Engine as _, engine::general_purpose::STANDARD};
use serde::Deserialize;
use serde_with::{base64::Base64, serde_as};

use super::block_reference::TxExecutionStatus;
use super::error::{ActionError, TxExecutionError};
use super::{AccountId, CryptoHash, Gas, NearToken, PublicKey, Signature};

// ============================================================================
// Constants
// ============================================================================

/// Cost per byte of storage in yoctoNEAR.
///
/// This is a protocol constant (10^19 yoctoNEAR per byte = 0.00001 NEAR/byte).
/// It has remained unchanged since NEAR genesis and would require a hard fork
/// to modify. Used for calculating available balance.
///
/// See: <https://docs.near.org/concepts/storage/storage-staking>
pub const STORAGE_AMOUNT_PER_BYTE: u128 = 10_000_000_000_000_000_000; // 10^19 yoctoNEAR

// ============================================================================
// Account types
// ============================================================================

/// Account information from view_account RPC.
#[derive(Debug, Clone, Deserialize)]
pub struct AccountView {
    /// Total balance including locked.
    pub amount: NearToken,
    /// Locked balance (staked).
    pub locked: NearToken,
    /// Hash of deployed contract code (or zeros if none).
    pub code_hash: CryptoHash,
    /// Storage used in bytes.
    pub storage_usage: u64,
    /// Storage paid at block height (deprecated, always 0).
    #[serde(default)]
    pub storage_paid_at: u64,
    /// Global contract code hash (if using a global contract).
    #[serde(default)]
    pub global_contract_hash: Option<CryptoHash>,
    /// Global contract account ID (if using a global contract by account).
    #[serde(default)]
    pub global_contract_account_id: Option<AccountId>,
    /// Block height of the query.
    pub block_height: u64,
    /// Block hash of the query.
    pub block_hash: CryptoHash,
}

impl AccountView {
    /// Calculate the total NEAR required for storage.
    fn storage_required(&self) -> NearToken {
        let yocto = STORAGE_AMOUNT_PER_BYTE.saturating_mul(self.storage_usage as u128);
        NearToken::from_yoctonear(yocto)
    }

    /// Get available (spendable) balance.
    ///
    /// This accounts for the protocol rule that staked tokens count towards
    /// the storage requirement:
    /// - available = amount - max(0, storage_required - locked)
    ///
    /// If staked >= storage cost, all liquid balance is available.
    /// If staked < storage cost, some liquid balance is reserved for storage.
    pub fn available(&self) -> NearToken {
        let storage_required = self.storage_required();

        // If staked covers storage, all liquid is available
        if self.locked >= storage_required {
            return self.amount;
        }

        // Otherwise, reserve the difference from liquid balance
        let reserved_for_storage = storage_required.saturating_sub(self.locked);
        self.amount.saturating_sub(reserved_for_storage)
    }

    /// Get the amount of NEAR reserved for storage costs.
    ///
    /// This is calculated as: max(0, storage_required - locked)
    pub fn storage_cost(&self) -> NearToken {
        let storage_required = self.storage_required();

        if self.locked >= storage_required {
            NearToken::ZERO
        } else {
            storage_required.saturating_sub(self.locked)
        }
    }

    /// Check if this account has a deployed contract.
    pub fn has_contract(&self) -> bool {
        !self.code_hash.is_zero()
    }
}

/// Simplified balance info.
#[derive(Debug, Clone)]
pub struct AccountBalance {
    /// Total balance (available + locked).
    pub total: NearToken,
    /// Available balance (spendable, accounting for storage).
    pub available: NearToken,
    /// Locked balance (staked).
    pub locked: NearToken,
    /// Amount reserved for storage costs.
    pub storage_cost: NearToken,
    /// Storage used in bytes.
    pub storage_usage: u64,
}

impl std::fmt::Display for AccountBalance {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.available)
    }
}

impl From<AccountView> for AccountBalance {
    fn from(view: AccountView) -> Self {
        Self {
            total: view.amount,
            available: view.available(),
            locked: view.locked,
            storage_cost: view.storage_cost(),
            storage_usage: view.storage_usage,
        }
    }
}

/// Access key information from view_access_key RPC.
#[derive(Debug, Clone, Deserialize)]
pub struct AccessKeyView {
    /// Nonce for replay protection.
    pub nonce: u64,
    /// Permission level.
    pub permission: AccessKeyPermissionView,
    /// Block height of the query.
    pub block_height: u64,
    /// Block hash of the query.
    pub block_hash: CryptoHash,
}

/// Access key details (without block info, used in lists).
#[derive(Debug, Clone, Deserialize)]
pub struct AccessKeyDetails {
    /// Nonce for replay protection.
    pub nonce: u64,
    /// Permission level.
    pub permission: AccessKeyPermissionView,
}

/// Access key permission from RPC.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum AccessKeyPermissionView {
    /// Full access.
    FullAccess,
    /// Function call access with restrictions.
    FunctionCall {
        /// Maximum amount this key can spend.
        allowance: Option<NearToken>,
        /// Contract that can be called.
        receiver_id: AccountId,
        /// Methods that can be called (empty = all).
        method_names: Vec<String>,
    },
    /// Gas key with function call access.
    GasKeyFunctionCall {
        /// Gas key balance.
        balance: NearToken,
        /// Number of nonces.
        num_nonces: u16,
        /// Maximum amount this key can spend.
        allowance: Option<NearToken>,
        /// Contract that can be called.
        receiver_id: AccountId,
        /// Methods that can be called (empty = all).
        method_names: Vec<String>,
    },
    /// Gas key with full access.
    GasKeyFullAccess {
        /// Gas key balance.
        balance: NearToken,
        /// Number of nonces.
        num_nonces: u16,
    },
}

/// Access key list from view_access_key_list RPC.
#[derive(Debug, Clone, Deserialize)]
pub struct AccessKeyListView {
    /// List of access keys.
    pub keys: Vec<AccessKeyInfoView>,
    /// Block height of the query.
    pub block_height: u64,
    /// Block hash of the query.
    pub block_hash: CryptoHash,
}

/// Single access key info in list.
#[derive(Debug, Clone, Deserialize)]
pub struct AccessKeyInfoView {
    /// Public key.
    pub public_key: PublicKey,
    /// Access key details.
    pub access_key: AccessKeyDetails,
}

// ============================================================================
// Block types
// ============================================================================

/// Block information from block RPC.
#[derive(Debug, Clone, Deserialize)]
pub struct BlockView {
    /// Block author (validator account ID).
    pub author: AccountId,
    /// Block header.
    pub header: BlockHeaderView,
    /// List of chunks in the block.
    pub chunks: Vec<ChunkHeaderView>,
}

/// Block header with full details.
#[derive(Debug, Clone, Deserialize)]
pub struct BlockHeaderView {
    /// Block height.
    pub height: u64,
    /// Previous block height (may be None for genesis).
    #[serde(default)]
    pub prev_height: Option<u64>,
    /// Block hash.
    pub hash: CryptoHash,
    /// Previous block hash.
    pub prev_hash: CryptoHash,
    /// Previous state root.
    pub prev_state_root: CryptoHash,
    /// Chunk receipts root.
    pub chunk_receipts_root: CryptoHash,
    /// Chunk headers root.
    pub chunk_headers_root: CryptoHash,
    /// Chunk transaction root.
    pub chunk_tx_root: CryptoHash,
    /// Outcome root.
    pub outcome_root: CryptoHash,
    /// Number of chunks included.
    pub chunks_included: u64,
    /// Challenges root.
    pub challenges_root: CryptoHash,
    /// Timestamp in nanoseconds (as u64).
    pub timestamp: u64,
    /// Timestamp in nanoseconds (as string for precision).
    pub timestamp_nanosec: String,
    /// Random value for the block.
    pub random_value: CryptoHash,
    /// Validator proposals.
    #[serde(default)]
    pub validator_proposals: Vec<ValidatorStakeView>,
    /// Chunk mask (which shards have chunks).
    #[serde(default)]
    pub chunk_mask: Vec<bool>,
    /// Gas price for this block.
    pub gas_price: NearToken,
    /// Block ordinal (may be None).
    #[serde(default)]
    pub block_ordinal: Option<u64>,
    /// Total supply of NEAR tokens.
    pub total_supply: NearToken,
    /// Challenges result.
    #[serde(default)]
    pub challenges_result: Vec<SlashedValidator>,
    /// Last final block hash.
    pub last_final_block: CryptoHash,
    /// Last DS final block hash.
    pub last_ds_final_block: CryptoHash,
    /// Epoch ID.
    pub epoch_id: CryptoHash,
    /// Next epoch ID.
    pub next_epoch_id: CryptoHash,
    /// Next block producer hash.
    pub next_bp_hash: CryptoHash,
    /// Block merkle root.
    pub block_merkle_root: CryptoHash,
    /// Epoch sync data hash (optional).
    #[serde(default)]
    pub epoch_sync_data_hash: Option<CryptoHash>,
    /// Block body hash (optional, added in later protocol versions).
    #[serde(default)]
    pub block_body_hash: Option<CryptoHash>,
    /// Block approvals (nullable signatures).
    #[serde(default)]
    pub approvals: Vec<Option<Signature>>,
    /// Block signature.
    pub signature: Signature,
    /// Latest protocol version.
    pub latest_protocol_version: u32,
    /// Rent paid (deprecated; when present, always 0).
    #[serde(default)]
    pub rent_paid: Option<NearToken>,
    /// Validator reward (deprecated; when present, always 0).
    #[serde(default)]
    pub validator_reward: Option<NearToken>,
    /// Chunk endorsements (optional).
    #[serde(default)]
    pub chunk_endorsements: Option<Vec<Vec<u8>>>,
    /// Shard split info (optional).
    #[serde(default)]
    pub shard_split: Option<(u64, AccountId)>,
}

/// Validator stake (versioned).
///
/// Used for validator proposals in block/chunk headers.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum ValidatorStakeView {
    /// Version 1 (current).
    V1(ValidatorStakeViewV1),
}

/// Validator stake data.
#[derive(Debug, Clone, Deserialize)]
pub struct ValidatorStakeViewV1 {
    /// Validator account ID.
    pub account_id: AccountId,
    /// Public key.
    pub public_key: PublicKey,
    /// Stake amount.
    pub stake: NearToken,
}

impl ValidatorStakeView {
    /// Get the inner V1 data.
    pub fn into_v1(self) -> ValidatorStakeViewV1 {
        match self {
            Self::V1(v) => v,
        }
    }

    /// Get the account ID.
    pub fn account_id(&self) -> &AccountId {
        match self {
            Self::V1(v) => &v.account_id,
        }
    }

    /// Get the stake amount.
    pub fn stake(&self) -> NearToken {
        match self {
            Self::V1(v) => v.stake,
        }
    }
}

/// Slashed validator from challenge results.
#[derive(Debug, Clone, Deserialize)]
pub struct SlashedValidator {
    /// Validator account ID.
    pub account_id: AccountId,
    /// Whether this was a double sign.
    pub is_double_sign: bool,
}

/// Chunk header with full details.
#[derive(Debug, Clone, Deserialize)]
pub struct ChunkHeaderView {
    /// Chunk hash.
    pub chunk_hash: CryptoHash,
    /// Previous block hash.
    pub prev_block_hash: CryptoHash,
    /// Outcome root.
    pub outcome_root: CryptoHash,
    /// Previous state root.
    pub prev_state_root: CryptoHash,
    /// Encoded merkle root.
    pub encoded_merkle_root: CryptoHash,
    /// Encoded length.
    pub encoded_length: u64,
    /// Height when chunk was created.
    pub height_created: u64,
    /// Height when chunk was included.
    pub height_included: u64,
    /// Shard ID.
    pub shard_id: u64,
    /// Gas used in this chunk.
    pub gas_used: u64,
    /// Gas limit for this chunk.
    pub gas_limit: u64,
    /// Validator reward.
    pub validator_reward: NearToken,
    /// Balance burnt.
    pub balance_burnt: NearToken,
    /// Outgoing receipts root.
    pub outgoing_receipts_root: CryptoHash,
    /// Transaction root.
    pub tx_root: CryptoHash,
    /// Validator proposals.
    #[serde(default)]
    pub validator_proposals: Vec<ValidatorStakeView>,
    /// Congestion info (optional, added in later protocol versions).
    #[serde(default)]
    pub congestion_info: Option<CongestionInfoView>,
    /// Bandwidth requests (optional, added in later protocol versions).
    #[serde(default)]
    pub bandwidth_requests: Option<BandwidthRequests>,
    /// Rent paid (deprecated; when present, always 0).
    #[serde(default)]
    pub rent_paid: Option<NearToken>,
    /// Proposed trie split for resharding.
    ///
    /// - `None` — field absent (older protocol versions)
    /// - `Some(None)` — field present as JSON `null` (no split proposed)
    /// - `Some(Some(split))` — active split proposal
    #[serde(default)]
    pub proposed_split: Option<Option<TrieSplit>>,
    /// Chunk signature.
    pub signature: Signature,
}

/// Bandwidth requests for a chunk (versioned).
#[derive(Debug, Clone, Deserialize)]
pub enum BandwidthRequests {
    /// Version 1.
    V1(BandwidthRequestsV1),
}

/// Bandwidth requests data (V1).
#[derive(Debug, Clone, Deserialize)]
pub struct BandwidthRequestsV1 {
    /// List of bandwidth requests.
    pub requests: Vec<BandwidthRequest>,
}

/// A single bandwidth request to a target shard.
#[derive(Debug, Clone, Deserialize)]
pub struct BandwidthRequest {
    /// Target shard index.
    pub to_shard: u16,
    /// Bitmap of requested values.
    pub requested_values_bitmap: BandwidthRequestBitmap,
}

/// Bitmap for bandwidth request values.
#[derive(Debug, Clone, Deserialize)]
pub struct BandwidthRequestBitmap {
    /// Raw bitmap data.
    pub data: [u8; 5],
}

/// Trie split information for resharding.
#[derive(Debug, Clone, Deserialize)]
pub struct TrieSplit {
    /// Account boundary for the split.
    pub boundary_account: AccountId,
    /// Memory usage of the left child.
    pub left_memory: u64,
    /// Memory usage of the right child.
    pub right_memory: u64,
}

/// Congestion information for a shard.
#[derive(Debug, Clone, Deserialize)]
pub struct CongestionInfoView {
    /// Gas used by delayed receipts.
    #[serde(default, deserialize_with = "dec_format")]
    pub delayed_receipts_gas: u128,
    /// Gas used by buffered receipts.
    #[serde(default, deserialize_with = "dec_format")]
    pub buffered_receipts_gas: u128,
    /// Bytes used by receipts.
    #[serde(default)]
    pub receipt_bytes: u64,
    /// Allowed shard.
    #[serde(default)]
    pub allowed_shard: u16,
}

/// Deserialize a u128 from a decimal string (NEAR RPC sends u128 as strings).
fn dec_format<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<u128, D::Error> {
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum StringOrNum {
        String(String),
        Num(u128),
    }
    match StringOrNum::deserialize(deserializer)? {
        StringOrNum::String(s) => s.parse().map_err(serde::de::Error::custom),
        StringOrNum::Num(n) => Ok(n),
    }
}

/// Deserialize a Gas (u64) from a decimal string or number.
fn gas_dec_format<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Gas, D::Error> {
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum StringOrNum {
        String(String),
        Num(u64),
    }
    let raw = match StringOrNum::deserialize(deserializer)? {
        StringOrNum::String(s) => s.parse::<u64>().map_err(serde::de::Error::custom)?,
        StringOrNum::Num(n) => n,
    };
    Ok(Gas::from_gas(raw))
}

/// Gas price response.
#[derive(Debug, Clone, Deserialize)]
pub struct GasPrice {
    /// Gas price in yoctoNEAR.
    pub gas_price: NearToken,
}

impl GasPrice {
    /// Get gas price as u128.
    pub fn as_u128(&self) -> u128 {
        self.gas_price.as_yoctonear()
    }
}

// ============================================================================
// Transaction outcome types
// ============================================================================

/// Overall transaction execution status.
///
/// Represents the final result of a transaction, matching nearcore's `FinalExecutionStatus`.
/// This is the `status` field in `FinalExecutionOutcome`.
#[derive(Debug, Clone, Default, Deserialize)]
pub enum FinalExecutionStatus {
    /// The transaction has not yet started execution.
    #[default]
    NotStarted,
    /// The transaction has started but the first receipt hasn't completed.
    Started,
    /// The transaction execution failed.
    Failure(TxExecutionError),
    /// The transaction execution succeeded (base64-encoded return value).
    SuccessValue(String),
}

/// Response returned for non-executed wait levels.
///
/// When you use a non-executed wait level ([`Submitted`](crate::types::Submitted),
/// [`Included`](crate::types::Included), [`IncludedFinal`](crate::types::IncludedFinal)),
/// the transaction hasn't been executed yet so there's no outcome to return.
/// This type gives you the information needed to poll for the result later
/// via [`Near::tx_status`](crate::Near::tx_status).
///
/// # Example
///
/// ```rust,no_run
/// # use near_kit::*;
/// # async fn example(near: &Near) -> Result<(), Error> {
/// let response = near.transfer("bob.testnet", NearToken::from_near(1))
///     .wait_until(Included)
///     .await?;
///
/// // Later, poll for the full outcome:
/// let outcome = near.tx_status(
///     &response.transaction_hash,
///     &response.sender_id,
///     Final,
/// ).await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct SendTxResponse {
    /// Hash of the submitted transaction.
    pub transaction_hash: CryptoHash,
    /// Account ID of the transaction signer.
    pub sender_id: AccountId,
}

/// Raw RPC response for transaction submission/status (internal).
///
/// Used internally to deserialize responses from `send_tx` and
/// `EXPERIMENTAL_tx_status` before converting to user-facing types
/// via [`WaitLevel::convert`](crate::types::WaitLevel::convert).
#[doc(hidden)]
#[derive(Debug, Clone, Deserialize)]
pub struct RawTransactionResponse {
    /// Transaction hash — populated after deserialization from the signed tx
    /// (for `send_tx`) or from the outcome (for `tx_status`).
    #[serde(skip)]
    pub transaction_hash: CryptoHash,
    /// The wait level that was reached.
    pub final_execution_status: TxExecutionStatus,
    /// The execution outcome, present when the transaction has been executed.
    #[serde(flatten)]
    pub outcome: Option<FinalExecutionOutcome>,
}

/// Final execution outcome from a NEAR transaction.
///
/// Returned by both `send_tx` and `EXPERIMENTAL_tx_status` RPC methods.
/// All fields are required — this type only appears when a transaction has
/// actually been executed (not for non-executed wait levels).
///
/// The `receipts` field contains full receipt details when the outcome comes
/// from `EXPERIMENTAL_tx_status` (i.e. `near.tx_status()`). When the outcome
/// comes from `send_tx` (i.e. `near.send()`), this field is an empty `Vec`.
#[derive(Debug, Clone, Deserialize)]
pub struct FinalExecutionOutcome {
    /// Overall transaction execution result.
    pub status: FinalExecutionStatus,
    /// The transaction that was executed.
    pub transaction: TransactionView,
    /// Outcome of the transaction itself.
    pub transaction_outcome: ExecutionOutcomeWithId,
    /// Outcomes of all receipts spawned by the transaction.
    pub receipts_outcome: Vec<ExecutionOutcomeWithId>,
    /// Full receipt details (populated by `tx_status`, empty from `send`).
    #[serde(default)]
    pub receipts: Vec<Receipt>,
}

impl FinalExecutionOutcome {
    /// Check if the transaction succeeded.
    pub fn is_success(&self) -> bool {
        matches!(&self.status, FinalExecutionStatus::SuccessValue(_))
    }

    /// Check if the transaction failed.
    pub fn is_failure(&self) -> bool {
        matches!(&self.status, FinalExecutionStatus::Failure(_))
    }

    /// Get the failure message if present.
    pub fn failure_message(&self) -> Option<String> {
        match &self.status {
            FinalExecutionStatus::Failure(err) => Some(err.to_string()),
            _ => None,
        }
    }

    /// Get the typed execution error if present.
    pub fn failure_error(&self) -> Option<&TxExecutionError> {
        match &self.status {
            FinalExecutionStatus::Failure(err) => Some(err),
            _ => None,
        }
    }

    /// Get the transaction hash.
    pub fn transaction_hash(&self) -> &CryptoHash {
        &self.transaction_outcome.id
    }

    /// Get total gas used across all receipts.
    pub fn total_gas_used(&self) -> Gas {
        let tx_gas = self.transaction_outcome.outcome.gas_burnt.as_gas();
        let receipt_gas: u64 = self
            .receipts_outcome
            .iter()
            .map(|r| r.outcome.gas_burnt.as_gas())
            .sum();
        Gas::from_gas(tx_gas + receipt_gas)
    }

    /// Get the return value as raw bytes (base64-decoded).
    ///
    /// Returns `Err` if the execution status is not `SuccessValue` (including
    /// transaction validation or action failures), or if the value is not
    /// valid base64.
    ///
    /// Note: When using the high-level transaction API, only transaction
    /// *validation* failures return `Err(Error::InvalidTx(..))` from the
    /// send call. On-chain action failures are returned as `Ok(outcome)`
    /// with `outcome.is_failure() == true`. This method is primarily useful
    /// when working with the low-level `rpc().send_tx()` API or when you
    /// already have an outcome and want to decode its return value.
    pub fn result(&self) -> Result<Vec<u8>, crate::error::Error> {
        match &self.status {
            FinalExecutionStatus::Failure(TxExecutionError::InvalidTxError(e)) => {
                Err(crate::error::Error::InvalidTx(Box::new(e.clone())))
            }
            FinalExecutionStatus::Failure(TxExecutionError::ActionError(e)) => Err(
                crate::error::Error::InvalidTransaction(format!("Action error: {e}")),
            ),
            FinalExecutionStatus::SuccessValue(s) => STANDARD.decode(s).map_err(|e| {
                crate::error::Error::InvalidTransaction(format!(
                    "Failed to decode base64 SuccessValue: {e}"
                ))
            }),
            other => Err(crate::error::Error::InvalidTransaction(format!(
                "Transaction status is {:?}, expected SuccessValue",
                other,
            ))),
        }
    }

    /// Deserialize the return value as JSON.
    ///
    /// Returns `Err` if `result()` fails (on-chain failure, unexpected status,
    /// or invalid base64) or if JSON deserialization fails.
    pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, crate::error::Error> {
        let bytes = self.result()?;
        serde_json::from_slice(&bytes).map_err(crate::error::Error::from)
    }
}

/// Per-receipt execution status.
///
/// Matches nearcore's `ExecutionStatusView`. Used in [`ExecutionOutcome`].
///
/// The `Failure` variant contains an [`ActionError`] rather than
/// [`TxExecutionError`] because receipt execution outcomes can only fail with
/// action errors. Transaction-validation errors (`InvalidTxError`) are caught
/// earlier in the send path and surfaced as [`crate::error::Error::InvalidTx`].
///
/// The NEAR RPC serialises the failure as `{"Failure": {"ActionError": {…}}}`.
/// A custom [`Deserialize`] impl unwraps the outer `TxExecutionError` envelope.
#[derive(Debug, Clone)]
pub enum ExecutionStatus {
    /// The execution is pending or unknown.
    Unknown,
    /// Execution failed with an action error.
    Failure(ActionError),
    /// Execution succeeded with a return value.
    SuccessValue(Vec<u8>),
    /// Execution succeeded, producing a receipt.
    SuccessReceiptId(CryptoHash),
}

impl<'de> serde::Deserialize<'de> for ExecutionStatus {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        /// Mirror of the on-wire format that serde can derive.
        #[serde_as]
        #[derive(Deserialize)]
        enum Raw {
            Unknown,
            Failure(TxExecutionError),
            SuccessValue(#[serde_as(as = "Base64")] Vec<u8>),
            SuccessReceiptId(CryptoHash),
        }

        match Raw::deserialize(deserializer)? {
            Raw::Unknown => Ok(Self::Unknown),
            Raw::Failure(TxExecutionError::ActionError(e)) => Ok(Self::Failure(e)),
            Raw::Failure(TxExecutionError::InvalidTxError(e)) => Err(serde::de::Error::custom(
                format!("unexpected InvalidTxError in receipt execution status: {e}"),
            )),
            Raw::SuccessValue(v) => Ok(Self::SuccessValue(v)),
            Raw::SuccessReceiptId(h) => Ok(Self::SuccessReceiptId(h)),
        }
    }
}

/// Transaction view in outcome.
#[derive(Debug, Clone, Deserialize)]
pub struct TransactionView {
    /// Signer account.
    pub signer_id: AccountId,
    /// Signer public key.
    pub public_key: PublicKey,
    /// Transaction nonce.
    pub nonce: u64,
    /// Receiver account.
    pub receiver_id: AccountId,
    /// Transaction hash.
    pub hash: CryptoHash,
    /// Actions in the transaction.
    #[serde(default)]
    pub actions: Vec<ActionView>,
    /// Transaction signature.
    pub signature: Signature,
    /// Priority fee (optional, for congestion pricing).
    #[serde(default)]
    pub priority_fee: Option<u64>,
    /// Nonce index (for gas key multi-nonce support).
    #[serde(default)]
    pub nonce_index: Option<u16>,
}

// ============================================================================
// Global contract identifier view
// ============================================================================

/// Backward-compatible deserialization helper for `GlobalContractIdentifierView`.
///
/// Handles both the new format (`{"hash": "<base58>"}` / `{"account_id": "alice.near"}`)
/// and the deprecated format (bare string `"<base58>"` / `"alice.near"`).
#[derive(Deserialize)]
#[serde(untagged)]
enum GlobalContractIdCompat {
    CodeHash { hash: CryptoHash },
    AccountId { account_id: AccountId },
    DeprecatedCodeHash(CryptoHash),
    DeprecatedAccountId(AccountId),
}

/// Global contract identifier in RPC view responses.
///
/// Identifies a global contract either by its code hash (immutable) or by the
/// publishing account ID (updatable). Supports both the current and deprecated
/// JSON serialization formats from nearcore.
#[derive(Debug, Clone, Deserialize)]
#[serde(from = "GlobalContractIdCompat")]
pub enum GlobalContractIdentifierView {
    /// Referenced by code hash.
    CodeHash(CryptoHash),
    /// Referenced by publisher account ID.
    AccountId(AccountId),
}

impl From<GlobalContractIdCompat> for GlobalContractIdentifierView {
    fn from(compat: GlobalContractIdCompat) -> Self {
        match compat {
            GlobalContractIdCompat::CodeHash { hash }
            | GlobalContractIdCompat::DeprecatedCodeHash(hash) => Self::CodeHash(hash),
            GlobalContractIdCompat::AccountId { account_id }
            | GlobalContractIdCompat::DeprecatedAccountId(account_id) => {
                Self::AccountId(account_id)
            }
        }
    }
}

impl std::fmt::Display for GlobalContractIdentifierView {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::CodeHash(hash) => write!(f, "hash({hash})"),
            Self::AccountId(account_id) => write!(f, "{account_id}"),
        }
    }
}

// ============================================================================
// Action view
// ============================================================================

/// View of a delegate action in RPC responses.
#[derive(Debug, Clone, Deserialize)]
pub struct DelegateActionView {
    /// The account that signed the delegate action.
    pub sender_id: AccountId,
    /// The intended receiver of the inner actions.
    pub receiver_id: AccountId,
    /// The actions to execute.
    pub actions: Vec<ActionView>,
    /// Nonce for replay protection.
    pub nonce: u64,
    /// Maximum block height before this delegate action expires.
    pub max_block_height: u64,
    /// Public key of the signer.
    pub public_key: PublicKey,
}

/// Action view in transaction.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum ActionView {
    CreateAccount,
    DeployContract {
        code: String, // base64
    },
    FunctionCall {
        method_name: String,
        args: String, // base64
        gas: Gas,
        deposit: NearToken,
    },
    Transfer {
        deposit: NearToken,
    },
    Stake {
        stake: NearToken,
        public_key: PublicKey,
    },
    AddKey {
        public_key: PublicKey,
        access_key: AccessKeyDetails,
    },
    DeleteKey {
        public_key: PublicKey,
    },
    DeleteAccount {
        beneficiary_id: AccountId,
    },
    Delegate {
        delegate_action: DelegateActionView,
        signature: Signature,
    },
    #[serde(rename = "DeployGlobalContract")]
    DeployGlobalContract {
        code: String,
    },
    #[serde(rename = "DeployGlobalContractByAccountId")]
    DeployGlobalContractByAccountId {
        code: String,
    },
    #[serde(rename = "UseGlobalContract")]
    UseGlobalContract {
        code_hash: CryptoHash,
    },
    #[serde(rename = "UseGlobalContractByAccountId")]
    UseGlobalContractByAccountId {
        account_id: AccountId,
    },
    #[serde(rename = "DeterministicStateInit")]
    DeterministicStateInit {
        code: GlobalContractIdentifierView,
        #[serde(default)]
        data: BTreeMap<String, String>,
        deposit: NearToken,
    },
    TransferToGasKey {
        public_key: PublicKey,
        deposit: NearToken,
    },
    WithdrawFromGasKey {
        public_key: PublicKey,
        amount: NearToken,
    },
}

/// Merkle path item for cryptographic proofs.
#[derive(Debug, Clone, Deserialize)]
pub struct MerklePathItem {
    /// Hash at this node.
    pub hash: CryptoHash,
    /// Direction of the path.
    pub direction: MerkleDirection,
}

/// Direction in merkle path.
#[derive(Debug, Clone, Deserialize)]
pub enum MerkleDirection {
    Left,
    Right,
}

/// Execution outcome with ID.
#[derive(Debug, Clone, Deserialize)]
pub struct ExecutionOutcomeWithId {
    /// Receipt or transaction ID.
    pub id: CryptoHash,
    /// Outcome details.
    pub outcome: ExecutionOutcome,
    /// Proof of execution.
    #[serde(default)]
    pub proof: Vec<MerklePathItem>,
    /// Block hash where this was executed.
    pub block_hash: CryptoHash,
}

/// Execution outcome details.
#[derive(Debug, Clone, Deserialize)]
pub struct ExecutionOutcome {
    /// Executor account.
    pub executor_id: AccountId,
    /// Gas burnt during execution.
    pub gas_burnt: Gas,
    /// Tokens burnt for gas.
    pub tokens_burnt: NearToken,
    /// Logs emitted.
    pub logs: Vec<String>,
    /// Receipt IDs generated.
    pub receipt_ids: Vec<CryptoHash>,
    /// Execution status.
    pub status: ExecutionStatus,
    /// Execution metadata (gas profiling).
    #[serde(default)]
    pub metadata: Option<ExecutionMetadata>,
}

/// Execution metadata with gas profiling.
#[derive(Debug, Clone, Deserialize)]
pub struct ExecutionMetadata {
    /// Metadata version.
    pub version: u32,
    /// Gas profile entries.
    #[serde(default)]
    pub gas_profile: Option<Vec<GasProfileEntry>>,
}

/// Gas profile entry for detailed gas accounting.
#[derive(Debug, Clone, Deserialize)]
pub struct GasProfileEntry {
    /// Cost category (ACTION_COST or WASM_HOST_COST).
    pub cost_category: String,
    /// Cost name.
    pub cost: String,
    /// Gas used for this cost.
    #[serde(deserialize_with = "gas_dec_format")]
    pub gas_used: Gas,
}

/// View function result from call_function RPC.
#[derive(Debug, Clone, Deserialize)]
pub struct ViewFunctionResult {
    /// Result bytes (often JSON).
    pub result: Vec<u8>,
    /// Logs emitted during view call.
    pub logs: Vec<String>,
    /// Block height of the query.
    pub block_height: u64,
    /// Block hash of the query.
    pub block_hash: CryptoHash,
}

impl ViewFunctionResult {
    /// Get the result as raw bytes.
    pub fn bytes(&self) -> &[u8] {
        &self.result
    }

    /// Get the result as a string.
    pub fn as_string(&self) -> Result<String, std::string::FromUtf8Error> {
        String::from_utf8(self.result.clone())
    }

    /// Deserialize the result as JSON.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let result = rpc.view_function(&contract, "get_data", &[], block).await?;
    /// let data: MyData = result.json()?;
    /// ```
    pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
        serde_json::from_slice(&self.result)
    }

    /// Deserialize the result as Borsh.
    ///
    /// Use this for contracts that return Borsh-encoded data instead of JSON.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let result = rpc.view_function(&contract, "get_state", &args, block).await?;
    /// let state: ContractState = result.borsh()?;
    /// ```
    pub fn borsh<T: borsh::BorshDeserialize>(&self) -> Result<T, borsh::io::Error> {
        borsh::from_slice(&self.result)
    }
}

// ============================================================================
// Receipt types (for EXPERIMENTAL_tx_status)
// ============================================================================

/// Receipt from EXPERIMENTAL_tx_status.
#[derive(Debug, Clone, Deserialize)]
pub struct Receipt {
    /// Predecessor account that created this receipt.
    pub predecessor_id: AccountId,
    /// Receiver account for this receipt.
    pub receiver_id: AccountId,
    /// Receipt ID.
    pub receipt_id: CryptoHash,
    /// Receipt content (action or data).
    pub receipt: ReceiptContent,
    /// Priority (optional, for congestion pricing).
    #[serde(default)]
    pub priority: Option<u64>,
}

/// Receipt content - action, data, or global contract distribution.
#[derive(Debug, Clone, Deserialize)]
pub enum ReceiptContent {
    /// Action receipt.
    Action(ActionReceiptData),
    /// Data receipt.
    Data(DataReceiptData),
    /// Global contract distribution receipt.
    GlobalContractDistribution {
        /// Global contract identifier.
        id: GlobalContractIdentifierView,
        /// Target shard ID.
        target_shard: u64,
        /// Shards that have already received this contract.
        #[serde(default)]
        already_delivered_shards: Vec<u64>,
        /// Code bytes (base64).
        code: String,
        /// Nonce (present in v2 receipts).
        #[serde(default)]
        nonce: Option<u64>,
    },
}

/// Data receiver for output data in action receipts.
#[derive(Debug, Clone, Deserialize)]
pub struct DataReceiverView {
    /// Data ID.
    pub data_id: CryptoHash,
    /// Receiver account ID.
    pub receiver_id: AccountId,
}

/// Action receipt data.
#[derive(Debug, Clone, Deserialize)]
pub struct ActionReceiptData {
    /// Signer account ID.
    pub signer_id: AccountId,
    /// Signer public key.
    pub signer_public_key: PublicKey,
    /// Gas price for this receipt.
    pub gas_price: NearToken,
    /// Output data receivers.
    #[serde(default)]
    pub output_data_receivers: Vec<DataReceiverView>,
    /// Input data IDs.
    #[serde(default)]
    pub input_data_ids: Vec<CryptoHash>,
    /// Actions in this receipt.
    pub actions: Vec<ActionView>,
    /// Whether this is a promise yield.
    #[serde(default)]
    pub is_promise_yield: Option<bool>,
}

/// Data receipt data.
#[derive(Debug, Clone, Deserialize)]
pub struct DataReceiptData {
    /// Data ID.
    pub data_id: CryptoHash,
    /// Data content (optional).
    #[serde(default)]
    pub data: Option<String>,
}

// ============================================================================
// Node status types
// ============================================================================

/// Node status response.
#[derive(Debug, Clone, Deserialize)]
pub struct StatusResponse {
    /// Protocol version.
    pub protocol_version: u32,
    /// Latest protocol version supported.
    pub latest_protocol_version: u32,
    /// Chain ID.
    pub chain_id: String,
    /// Genesis hash.
    pub genesis_hash: CryptoHash,
    /// RPC address.
    #[serde(default)]
    pub rpc_addr: Option<String>,
    /// Node public key.
    #[serde(default)]
    pub node_public_key: Option<String>,
    /// Node key (deprecated).
    #[serde(default)]
    pub node_key: Option<String>,
    /// Validator account ID (if validating).
    #[serde(default)]
    pub validator_account_id: Option<AccountId>,
    /// Validator public key (if validating).
    #[serde(default)]
    pub validator_public_key: Option<PublicKey>,
    /// List of current validators.
    #[serde(default)]
    pub validators: Vec<ValidatorInfo>,
    /// Sync information.
    pub sync_info: SyncInfo,
    /// Node version.
    pub version: NodeVersion,
    /// Uptime in seconds.
    #[serde(default)]
    pub uptime_sec: Option<u64>,
}

/// Validator information.
#[derive(Debug, Clone, Deserialize)]
pub struct ValidatorInfo {
    /// Validator account ID.
    pub account_id: AccountId,
}

/// Sync information.
#[derive(Debug, Clone, Deserialize)]
pub struct SyncInfo {
    /// Latest block hash.
    pub latest_block_hash: CryptoHash,
    /// Latest block height.
    pub latest_block_height: u64,
    /// Latest state root.
    #[serde(default)]
    pub latest_state_root: Option<CryptoHash>,
    /// Latest block timestamp.
    pub latest_block_time: String,
    /// Whether the node is syncing.
    pub syncing: bool,
    /// Earliest block hash (if available).
    #[serde(default)]
    pub earliest_block_hash: Option<CryptoHash>,
    /// Earliest block height (if available).
    #[serde(default)]
    pub earliest_block_height: Option<u64>,
    /// Earliest block time (if available).
    #[serde(default)]
    pub earliest_block_time: Option<String>,
    /// Current epoch ID.
    #[serde(default)]
    pub epoch_id: Option<CryptoHash>,
    /// Epoch start height.
    #[serde(default)]
    pub epoch_start_height: Option<u64>,
}

/// Node version information.
#[derive(Debug, Clone, Deserialize)]
pub struct NodeVersion {
    /// Version string.
    pub version: String,
    /// Build string.
    pub build: String,
    /// Git commit hash.
    #[serde(default)]
    pub commit: Option<String>,
    /// Rust compiler version.
    #[serde(default)]
    pub rustc_version: Option<String>,
}

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

    fn make_account_view(amount: u128, locked: u128, storage_usage: u64) -> AccountView {
        AccountView {
            amount: NearToken::from_yoctonear(amount),
            locked: NearToken::from_yoctonear(locked),
            code_hash: CryptoHash::default(),
            storage_usage,
            storage_paid_at: 0,
            global_contract_hash: None,
            global_contract_account_id: None,
            block_height: 0,
            block_hash: CryptoHash::default(),
        }
    }

    #[test]
    fn test_available_balance_no_stake_no_storage() {
        // No storage, no stake -> all balance is available
        let view = make_account_view(1_000_000_000_000_000_000_000_000, 0, 0); // 1 NEAR
        assert_eq!(view.available(), view.amount);
    }

    #[test]
    fn test_available_balance_with_storage_no_stake() {
        // 1000 bytes storage (= 0.00001 NEAR * 1000 = 0.01 NEAR = 10^22 yocto)
        // Amount: 1 NEAR = 10^24 yocto
        // Available should be: 1 NEAR - 0.01 NEAR = 0.99 NEAR
        let amount = 1_000_000_000_000_000_000_000_000u128; // 1 NEAR
        let storage_usage = 1000u64;
        let storage_cost = STORAGE_AMOUNT_PER_BYTE * storage_usage as u128; // 10^22

        let view = make_account_view(amount, 0, storage_usage);
        let expected = NearToken::from_yoctonear(amount - storage_cost);
        assert_eq!(view.available(), expected);
    }

    #[test]
    fn test_available_balance_stake_covers_storage() {
        // Staked amount >= storage cost -> all liquid balance is available
        // 1000 bytes storage = 10^22 yocto cost
        // 1 NEAR staked = 10^24 yocto (more than storage cost)
        let amount = 1_000_000_000_000_000_000_000_000u128; // 1 NEAR liquid
        let locked = 1_000_000_000_000_000_000_000_000u128; // 1 NEAR staked
        let storage_usage = 1000u64;

        let view = make_account_view(amount, locked, storage_usage);
        // All liquid balance should be available since stake covers storage
        assert_eq!(view.available(), view.amount);
    }

    #[test]
    fn test_available_balance_stake_partially_covers_storage() {
        // Staked = 0.005 NEAR = 5 * 10^21 yocto
        // Storage = 1000 bytes = 0.01 NEAR = 10^22 yocto
        // Reserved = 0.01 - 0.005 = 0.005 NEAR = 5 * 10^21 yocto
        // Amount = 1 NEAR
        // Available = 1 NEAR - 0.005 NEAR = 0.995 NEAR
        let amount = 1_000_000_000_000_000_000_000_000u128; // 1 NEAR
        let locked = 5_000_000_000_000_000_000_000u128; // 0.005 NEAR
        let storage_usage = 1000u64;
        let storage_cost = STORAGE_AMOUNT_PER_BYTE * storage_usage as u128; // 10^22
        let reserved = storage_cost - locked; // 5 * 10^21

        let view = make_account_view(amount, locked, storage_usage);
        let expected = NearToken::from_yoctonear(amount - reserved);
        assert_eq!(view.available(), expected);
    }

    #[test]
    fn test_storage_cost_calculation() {
        let storage_usage = 1000u64;
        let view = make_account_view(1_000_000_000_000_000_000_000_000, 0, storage_usage);

        let expected_cost = STORAGE_AMOUNT_PER_BYTE * storage_usage as u128;
        assert_eq!(
            view.storage_cost(),
            NearToken::from_yoctonear(expected_cost)
        );
    }

    #[test]
    fn test_storage_cost_zero_when_stake_covers() {
        // Staked > storage cost -> storage_cost returns 0
        let locked = 1_000_000_000_000_000_000_000_000u128; // 1 NEAR
        let view = make_account_view(1_000_000_000_000_000_000_000_000, locked, 1000);

        assert_eq!(view.storage_cost(), NearToken::ZERO);
    }

    #[test]
    fn test_account_balance_from_view() {
        let amount = 1_000_000_000_000_000_000_000_000u128; // 1 NEAR
        let locked = 500_000_000_000_000_000_000_000u128; // 0.5 NEAR
        let storage_usage = 1000u64;

        let view = make_account_view(amount, locked, storage_usage);
        let balance = AccountBalance::from(view.clone());

        assert_eq!(balance.total, view.amount);
        assert_eq!(balance.available, view.available());
        assert_eq!(balance.locked, view.locked);
        assert_eq!(balance.storage_cost, view.storage_cost());
        assert_eq!(balance.storage_usage, storage_usage);
    }

    // ========================================================================
    // ViewFunctionResult tests
    // ========================================================================

    fn make_view_result(result: Vec<u8>) -> ViewFunctionResult {
        ViewFunctionResult {
            result,
            logs: vec![],
            block_height: 12345,
            block_hash: CryptoHash::default(),
        }
    }

    #[test]
    fn test_view_function_result_bytes() {
        let data = vec![1, 2, 3, 4, 5];
        let result = make_view_result(data.clone());
        assert_eq!(result.bytes(), &data[..]);
    }

    #[test]
    fn test_view_function_result_as_string() {
        let result = make_view_result(b"hello world".to_vec());
        assert_eq!(result.as_string().unwrap(), "hello world");
    }

    #[test]
    fn test_view_function_result_json() {
        let result = make_view_result(b"42".to_vec());
        let value: u64 = result.json().unwrap();
        assert_eq!(value, 42);
    }

    #[test]
    fn test_view_function_result_json_object() {
        let result = make_view_result(b"{\"count\":123}".to_vec());
        let value: serde_json::Value = result.json().unwrap();
        assert_eq!(value["count"], 123);
    }

    #[test]
    fn test_view_function_result_borsh() {
        // Borsh-encode a u64 value
        let original: u64 = 42;
        let encoded = borsh::to_vec(&original).unwrap();
        let result = make_view_result(encoded);

        let decoded: u64 = result.borsh().unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn test_view_function_result_borsh_struct() {
        #[derive(borsh::BorshSerialize, borsh::BorshDeserialize, PartialEq, Debug)]
        struct TestStruct {
            value: u64,
            name: String,
        }

        let original = TestStruct {
            value: 123,
            name: "test".to_string(),
        };
        let encoded = borsh::to_vec(&original).unwrap();
        let result = make_view_result(encoded);

        let decoded: TestStruct = result.borsh().unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn test_view_function_result_borsh_error() {
        // Invalid Borsh data for a u64 (too short)
        let result = make_view_result(vec![1, 2, 3]);
        let decoded: Result<u64, _> = result.borsh();
        assert!(decoded.is_err());
    }

    // ========================================================================
    // GasProfileEntry tests
    // ========================================================================

    #[test]
    fn test_gas_profile_entry_string_gas_used() {
        let json = serde_json::json!({
            "cost_category": "WASM_HOST_COST",
            "cost": "BASE",
            "gas_used": "123456789"
        });
        let entry: GasProfileEntry = serde_json::from_value(json).unwrap();
        assert_eq!(entry.gas_used.as_gas(), 123456789);
    }

    #[test]
    fn test_gas_profile_entry_numeric_gas_used() {
        let json = serde_json::json!({
            "cost_category": "ACTION_COST",
            "cost": "FUNCTION_CALL",
            "gas_used": 999000000
        });
        let entry: GasProfileEntry = serde_json::from_value(json).unwrap();
        assert_eq!(entry.gas_used.as_gas(), 999000000);
    }

    #[test]
    fn test_gas_key_function_call_deserialization() {
        let json = serde_json::json!({
            "GasKeyFunctionCall": {
                "balance": "1000000000000000000000000",
                "num_nonces": 5,
                "allowance": "500000000000000000000000",
                "receiver_id": "app.near",
                "method_names": ["call_method"]
            }
        });
        let perm: AccessKeyPermissionView = serde_json::from_value(json).unwrap();
        assert!(matches!(
            perm,
            AccessKeyPermissionView::GasKeyFunctionCall { .. }
        ));
    }

    #[test]
    fn test_gas_key_full_access_deserialization() {
        let json = serde_json::json!({
            "GasKeyFullAccess": {
                "balance": "1000000000000000000000000",
                "num_nonces": 10
            }
        });
        let perm: AccessKeyPermissionView = serde_json::from_value(json).unwrap();
        assert!(matches!(
            perm,
            AccessKeyPermissionView::GasKeyFullAccess { .. }
        ));
    }

    #[test]
    fn test_transfer_to_gas_key_action_view_deserialization() {
        let json = serde_json::json!({
            "TransferToGasKey": {
                "public_key": "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp",
                "deposit": "1000000000000000000000000"
            }
        });
        let action: ActionView = serde_json::from_value(json).unwrap();
        assert!(matches!(action, ActionView::TransferToGasKey { .. }));
    }

    #[test]
    fn test_delegate_action_view_deserialization() {
        let json = serde_json::json!({
            "Delegate": {
                "delegate_action": {
                    "sender_id": "alice.near",
                    "receiver_id": "contract.near",
                    "actions": [
                        {"FunctionCall": {
                            "method_name": "do_something",
                            "args": "e30=",
                            "gas": 30000000000000_u64,
                            "deposit": "0"
                        }}
                    ],
                    "nonce": 42,
                    "max_block_height": 100000,
                    "public_key": "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp"
                },
                "signature": "ed25519:3s1dvMqNDCByoMnDnkhB4GPjTSXCRt4nt3Af5n1RX8W7aJ2FC6MfRf5BNXZ52EBifNJnNVBsGvke6GRYuaEYJXt5"
            }
        });
        let action: ActionView = serde_json::from_value(json).unwrap();
        match action {
            ActionView::Delegate {
                delegate_action,
                signature,
            } => {
                assert_eq!(delegate_action.sender_id.as_str(), "alice.near");
                assert_eq!(delegate_action.receiver_id.as_str(), "contract.near");
                assert_eq!(delegate_action.nonce, 42);
                assert_eq!(delegate_action.max_block_height, 100000);
                assert_eq!(delegate_action.actions.len(), 1);
                assert!(signature.to_string().starts_with("ed25519:"));
            }
            _ => panic!("Expected Delegate action"),
        }
    }

    #[test]
    fn test_withdraw_from_gas_key_action_view_deserialization() {
        let json = serde_json::json!({
            "WithdrawFromGasKey": {
                "public_key": "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp",
                "amount": "500000000000000000000000"
            }
        });
        let action: ActionView = serde_json::from_value(json).unwrap();
        assert!(matches!(action, ActionView::WithdrawFromGasKey { .. }));
    }

    // ========================================================================
    // FinalExecutionStatus tests
    // ========================================================================

    #[test]
    fn test_final_execution_status_default() {
        let status = FinalExecutionStatus::default();
        assert!(matches!(status, FinalExecutionStatus::NotStarted));
    }

    #[test]
    fn test_final_execution_status_not_started() {
        let json = serde_json::json!("NotStarted");
        let status: FinalExecutionStatus = serde_json::from_value(json).unwrap();
        assert!(matches!(status, FinalExecutionStatus::NotStarted));
    }

    #[test]
    fn test_final_execution_status_started() {
        let json = serde_json::json!("Started");
        let status: FinalExecutionStatus = serde_json::from_value(json).unwrap();
        assert!(matches!(status, FinalExecutionStatus::Started));
    }

    #[test]
    fn test_final_execution_status_success_value() {
        let json = serde_json::json!({"SuccessValue": "aGVsbG8="});
        let status: FinalExecutionStatus = serde_json::from_value(json).unwrap();
        assert!(matches!(status, FinalExecutionStatus::SuccessValue(ref s) if s == "aGVsbG8="));
    }

    #[test]
    fn test_final_execution_status_failure() {
        let json = serde_json::json!({
            "Failure": {
                "ActionError": {
                    "index": 0,
                    "kind": {
                        "FunctionCallError": {
                            "ExecutionError": "Smart contract panicked"
                        }
                    }
                }
            }
        });
        let status: FinalExecutionStatus = serde_json::from_value(json).unwrap();
        assert!(matches!(status, FinalExecutionStatus::Failure(_)));
    }

    // ========================================================================
    // FinalExecutionOutcome helper tests
    // ========================================================================

    #[test]
    fn test_send_tx_response_with_outcome() {
        let json = serde_json::json!({
            "final_execution_status": "FINAL",
            "status": {"SuccessValue": ""},
            "transaction": {
                "signer_id": "alice.near",
                "public_key": "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp",
                "nonce": 1,
                "receiver_id": "bob.near",
                "actions": [{"Transfer": {"deposit": "1000000000000000000000000"}}],
                "signature": "ed25519:3s1dvMqNDCByoMnDnkhB4GPjTSXCRt4nt3Af5n1RX8W7aJ2FC6MfRf5BNXZ52EBifNJnNVBsGvke6GRYuaEYJXt5",
                "hash": "9FtHUFBQsZ2MG77K3x3MJ9wjX3UT8zE1TczCrhZEcG8U"
            },
            "transaction_outcome": {
                "id": "9FtHUFBQsZ2MG77K3x3MJ9wjX3UT8zE1TczCrhZEcG8U",
                "outcome": {
                    "executor_id": "alice.near",
                    "gas_burnt": 223182562500_i64,
                    "tokens_burnt": "22318256250000000000",
                    "logs": [],
                    "receipt_ids": ["3GTGoiN3FEoJenSw5ob4YMmFEV2Fbiichj3FDBnM78xK"],
                    "status": {"SuccessReceiptId": "3GTGoiN3FEoJenSw5ob4YMmFEV2Fbiichj3FDBnM78xK"}
                },
                "block_hash": "A6DJpKBhmAMmBuQXtY3dWbo8dGVSQ9yH7BQSJBfn8rBo",
                "proof": []
            },
            "receipts_outcome": []
        });
        let response: RawTransactionResponse = serde_json::from_value(json).unwrap();
        assert_eq!(response.final_execution_status, TxExecutionStatus::Final);
        let outcome = response.outcome.unwrap();
        assert!(outcome.is_success());
        assert!(!outcome.is_failure());
    }

    #[test]
    fn test_send_tx_response_pending_none() {
        let json = serde_json::json!({
            "final_execution_status": "NONE"
        });
        let response: RawTransactionResponse = serde_json::from_value(json).unwrap();
        assert_eq!(response.final_execution_status, TxExecutionStatus::None);
        assert!(response.outcome.is_none());
        // transaction_hash is serde(skip) — populated by rpc methods, not deserialization
        assert!(response.transaction_hash.is_zero());
    }

    #[test]
    fn test_final_execution_outcome_failure() {
        let json = serde_json::json!({
            "final_execution_status": "EXECUTED_OPTIMISTIC",
            "status": {
                "Failure": {
                    "ActionError": {
                        "index": 0,
                        "kind": {
                            "FunctionCallError": {
                                "ExecutionError": "Smart contract panicked"
                            }
                        }
                    }
                }
            },
            "transaction": {
                "signer_id": "alice.near",
                "public_key": "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp",
                "nonce": 1,
                "receiver_id": "bob.near",
                "actions": [],
                "signature": "ed25519:3s1dvMqNDCByoMnDnkhB4GPjTSXCRt4nt3Af5n1RX8W7aJ2FC6MfRf5BNXZ52EBifNJnNVBsGvke6GRYuaEYJXt5",
                "hash": "9FtHUFBQsZ2MG77K3x3MJ9wjX3UT8zE1TczCrhZEcG8U"
            },
            "transaction_outcome": {
                "id": "9FtHUFBQsZ2MG77K3x3MJ9wjX3UT8zE1TczCrhZEcG8U",
                "outcome": {
                    "executor_id": "alice.near",
                    "gas_burnt": 0,
                    "tokens_burnt": "0",
                    "logs": [],
                    "receipt_ids": [],
                    "status": "Unknown"
                },
                "block_hash": "A6DJpKBhmAMmBuQXtY3dWbo8dGVSQ9yH7BQSJBfn8rBo",
                "proof": []
            },
            "receipts_outcome": []
        });
        let response: RawTransactionResponse = serde_json::from_value(json).unwrap();
        let outcome = response.outcome.unwrap();
        assert!(outcome.is_failure());
        assert!(!outcome.is_success());
        assert!(outcome.failure_message().is_some());
        assert!(outcome.failure_error().is_some());
    }

    // ========================================================================
    // FinalExecutionOutcome result/json tests
    // ========================================================================

    fn make_success_outcome(base64_value: &str) -> FinalExecutionOutcome {
        let json = serde_json::json!({
            "final_execution_status": "FINAL",
            "status": {"SuccessValue": base64_value},
            "transaction": {
                "signer_id": "alice.near",
                "public_key": "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp",
                "nonce": 1,
                "receiver_id": "bob.near",
                "actions": [],
                "signature": "ed25519:3s1dvMqNDCByoMnDnkhB4GPjTSXCRt4nt3Af5n1RX8W7aJ2FC6MfRf5BNXZ52EBifNJnNVBsGvke6GRYuaEYJXt5",
                "hash": "9FtHUFBQsZ2MG77K3x3MJ9wjX3UT8zE1TczCrhZEcG8U"
            },
            "transaction_outcome": {
                "id": "9FtHUFBQsZ2MG77K3x3MJ9wjX3UT8zE1TczCrhZEcG8U",
                "outcome": {
                    "executor_id": "alice.near",
                    "gas_burnt": 223182562500_i64,
                    "tokens_burnt": "22318256250000000000",
                    "logs": [],
                    "receipt_ids": [],
                    "status": {"SuccessReceiptId": "3GTGoiN3FEoJenSw5ob4YMmFEV2Fbiichj3FDBnM78xK"}
                },
                "block_hash": "A6DJpKBhmAMmBuQXtY3dWbo8dGVSQ9yH7BQSJBfn8rBo",
                "proof": []
            },
            "receipts_outcome": []
        });
        let response: RawTransactionResponse = serde_json::from_value(json).unwrap();
        response.outcome.unwrap()
    }

    #[test]
    fn test_outcome_result() {
        // "hello" in base64
        let outcome = make_success_outcome("aGVsbG8=");
        assert_eq!(outcome.result().unwrap(), b"hello");
    }

    #[test]
    fn test_outcome_result_empty() {
        let outcome = make_success_outcome("");
        assert_eq!(outcome.result().unwrap(), b"");
    }

    #[test]
    fn test_outcome_json() {
        // JSON `42` in base64
        let outcome = make_success_outcome("NDI=");
        let val: u64 = outcome.json().unwrap();
        assert_eq!(val, 42);
    }

    #[test]
    fn test_outcome_json_bad_data() {
        // "hello" is not valid JSON
        let outcome = make_success_outcome("aGVsbG8=");
        let result: Result<u64, _> = outcome.json();
        assert!(result.is_err());
    }

    #[test]
    fn test_outcome_result_invalid_base64_returns_err() {
        // If the RPC somehow returns invalid base64 (protocol bug),
        // result() returns an error so callers can distinguish it from empty values.
        let outcome = make_success_outcome("not-valid-base64!!!");
        let err = outcome.result().unwrap_err();
        assert!(
            err.to_string().contains("base64"),
            "Error should mention base64 decode failure, got: {err}"
        );
    }

    #[test]
    fn test_outcome_failure_result_returns_err() {
        let json = serde_json::json!({
            "final_execution_status": "FINAL",
            "status": {"Failure": {"ActionError": {"index": 0, "kind": {"FunctionCallError": {"ExecutionError": "test error"}}}}},
            "transaction": {
                "signer_id": "alice.near",
                "public_key": "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp",
                "nonce": 1,
                "receiver_id": "bob.near",
                "actions": [],
                "signature": "ed25519:3s1dvMqNDCByoMnDnkhB4GPjTSXCRt4nt3Af5n1RX8W7aJ2FC6MfRf5BNXZ52EBifNJnNVBsGvke6GRYuaEYJXt5",
                "hash": "9FtHUFBQsZ2MG77K3x3MJ9wjX3UT8zE1TczCrhZEcG8U"
            },
            "transaction_outcome": {
                "id": "9FtHUFBQsZ2MG77K3x3MJ9wjX3UT8zE1TczCrhZEcG8U",
                "outcome": {
                    "executor_id": "alice.near",
                    "gas_burnt": 223182562500_i64,
                    "tokens_burnt": "22318256250000000000",
                    "logs": [],
                    "receipt_ids": [],
                    "status": {"SuccessReceiptId": "3GTGoiN3FEoJenSw5ob4YMmFEV2Fbiichj3FDBnM78xK"}
                },
                "block_hash": "A6DJpKBhmAMmBuQXtY3dWbo8dGVSQ9yH7BQSJBfn8rBo",
                "proof": []
            },
            "receipts_outcome": []
        });
        let outcome: FinalExecutionOutcome = serde_json::from_value(json).unwrap();

        assert!(outcome.is_failure());
        assert!(!outcome.is_success());
        assert!(outcome.result().is_err());
        assert!(outcome.json::<u64>().is_err());
        // Metadata is still accessible
        assert!(!outcome.transaction_hash().is_zero());
        assert!(outcome.total_gas_used().as_gas() > 0);
    }

    // ========================================================================
    // ExecutionStatus tests (per-receipt)
    // ========================================================================

    #[test]
    fn test_execution_status_unknown() {
        let json = serde_json::json!("Unknown");
        let status: ExecutionStatus = serde_json::from_value(json).unwrap();
        assert!(matches!(status, ExecutionStatus::Unknown));
    }

    #[test]
    fn test_execution_status_success_value() {
        let json = serde_json::json!({"SuccessValue": "aGVsbG8="});
        let status: ExecutionStatus = serde_json::from_value(json).unwrap();
        assert!(matches!(status, ExecutionStatus::SuccessValue(_)));
    }

    #[test]
    fn test_execution_status_success_receipt_id() {
        let json =
            serde_json::json!({"SuccessReceiptId": "9FtHUFBQsZ2MG77K3x3MJ9wjX3UT8zE1TczCrhZEcG8U"});
        let status: ExecutionStatus = serde_json::from_value(json).unwrap();
        assert!(matches!(status, ExecutionStatus::SuccessReceiptId(_)));
    }

    #[test]
    fn test_execution_status_failure_action_error() {
        let json = serde_json::json!({
            "Failure": {
                "ActionError": {
                    "index": 0,
                    "kind": {
                        "FunctionCallError": {
                            "ExecutionError": "Smart contract panicked"
                        }
                    }
                }
            }
        });
        let status: ExecutionStatus = serde_json::from_value(json).unwrap();
        match status {
            ExecutionStatus::Failure(ae) => {
                assert_eq!(ae.index, Some(0));
            }
            other => panic!("expected Failure, got: {other:?}"),
        }
    }

    #[test]
    fn test_execution_status_failure_invalid_tx_error_rejected() {
        let json = serde_json::json!({
            "Failure": {
                "InvalidTxError": "InvalidSignature"
            }
        });
        let err = serde_json::from_value::<ExecutionStatus>(json)
            .expect_err("InvalidTxError should be rejected in receipt execution status");
        let msg = err.to_string();
        assert!(
            msg.contains("unexpected InvalidTxError"),
            "Expected descriptive error containing \"unexpected InvalidTxError\", got: {msg}"
        );
    }

    // ========================================================================
    // GlobalContractIdentifierView tests
    // ========================================================================

    #[test]
    fn test_global_contract_id_view_new_format_hash() {
        let json = serde_json::json!({"hash": "9SP8Y3sVADWNN5QoEB5CsvPUE5HT4o8YfBaCnhLss87K"});
        let id: GlobalContractIdentifierView = serde_json::from_value(json).unwrap();
        assert!(matches!(id, GlobalContractIdentifierView::CodeHash(_)));
    }

    #[test]
    fn test_global_contract_id_view_new_format_account() {
        let json = serde_json::json!({"account_id": "alice.near"});
        let id: GlobalContractIdentifierView = serde_json::from_value(json).unwrap();
        assert!(matches!(id, GlobalContractIdentifierView::AccountId(_)));
    }

    #[test]
    fn test_global_contract_id_view_deprecated_hash() {
        let json = serde_json::json!("9SP8Y3sVADWNN5QoEB5CsvPUE5HT4o8YfBaCnhLss87K");
        let id: GlobalContractIdentifierView = serde_json::from_value(json).unwrap();
        assert!(matches!(id, GlobalContractIdentifierView::CodeHash(_)));
    }

    #[test]
    fn test_global_contract_id_view_deprecated_account() {
        let json = serde_json::json!("alice.near");
        let id: GlobalContractIdentifierView = serde_json::from_value(json).unwrap();
        assert!(matches!(id, GlobalContractIdentifierView::AccountId(_)));
    }

    // ========================================================================
    // DeterministicStateInit ActionView tests
    // ========================================================================

    #[test]
    fn test_action_view_deterministic_state_init() {
        let json = serde_json::json!({
            "DeterministicStateInit": {
                "code": {"hash": "9SP8Y3sVADWNN5QoEB5CsvPUE5HT4o8YfBaCnhLss87K"},
                "data": {"a2V5": "dmFsdWU="},
                "deposit": "1000000000000000000000000"
            }
        });
        let action: ActionView = serde_json::from_value(json).unwrap();
        match action {
            ActionView::DeterministicStateInit {
                code,
                data,
                deposit,
            } => {
                assert!(matches!(code, GlobalContractIdentifierView::CodeHash(_)));
                assert_eq!(data.len(), 1);
                assert_eq!(data.get("a2V5").unwrap(), "dmFsdWU=");
                assert_eq!(deposit, NearToken::from_near(1));
            }
            _ => panic!("Expected DeterministicStateInit"),
        }
    }

    #[test]
    fn test_action_view_deterministic_state_init_empty_data() {
        let json = serde_json::json!({
            "DeterministicStateInit": {
                "code": {"account_id": "publisher.near"},
                "deposit": "0"
            }
        });
        let action: ActionView = serde_json::from_value(json).unwrap();
        match action {
            ActionView::DeterministicStateInit { code, data, .. } => {
                assert!(matches!(code, GlobalContractIdentifierView::AccountId(_)));
                assert!(data.is_empty());
            }
            _ => panic!("Expected DeterministicStateInit"),
        }
    }

    // ========================================================================
    // GlobalContractDistribution receipt tests
    // ========================================================================

    #[test]
    fn test_receipt_global_contract_distribution() {
        let json = serde_json::json!({
            "GlobalContractDistribution": {
                "id": {"hash": "9SP8Y3sVADWNN5QoEB5CsvPUE5HT4o8YfBaCnhLss87K"},
                "target_shard": 3,
                "already_delivered_shards": [0, 1, 2],
                "code": "AGFzbQ==",
                "nonce": 42
            }
        });
        let content: ReceiptContent = serde_json::from_value(json).unwrap();
        match content {
            ReceiptContent::GlobalContractDistribution {
                id,
                target_shard,
                already_delivered_shards,
                code,
                nonce,
            } => {
                assert!(matches!(id, GlobalContractIdentifierView::CodeHash(_)));
                assert_eq!(target_shard, 3);
                assert_eq!(already_delivered_shards, vec![0, 1, 2]);
                assert_eq!(code, "AGFzbQ==");
                assert_eq!(nonce, Some(42));
            }
            _ => panic!("Expected GlobalContractDistribution"),
        }
    }

    #[test]
    fn test_receipt_global_contract_distribution_without_nonce() {
        let json = serde_json::json!({
            "GlobalContractDistribution": {
                "id": {"account_id": "publisher.near"},
                "target_shard": 0,
                "already_delivered_shards": [],
                "code": "AGFzbQ=="
            }
        });
        let content: ReceiptContent = serde_json::from_value(json).unwrap();
        match content {
            ReceiptContent::GlobalContractDistribution { nonce, .. } => {
                assert_eq!(nonce, None);
            }
            _ => panic!("Expected GlobalContractDistribution"),
        }
    }

    #[test]
    fn test_gas_profile_entry_deserialization() {
        let json = serde_json::json!({
            "cost_category": "WASM_HOST_COST",
            "cost": "BASE",
            "gas_used": "2646228750"
        });
        let entry: GasProfileEntry = serde_json::from_value(json).unwrap();
        assert_eq!(entry.cost_category, "WASM_HOST_COST");
        assert_eq!(entry.cost, "BASE");
        assert_eq!(entry.gas_used, Gas::from_gas(2646228750));
    }

    #[test]
    fn test_transaction_view_with_signature() {
        let json = serde_json::json!({
            "signer_id": "alice.near",
            "public_key": "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp",
            "nonce": 1,
            "receiver_id": "bob.near",
            "hash": "9FtHUFBQsZ2MG77K3x3MJ9wjX3UT8zE1TczCrhZEcG8U",
            "actions": [{"Transfer": {"deposit": "1000000000000000000000000"}}],
            "signature": "ed25519:3s1dvMqNDCByoMnDnkhB4GPjTSXCRt4nt3Af5n1RX8W7aJ2FC6MfRf5BNXZ52EBifNJnNVBsGvke6GRYuaEYJXt5"
        });
        let tx: TransactionView = serde_json::from_value(json).unwrap();
        assert_eq!(tx.signer_id.as_str(), "alice.near");
        assert!(tx.signature.to_string().starts_with("ed25519:"));
    }
}