scope-bca-core 0.8.6

Scope Blockchain Analysis - Core library for blockchain data analysis
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
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
//! # Solana Client
//!
//! This module provides a Solana blockchain client for querying balances,
//! transactions, and account information on the Solana network.
//!
//! ## Features
//!
//! - Balance queries via Solana JSON-RPC (with USD valuation via DexScreener)
//! - Transaction details lookup via `getTransaction` RPC (jsonParsed encoding)
//! - Enriched transaction history with slot, timestamp, and status from `getSignaturesForAddress`
//! - SPL token balance fetching via `getTokenAccountsByOwner`
//! - Base58 address and signature validation
//! - Support for both legacy and versioned transactions
//!
//! ## Usage
//!
//! ```rust,no_run
//! use scope::chains::SolanaClient;
//! use scope::config::ChainsConfig;
//!
//! #[tokio::main]
//! async fn main() -> scope::Result<()> {
//!     let config = ChainsConfig::default();
//!     let client = SolanaClient::new(&config)?;
//!     
//!     let mut balance = client.get_balance("DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy").await?;
//!     client.enrich_balance_usd(&mut balance).await;
//!     println!("Balance: {} SOL", balance.formatted);
//!     Ok(())
//! }
//! ```

use crate::chains::{Balance, ChainClient, Token, Transaction};
use crate::config::ChainsConfig;
use crate::error::{Result, ScopeError};
use crate::http::{HttpClient, Request};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// Default Solana mainnet RPC endpoint.
const DEFAULT_SOLANA_RPC: &str = "https://api.mainnet-beta.solana.com";

/// Solscan API base URL for transaction history.
#[allow(dead_code)] // Reserved for future Solscan integration
const SOLSCAN_API_URL: &str = "https://api.solscan.io";

/// Solana native token decimals.
const SOL_DECIMALS: u8 = 9;

/// Solana blockchain client.
///
/// Supports balance queries via JSON-RPC and optional transaction
/// history via Solscan API.
#[derive(Clone)]
pub struct SolanaClient {
    /// HTTP client for API requests.
    http: Arc<dyn HttpClient>,

    /// Solana JSON-RPC endpoint URL.
    rpc_url: String,

    /// Solscan API key for enhanced transaction data.
    #[allow(dead_code)] // Reserved for future Solscan integration
    solscan_api_key: Option<String>,
}

/// JSON-RPC request structure.
#[derive(Debug, Serialize)]
struct RpcRequest<'a, T: Serialize> {
    jsonrpc: &'a str,
    id: u64,
    method: &'a str,
    params: T,
}

/// JSON-RPC response structure.
#[derive(Debug, Deserialize)]
struct RpcResponse<T> {
    result: Option<T>,
    error: Option<RpcError>,
}

/// JSON-RPC error structure.
#[derive(Debug, Deserialize)]
struct RpcError {
    code: i64,
    message: String,
}

/// Balance response from getBalance RPC call.
#[derive(Debug, Deserialize)]
struct BalanceResponse {
    value: u64,
}

/// Response structure for getTokenAccountsByOwner.
#[derive(Debug, Deserialize)]
struct TokenAccountsResponse {
    value: Vec<TokenAccountInfo>,
}

/// Individual token account info.
#[derive(Debug, Deserialize)]
struct TokenAccountInfo {
    pubkey: String,
    account: TokenAccountData,
}

/// Token account data.
#[derive(Debug, Deserialize)]
struct TokenAccountData {
    data: TokenAccountParsedData,
}

/// Parsed token account data.
#[derive(Debug, Deserialize)]
struct TokenAccountParsedData {
    parsed: TokenAccountParsedInfo,
}

/// Parsed info containing token details.
#[derive(Debug, Deserialize)]
struct TokenAccountParsedInfo {
    info: TokenInfo,
}

/// Token balance and mint information.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TokenInfo {
    mint: String,
    token_amount: TokenAmount,
}

/// Token amount with UI representation.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)] // ui_amount_string reserved for future use
struct TokenAmount {
    amount: String,
    decimals: u8,
    ui_amount: Option<f64>,
    ui_amount_string: String,
}

/// SPL Token balance with metadata.
#[derive(Debug, Clone, Serialize)]
pub struct TokenBalance {
    /// Token mint address.
    pub mint: String,
    /// Token account address.
    pub token_account: String,
    /// Raw balance in smallest unit.
    pub raw_amount: String,
    /// Human-readable balance.
    pub ui_amount: f64,
    /// Token decimals.
    pub decimals: u8,
    /// Token symbol (if known).
    pub symbol: Option<String>,
    /// Token name (if known).
    pub name: Option<String>,
}

/// Transaction signature info from getSignaturesForAddress.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)] // Fields used for deserialization
struct SignatureInfo {
    signature: String,
    slot: u64,
    block_time: Option<i64>,
    err: Option<serde_json::Value>,
}

/// Solana transaction result from getTransaction RPC.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SolanaTransactionResult {
    #[serde(default)]
    slot: Option<u64>,
    #[serde(default)]
    block_time: Option<i64>,
    #[serde(default)]
    transaction: Option<SolanaTransactionData>,
    #[serde(default)]
    meta: Option<SolanaTransactionMeta>,
}

/// Transaction data from Solana RPC.
#[derive(Debug, Deserialize)]
struct SolanaTransactionData {
    #[serde(default)]
    message: Option<SolanaTransactionMessage>,
}

/// Transaction message from Solana RPC.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SolanaTransactionMessage {
    #[serde(default)]
    account_keys: Option<Vec<AccountKeyEntry>>,
}

/// Account key can be a string or an object with pubkey + signer fields.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum AccountKeyEntry {
    String(String),
    Object {
        pubkey: String,
        #[serde(default)]
        #[allow(dead_code)]
        signer: bool,
    },
}

/// Transaction metadata from Solana RPC.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SolanaTransactionMeta {
    #[serde(default)]
    fee: Option<u64>,
    #[serde(default)]
    pre_balances: Option<Vec<u64>>,
    #[serde(default)]
    post_balances: Option<Vec<u64>>,
    #[serde(default)]
    err: Option<serde_json::Value>,
}

/// Solscan account info response.
#[derive(Debug, Deserialize)]
#[allow(dead_code)] // Reserved for future Solscan integration
struct SolscanAccountInfo {
    lamports: u64,
    #[serde(rename = "type")]
    account_type: Option<String>,
}

impl SolanaClient {
    /// Creates a new Solana client with the given configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - Chain configuration containing RPC endpoint and API keys
    ///
    /// # Returns
    ///
    /// Returns a configured [`SolanaClient`] instance.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use scope::chains::SolanaClient;
    /// use scope::config::ChainsConfig;
    ///
    /// let config = ChainsConfig::default();
    /// let client = SolanaClient::new(&config).unwrap();
    /// ```
    #[deprecated(
        since = "0.8.0",
        note = "pass the transport: use `SolanaClient::new_with_http`"
    )]
    pub fn new(config: &ChainsConfig) -> Result<Self> {
        Self::new_with_http(config, crate::http::shared::fallback())
    }

    /// Creates a new Solana client with a pre-built HTTP transport.
    pub fn new_with_http(config: &ChainsConfig, http: Arc<dyn HttpClient>) -> Result<Self> {
        let rpc_url = config
            .solana_rpc
            .as_deref()
            .unwrap_or(DEFAULT_SOLANA_RPC)
            .to_string();

        Ok(Self {
            http,
            rpc_url,
            solscan_api_key: config.api_keys.get("solscan").cloned(),
        })
    }

    /// Creates a client with a custom RPC URL.
    ///
    /// # Arguments
    ///
    /// * `rpc_url` - The Solana JSON-RPC endpoint URL
    pub fn with_rpc_url(rpc_url: &str) -> Self {
        Self {
            http: crate::http::shared::fallback(),
            rpc_url: rpc_url.to_string(),
            solscan_api_key: None,
        }
    }

    /// Returns the chain name.
    pub fn chain_name(&self) -> &str {
        "solana"
    }

    /// Returns the native token symbol.
    pub fn native_token_symbol(&self) -> &str {
        "SOL"
    }

    /// Fetches the SOL balance for an address.
    ///
    /// # Arguments
    ///
    /// * `address` - The Solana address (base58 encoded)
    ///
    /// # Returns
    ///
    /// Returns a [`Balance`] struct with the balance in multiple formats.
    ///
    /// # Errors
    ///
    /// Returns [`ScopeError::InvalidAddress`] if the address format is invalid.
    /// Returns [`ScopeError::Request`] if the API request fails.
    pub async fn get_balance(&self, address: &str) -> Result<Balance> {
        // Validate address
        validate_solana_address(address)?;

        let request = RpcRequest {
            jsonrpc: "2.0",
            id: 1,
            method: "getBalance",
            params: vec![address],
        };

        tracing::debug!(url = %self.rpc_url, address = %address, "Fetching Solana balance");

        let body = serde_json::to_string(&request)?;
        let response: RpcResponse<BalanceResponse> = self
            .http
            .send(Request::post_json(&self.rpc_url, body))
            .await?
            .json()?;

        if let Some(error) = response.error {
            return Err(ScopeError::Chain(format!(
                "Solana RPC error ({}): {}",
                error.code, error.message
            )));
        }

        let balance = response
            .result
            .ok_or_else(|| ScopeError::Chain("Empty RPC response".to_string()))?;

        let lamports = balance.value;
        let sol = lamports as f64 / 10_f64.powi(SOL_DECIMALS as i32);

        Ok(Balance {
            raw: lamports.to_string(),
            formatted: format!("{:.9} SOL", sol),
            decimals: SOL_DECIMALS,
            symbol: "SOL".to_string(),
            usd_value: None, // Populated by caller via enrich_balance_usd
        })
    }

    /// Fetches SPL token (mint) info from RPC.
    ///
    /// Parses decimals from the mint account data. Symbol and name use
    /// placeholders (Solscan Pro API would provide full metadata).
    pub async fn get_token_info(&self, mint_address: &str) -> Result<Token> {
        validate_solana_address(mint_address)?;

        let request = RpcRequest {
            jsonrpc: "2.0",
            id: 1,
            method: "getAccountInfo",
            params: serde_json::json!([mint_address, { "encoding": "base64" }]),
        };

        tracing::debug!(
            url = %self.rpc_url,
            mint = %mint_address,
            "Fetching SPL mint info"
        );

        #[derive(Deserialize)]
        struct AccountInfoResult {
            value: Option<AccountInfoValue>,
        }
        #[derive(Deserialize)]
        struct AccountInfoValue {
            data: Option<Vec<String>>,
        }

        let body = serde_json::to_string(&request)?;
        let response: RpcResponse<AccountInfoResult> = self
            .http
            .send(Request::post_json(&self.rpc_url, body))
            .await?
            .json()?;

        if let Some(error) = response.error {
            return Err(ScopeError::Chain(format!(
                "Solana RPC error ({}): {}",
                error.code, error.message
            )));
        }

        let account = response.result.and_then(|r| r.value).ok_or_else(|| {
            ScopeError::NotFound(format!("Mint account not found: {}", mint_address))
        })?;

        let data_b64 = account
            .data
            .and_then(|d| d.into_iter().next())
            .ok_or_else(|| {
                ScopeError::Chain(format!("No account data for mint: {}", mint_address))
            })?;

        let data = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &data_b64)
            .map_err(|e| ScopeError::Chain(format!("Failed to decode mint data: {}", e)))?;

        // SPL Token mint layout: 32 (mint_authority) + 8 (supply) + 1 (decimals) + ...
        const DECIMALS_OFFSET: usize = 40;
        let decimals = if data.len() > DECIMALS_OFFSET {
            data[DECIMALS_OFFSET]
        } else {
            return Err(ScopeError::Chain(format!(
                "Invalid mint account data (too short): {}",
                mint_address
            )));
        };

        let short_mint = crate::display::text::abbreviate(mint_address);

        Ok(Token {
            contract_address: mint_address.to_string(),
            symbol: short_mint,
            name: "SPL Token".to_string(),
            decimals,
        })
    }

    /// Enriches a balance with a USD value using DexScreener price lookup.
    pub async fn enrich_balance_usd(&self, balance: &mut Balance) {
        let dex = crate::chains::DexClient::new_with_http(self.http.clone());
        if let Some(price) = dex.get_native_token_price("solana").await {
            let lamports: f64 = balance.raw.parse().unwrap_or(0.0);
            let sol = lamports / 10_f64.powi(SOL_DECIMALS as i32);
            balance.usd_value = Some(sol * price);
        }
    }

    /// Fetches all SPL token balances for an address.
    ///
    /// # Arguments
    ///
    /// * `address` - The Solana wallet address to query
    ///
    /// # Returns
    ///
    /// Returns a vector of [`TokenBalance`] containing all SPL tokens held by the address.
    ///
    /// # Errors
    ///
    /// Returns [`ScopeError::InvalidAddress`] if the address format is invalid.
    /// Returns [`ScopeError::Request`] if the API request fails.
    pub async fn get_token_balances(&self, address: &str) -> Result<Vec<TokenBalance>> {
        validate_solana_address(address)?;

        // Use getTokenAccountsByOwner to get all token accounts
        // The TOKEN_PROGRAM_ID is the standard SPL Token program
        const TOKEN_PROGRAM_ID: &str = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";

        let request = serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "getTokenAccountsByOwner",
            "params": [
                address,
                { "programId": TOKEN_PROGRAM_ID },
                { "encoding": "jsonParsed" }
            ]
        });

        tracing::debug!(url = %self.rpc_url, address = %address, "Fetching SPL token balances");

        let body = serde_json::to_string(&request)?;
        let response: RpcResponse<TokenAccountsResponse> = self
            .http
            .send(Request::post_json(&self.rpc_url, body))
            .await?
            .json()?;

        if let Some(error) = response.error {
            return Err(ScopeError::Chain(format!(
                "Solana RPC error ({}): {}",
                error.code, error.message
            )));
        }

        let accounts = response
            .result
            .ok_or_else(|| ScopeError::Chain("Empty RPC response".to_string()))?;

        let token_balances: Vec<TokenBalance> = accounts
            .value
            .into_iter()
            .filter_map(|account| {
                let info = &account.account.data.parsed.info;
                let ui_amount = info.token_amount.ui_amount.unwrap_or(0.0);

                // Skip zero balances
                if ui_amount == 0.0 {
                    return None;
                }

                Some(TokenBalance {
                    mint: info.mint.clone(),
                    token_account: account.pubkey,
                    raw_amount: info.token_amount.amount.clone(),
                    ui_amount,
                    decimals: info.token_amount.decimals,
                    symbol: None, // Would need token metadata to get this
                    name: None,
                })
            })
            .collect();

        Ok(token_balances)
    }

    /// Fetches recent transaction signatures for an address.
    ///
    /// # Arguments
    ///
    /// * `address` - The Solana address to query
    /// * `limit` - Maximum number of signatures to return
    ///
    /// # Returns
    ///
    /// Returns a vector of transaction signatures.
    pub async fn get_signatures(&self, address: &str, limit: u32) -> Result<Vec<String>> {
        let infos = self.get_signature_infos(address, limit).await?;
        Ok(infos.into_iter().map(|s| s.signature).collect())
    }

    /// Fetches recent transaction signature info (with metadata) for an address.
    async fn get_signature_infos(&self, address: &str, limit: u32) -> Result<Vec<SignatureInfo>> {
        validate_solana_address(address)?;

        #[derive(Serialize)]
        struct GetSignaturesParams<'a> {
            limit: u32,
            #[serde(skip_serializing_if = "Option::is_none")]
            before: Option<&'a str>,
        }

        let request = RpcRequest {
            jsonrpc: "2.0",
            id: 1,
            method: "getSignaturesForAddress",
            params: (
                address,
                GetSignaturesParams {
                    limit,
                    before: None,
                },
            ),
        };

        tracing::debug!(
            url = %self.rpc_url,
            address = %address,
            limit = %limit,
            "Fetching Solana transaction signatures"
        );

        let body = serde_json::to_string(&request)?;
        let response: RpcResponse<Vec<SignatureInfo>> = self
            .http
            .send(Request::post_json(&self.rpc_url, body))
            .await?
            .json()?;

        if let Some(error) = response.error {
            return Err(ScopeError::Chain(format!(
                "Solana RPC error ({}): {}",
                error.code, error.message
            )));
        }

        response
            .result
            .ok_or_else(|| ScopeError::Chain("Empty RPC response".to_string()))
    }

    /// Fetches transaction details by signature.
    ///
    /// # Arguments
    ///
    /// * `signature` - The transaction signature (base58 encoded)
    ///
    /// # Returns
    ///
    /// Returns [`Transaction`] details.
    pub async fn get_transaction(&self, signature: &str) -> Result<Transaction> {
        // Validate signature format
        validate_solana_signature(signature)?;

        let request = RpcRequest {
            jsonrpc: "2.0",
            id: 1,
            method: "getTransaction",
            params: serde_json::json!([
                signature,
                {
                    "encoding": "jsonParsed",
                    "maxSupportedTransactionVersion": 0
                }
            ]),
        };

        tracing::debug!(
            url = %self.rpc_url,
            signature = %signature,
            "Fetching Solana transaction"
        );

        let body = serde_json::to_string(&request)?;
        let response: RpcResponse<SolanaTransactionResult> = self
            .http
            .send(Request::post_json(&self.rpc_url, body))
            .await?
            .json()?;

        if let Some(error) = response.error {
            return Err(ScopeError::Chain(format!(
                "Solana RPC error ({}): {}",
                error.code, error.message
            )));
        }

        let tx_result = response
            .result
            .ok_or_else(|| ScopeError::NotFound(format!("Transaction not found: {}", signature)))?;

        // Extract the first signer (fee payer) as "from"
        let from = tx_result
            .transaction
            .as_ref()
            .and_then(|tx| tx.message.as_ref())
            .and_then(|msg| msg.account_keys.as_ref())
            .and_then(|keys| keys.first())
            .map(|key| match key {
                AccountKeyEntry::String(s) => s.clone(),
                AccountKeyEntry::Object { pubkey, .. } => pubkey.clone(),
            })
            .unwrap_or_default();

        // Try to find the SOL transfer amount from the transaction
        let value = tx_result
            .meta
            .as_ref()
            .and_then(|meta| {
                let pre = meta.pre_balances.as_ref()?;
                let post = meta.post_balances.as_ref()?;
                if pre.len() >= 2 && post.len() >= 2 {
                    // Amount sent = pre[0] - post[0] - fee (fee payer's balance change minus fee)
                    let fee = meta.fee.unwrap_or(0);
                    let sent = pre[0].saturating_sub(post[0]).saturating_sub(fee);
                    if sent > 0 {
                        let sol = sent as f64 / 10_f64.powi(SOL_DECIMALS as i32);
                        return Some(format!("{:.9}", sol));
                    }
                }
                None
            })
            .unwrap_or_else(|| "0".to_string());

        // Extract "to" address (second account key, typically the recipient)
        let to = tx_result
            .transaction
            .as_ref()
            .and_then(|tx| tx.message.as_ref())
            .and_then(|msg| msg.account_keys.as_ref())
            .and_then(|keys| {
                if keys.len() >= 2 {
                    Some(match &keys[1] {
                        AccountKeyEntry::String(s) => s.clone(),
                        AccountKeyEntry::Object { pubkey, .. } => pubkey.clone(),
                    })
                } else {
                    None
                }
            });

        let fee = tx_result
            .meta
            .as_ref()
            .and_then(|meta| meta.fee)
            .unwrap_or(0);

        let status = tx_result.meta.as_ref().map(|meta| meta.err.is_none());

        Ok(Transaction {
            hash: signature.to_string(),
            block_number: tx_result.slot,
            timestamp: tx_result.block_time.map(|t| t as u64),
            from,
            to,
            value,
            gas_limit: 0, // Solana uses compute units, not gas
            gas_used: None,
            gas_price: fee.to_string(), // Use fee as gas_price equivalent
            nonce: 0,
            input: String::new(),
            status,
        })
    }

    /// Fetches recent transactions for an address.
    ///
    /// # Arguments
    ///
    /// * `address` - The address to query
    /// * `limit` - Maximum number of transactions
    ///
    /// # Returns
    ///
    /// Returns a vector of [`Transaction`] objects.
    pub async fn get_transactions(&self, address: &str, limit: u32) -> Result<Vec<Transaction>> {
        validate_solana_address(address)?;

        // Get signature infos (includes slot, blockTime, err)
        let sig_infos = self.get_signature_infos(address, limit).await?;

        let transactions: Vec<Transaction> = sig_infos
            .into_iter()
            .map(|info| Transaction {
                hash: info.signature,
                block_number: Some(info.slot),
                timestamp: info.block_time.map(|t| t as u64),
                from: address.to_string(),
                to: None,
                value: "0".to_string(),
                gas_limit: 0,
                gas_used: None,
                gas_price: "0".to_string(),
                nonce: 0,
                input: String::new(),
                status: Some(info.err.is_none()),
            })
            .collect();

        Ok(transactions)
    }

    /// Fetches the current slot number (equivalent to block number).
    pub async fn get_slot(&self) -> Result<u64> {
        let request = RpcRequest {
            jsonrpc: "2.0",
            id: 1,
            method: "getSlot",
            params: (),
        };

        let body = serde_json::to_string(&request)?;
        let response: RpcResponse<u64> = self
            .http
            .send(Request::post_json(&self.rpc_url, body))
            .await?
            .json()?;

        if let Some(error) = response.error {
            return Err(ScopeError::Chain(format!(
                "Solana RPC error ({}): {}",
                error.code, error.message
            )));
        }

        response
            .result
            .ok_or_else(|| ScopeError::Chain("Empty RPC response".to_string()))
    }
}

impl Default for SolanaClient {
    fn default() -> Self {
        Self {
            http: crate::http::shared::fallback(),
            rpc_url: DEFAULT_SOLANA_RPC.to_string(),
            solscan_api_key: None,
        }
    }
}

/// Validates a Solana address format (base58 encoded, 32-44 characters).
///
/// # Arguments
///
/// * `address` - The address to validate
///
/// # Returns
///
/// Returns `Ok(())` if valid, or an error describing the validation failure.
pub fn validate_solana_address(address: &str) -> Result<()> {
    // Solana addresses are base58 encoded ed25519 public keys
    // They are typically 32-44 characters long

    if address.is_empty() {
        return Err(ScopeError::InvalidAddress("Address cannot be empty".into()));
    }

    // Check length (base58 encoded 32-byte keys are 32-44 chars)
    if address.len() < 32 || address.len() > 44 {
        return Err(ScopeError::InvalidAddress(format!(
            "Solana address must be 32-44 characters, got {}: {}",
            address.len(),
            address
        )));
    }

    // Validate base58 encoding
    match bs58::decode(address).into_vec() {
        Ok(bytes) => {
            // Should decode to 32 bytes (ed25519 public key)
            if bytes.len() != 32 {
                return Err(ScopeError::InvalidAddress(format!(
                    "Solana address must decode to 32 bytes, got {}: {}",
                    bytes.len(),
                    address
                )));
            }
        }
        Err(e) => {
            return Err(ScopeError::InvalidAddress(format!(
                "Invalid base58 encoding: {}: {}",
                e, address
            )));
        }
    }

    Ok(())
}

/// Validates a Solana transaction signature format (base58 encoded).
///
/// # Arguments
///
/// * `signature` - The signature to validate
///
/// # Returns
///
/// Returns `Ok(())` if valid, or an error describing the validation failure.
pub fn validate_solana_signature(signature: &str) -> Result<()> {
    // Solana signatures are base58 encoded 64-byte signatures
    // They are typically 87-88 characters long

    if signature.is_empty() {
        return Err(ScopeError::InvalidHash("Signature cannot be empty".into()));
    }

    // Check length (base58 encoded 64-byte signatures are ~87-88 chars)
    if signature.len() < 80 || signature.len() > 90 {
        return Err(ScopeError::InvalidHash(format!(
            "Solana signature must be 80-90 characters, got {}: {}",
            signature.len(),
            signature
        )));
    }

    // Validate base58 encoding
    match bs58::decode(signature).into_vec() {
        Ok(bytes) => {
            // Should decode to 64 bytes (ed25519 signature)
            if bytes.len() != 64 {
                return Err(ScopeError::InvalidHash(format!(
                    "Solana signature must decode to 64 bytes, got {}: {}",
                    bytes.len(),
                    signature
                )));
            }
        }
        Err(e) => {
            return Err(ScopeError::InvalidHash(format!(
                "Invalid base58 encoding: {}: {}",
                e, signature
            )));
        }
    }

    Ok(())
}

// ============================================================================
// ChainClient Trait Implementation
// ============================================================================

#[async_trait]
impl ChainClient for SolanaClient {
    fn chain_name(&self) -> &str {
        "solana"
    }

    fn native_token_symbol(&self) -> &str {
        "SOL"
    }

    async fn get_balance(&self, address: &str) -> Result<Balance> {
        self.get_balance(address).await
    }

    async fn enrich_balance_usd(&self, balance: &mut Balance) {
        self.enrich_balance_usd(balance).await
    }

    async fn get_transaction(&self, hash: &str) -> Result<Transaction> {
        self.get_transaction(hash).await
    }

    async fn get_transactions(&self, address: &str, limit: u32) -> Result<Vec<Transaction>> {
        self.get_transactions(address, limit).await
    }

    async fn get_block_number(&self) -> Result<u64> {
        self.get_slot().await
    }

    async fn get_token_info(&self, address: &str) -> Result<Token> {
        self.get_token_info(address).await
    }

    async fn get_token_balances(&self, address: &str) -> Result<Vec<crate::chains::TokenBalance>> {
        let solana_balances = self.get_token_balances(address).await?;
        Ok(solana_balances
            .into_iter()
            .map(|tb| crate::chains::TokenBalance {
                token: Token {
                    contract_address: tb.mint.clone(),
                    symbol: tb
                        .symbol
                        .unwrap_or_else(|| tb.mint[..8.min(tb.mint.len())].to_string()),
                    name: tb.name.unwrap_or_else(|| "SPL Token".to_string()),
                    decimals: tb.decimals,
                },
                balance: tb.raw_amount,
                formatted_balance: format!("{:.6}", tb.ui_amount),
                usd_value: None,
            })
            .collect())
    }
}

// ============================================================================
// Unit Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::chains::{Balance, ChainClient};

    // Valid Solana address (Phantom treasury)
    const VALID_ADDRESS: &str = "DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy";

    // Valid Solana transaction signature
    const VALID_SIGNATURE: &str =
        "5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW";

    #[test]
    fn test_validate_solana_address_valid() {
        assert!(validate_solana_address(VALID_ADDRESS).is_ok());
    }

    #[test]
    fn test_validate_solana_address_empty() {
        let result = validate_solana_address("");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("empty"));
    }

    #[test]
    fn test_validate_solana_address_too_short() {
        let result = validate_solana_address("DRpbCBMxVnDK7maPM5t");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("32-44"));
    }

    #[test]
    fn test_validate_solana_address_too_long() {
        let long_addr = "DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hyAAAAAAAAAAAA";
        let result = validate_solana_address(long_addr);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_solana_address_invalid_base58() {
        // Contains '0' which is not valid base58
        let result = validate_solana_address("0RpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("base58"));
    }

    #[test]
    fn test_validate_solana_address_wrong_decoded_length() {
        // Valid base58 but decodes to wrong byte length (not 32 bytes)
        // "abc" is valid base58 but too short when decoded
        let result = validate_solana_address("abcdefghijabcdefghijabcdefghijab");
        assert!(result.is_err());
        // Should fail due to decoded length being wrong
    }

    #[test]
    fn test_validate_solana_signature_valid() {
        assert!(validate_solana_signature(VALID_SIGNATURE).is_ok());
    }

    #[test]
    fn test_validate_solana_signature_empty() {
        let result = validate_solana_signature("");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("empty"));
    }

    #[test]
    fn test_validate_solana_signature_too_short() {
        let result = validate_solana_signature("abc");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("80-90"));
    }

    #[test]
    fn test_solana_client_default() {
        let client = SolanaClient::default();
        assert_eq!(client.chain_name(), "solana");
        assert_eq!(client.native_token_symbol(), "SOL");
        assert!(client.rpc_url.contains("mainnet-beta"));
    }

    #[test]
    fn test_solana_client_with_rpc_url() {
        let client = SolanaClient::with_rpc_url("https://custom.rpc.com");
        assert_eq!(client.rpc_url, "https://custom.rpc.com");
    }

    #[test]
    fn test_solana_client_new() {
        let config = ChainsConfig::default();
        let client = SolanaClient::new_with_http(&config, crate::http::test_transport());
        assert!(client.is_ok());
    }

    #[test]
    fn test_solana_client_new_with_custom_rpc() {
        let config = ChainsConfig {
            solana_rpc: Some("https://my-solana-rpc.com".to_string()),
            ..Default::default()
        };
        let client = SolanaClient::new_with_http(&config, crate::http::test_transport()).unwrap();
        assert_eq!(client.rpc_url, "https://my-solana-rpc.com");
    }

    #[test]
    fn test_solana_client_new_with_api_key() {
        use std::collections::HashMap;

        let mut api_keys = HashMap::new();
        api_keys.insert("solscan".to_string(), "test-key".to_string());

        let config = ChainsConfig {
            api_keys,
            ..Default::default()
        };

        let client = SolanaClient::new_with_http(&config, crate::http::test_transport()).unwrap();
        assert_eq!(client.solscan_api_key, Some("test-key".to_string()));
    }

    #[test]
    fn test_rpc_request_serialization() {
        let request = RpcRequest {
            jsonrpc: "2.0",
            id: 1,
            method: "getBalance",
            params: vec!["test"],
        };

        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("jsonrpc"));
        assert!(json.contains("getBalance"));
    }

    #[test]
    fn test_rpc_response_deserialization() {
        let json = r#"{"jsonrpc":"2.0","result":{"value":1000000000},"id":1}"#;
        let response: RpcResponse<BalanceResponse> = serde_json::from_str(json).unwrap();
        assert!(response.result.is_some());
        assert_eq!(response.result.unwrap().value, 1_000_000_000);
    }

    #[test]
    fn test_rpc_error_deserialization() {
        let json =
            r#"{"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid request"},"id":1}"#;
        let response: RpcResponse<BalanceResponse> = serde_json::from_str(json).unwrap();
        assert!(response.error.is_some());
        let error = response.error.unwrap();
        assert_eq!(error.code, -32600);
        assert_eq!(error.message, "Invalid request");
    }

    // ========================================================================
    // HTTP mocking tests
    // ========================================================================

    #[tokio::test]
    async fn test_get_balance() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":{"value":5000000000},"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let balance = client.get_balance(VALID_ADDRESS).await.unwrap();
        assert_eq!(balance.raw, "5000000000");
        assert_eq!(balance.symbol, "SOL");
        assert_eq!(balance.decimals, 9);
        assert!(balance.formatted.contains("5.000000000"));
    }

    #[tokio::test]
    async fn test_get_balance_zero() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":{"value":0},"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let balance = client.get_balance(VALID_ADDRESS).await.unwrap();
        assert_eq!(balance.raw, "0");
        assert!(balance.formatted.contains("0.000000000"));
    }

    #[tokio::test]
    async fn test_get_balance_rpc_error() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid params"},"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client.get_balance(VALID_ADDRESS).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("RPC error"));
    }

    #[tokio::test]
    async fn test_get_balance_empty_response() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client.get_balance(VALID_ADDRESS).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Empty RPC"));
    }

    #[tokio::test]
    async fn test_get_balance_invalid_address() {
        let client = SolanaClient::default();
        let result = client.get_balance("invalid").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_get_transaction() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","result":{
                "slot":123456789,
                "blockTime":1700000000,
                "transaction":{
                    "message":{
                        "accountKeys":[
                            {"pubkey":"DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy","signer":true},
                            {"pubkey":"9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM","signer":false}
                        ]
                    }
                },
                "meta":{
                    "fee":5000,
                    "preBalances":[10000000000,5000000000],
                    "postBalances":[8999995000,6000000000],
                    "err":null
                }
            },"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let tx = client.get_transaction(VALID_SIGNATURE).await.unwrap();
        assert_eq!(tx.hash, VALID_SIGNATURE);
        assert_eq!(tx.from, "DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy");
        assert_eq!(
            tx.to,
            Some("9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM".to_string())
        );
        assert_eq!(tx.block_number, Some(123456789));
        assert_eq!(tx.timestamp, Some(1700000000));
        assert!(tx.status.unwrap()); // err is null → success
        assert_eq!(tx.gas_price, "5000"); // fee
    }

    #[tokio::test]
    async fn test_get_transaction_failed() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":{
                "slot":100,
                "transaction":{"message":{"accountKeys":["DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy"]}},
                "meta":{"fee":5000,"preBalances":[1000],"postBalances":[1000],"err":{"InstructionError":[0,{"Custom":1}]}}
            },"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let tx = client.get_transaction(VALID_SIGNATURE).await.unwrap();
        assert!(!tx.status.unwrap()); // err is not null → failure
    }

    #[tokio::test]
    async fn test_get_transaction_not_found() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":null,"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client.get_transaction(VALID_SIGNATURE).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[tokio::test]
    async fn test_get_transaction_string_account_keys() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":{
                "slot":100,
                "transaction":{"message":{"accountKeys":["DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy","9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM"]}},
                "meta":{"fee":5000,"preBalances":[1000000000,0],"postBalances":[999995000,0],"err":null}
            },"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let tx = client.get_transaction(VALID_SIGNATURE).await.unwrap();
        assert_eq!(tx.from, "DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy");
        assert_eq!(
            tx.to,
            Some("9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM".to_string())
        );
    }

    #[tokio::test]
    async fn test_get_signatures() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":[
                {"signature":"5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW","slot":100,"blockTime":1700000000,"err":null},
                {"signature":"4VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUX","slot":101,"blockTime":1700000060,"err":{"InstructionError":[0,{"Custom":1}]}}
            ],"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let sigs = client.get_signatures(VALID_ADDRESS, 10).await.unwrap();
        assert_eq!(sigs.len(), 2);
        assert!(sigs[0].starts_with("5VERv8"));
    }

    #[tokio::test]
    async fn test_get_transactions() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":[
                {"signature":"5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW","slot":100,"blockTime":1700000000,"err":null},
                {"signature":"4VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUX","slot":101,"blockTime":1700000060,"err":{"InstructionError":[0,{"Custom":1}]}}
            ],"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let txs = client.get_transactions(VALID_ADDRESS, 10).await.unwrap();
        assert_eq!(txs.len(), 2);
        assert!(txs[0].status.unwrap()); // err null → success
        assert!(!txs[1].status.unwrap()); // err present → failure
        assert_eq!(txs[0].block_number, Some(100));
        assert_eq!(txs[0].timestamp, Some(1700000000));
    }

    #[tokio::test]
    async fn test_get_token_balances() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","result":{"value":[
                {
                    "pubkey":"TokenAccAddr1",
                    "account":{
                        "data":{
                            "parsed":{
                                "info":{
                                    "mint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
                                    "tokenAmount":{
                                        "amount":"1000000",
                                        "decimals":6,
                                        "uiAmount":1.0,
                                        "uiAmountString":"1"
                                    }
                                }
                            }
                        }
                    }
                },
                {
                    "pubkey":"TokenAccAddr2",
                    "account":{
                        "data":{
                            "parsed":{
                                "info":{
                                    "mint":"So11111111111111111111111111111111111111112",
                                    "tokenAmount":{
                                        "amount":"0",
                                        "decimals":9,
                                        "uiAmount":0.0,
                                        "uiAmountString":"0"
                                    }
                                }
                            }
                        }
                    }
                }
            ]},"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let balances = client.get_token_balances(VALID_ADDRESS).await.unwrap();
        // Second token has zero balance so it's filtered out
        assert_eq!(balances.len(), 1);
        assert_eq!(
            balances[0].mint,
            "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
        );
        assert_eq!(balances[0].ui_amount, 1.0);
        assert_eq!(balances[0].decimals, 6);
    }

    #[tokio::test]
    async fn test_get_token_balances_rpc_error() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid params"},"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client.get_token_balances(VALID_ADDRESS).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_get_slot() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":256000000,"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let slot = client.get_slot().await.unwrap();
        assert_eq!(slot, 256000000);
    }

    #[tokio::test]
    async fn test_get_slot_error() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","error":{"code":-32005,"message":"Node is behind"},"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client.get_slot().await;
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_solana_signature_invalid_base58() {
        // '0' and 'O' and 'I' and 'l' are not valid base58 characters
        let bad_sig = "0OIl00000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
        let result = validate_solana_signature(bad_sig);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_solana_signature_wrong_decoded_length() {
        // Valid base58 but decodes to wrong length (not 64 bytes)
        // "1" decodes to a single zero byte
        let short = "11111111111111111111111111111111"; // 32 chars of '1' = 32 zero bytes
        let result = validate_solana_signature(short);
        // This should fail: either length check or decoded-byte-count check
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_get_transaction_rpc_error() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","error":{"code":-32600,"message":"Transaction not found"},"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client
            .get_transaction("5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW")
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("RPC error"));
    }

    #[tokio::test]
    async fn test_solana_chain_client_trait_chain_name() {
        let client = SolanaClient::with_rpc_url("http://localhost:8899");
        let chain_client: &dyn ChainClient = &client;
        assert_eq!(chain_client.chain_name(), "solana");
        assert_eq!(chain_client.native_token_symbol(), "SOL");
    }

    #[tokio::test]
    async fn test_chain_client_trait_get_balance() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","result":{"context":{"slot":1},"value":1000000000},"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let chain_client: &dyn ChainClient = &client;
        let balance = chain_client.get_balance(VALID_ADDRESS).await.unwrap();
        assert_eq!(balance.symbol, "SOL");
    }

    #[tokio::test]
    async fn test_chain_client_trait_get_block_number() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":250000000,"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let chain_client: &dyn ChainClient = &client;
        let slot = chain_client.get_block_number().await.unwrap();
        assert_eq!(slot, 250000000);
    }

    #[tokio::test]
    async fn test_chain_client_trait_get_token_balances() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","result":{"context":{"slot":1},"value":[
                {
                    "pubkey":"TokenAccAddr1",
                    "account":{
                        "data":{
                            "parsed":{
                                "info":{
                                    "mint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
                                    "tokenAmount":{
                                        "amount":"1000000",
                                        "decimals":6,
                                        "uiAmount":1.0,
                                        "uiAmountString":"1"
                                    }
                                }
                            }
                        }
                    }
                }
            ]},"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let chain_client: &dyn ChainClient = &client;
        let balances = chain_client
            .get_token_balances(VALID_ADDRESS)
            .await
            .unwrap();
        assert!(!balances.is_empty());
        // Verify the mapping from SolanaTokenBalance to TokenBalance
        assert_eq!(
            balances[0].token.contract_address,
            "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
        );
    }

    #[tokio::test]
    async fn test_chain_client_trait_get_transaction_solana() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","result":{
                "slot":200000000,
                "blockTime":1700000000,
                "meta":{
                    "fee":5000,
                    "preBalances":[1000000000,500000000],
                    "postBalances":[999995000,500005000],
                    "err":null
                },
                "transaction":{
                    "message":{
                        "accountKeys":[
                            "DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy",
                            "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
                        ]
                    },
                    "signatures":["5VERv8NMhCTbSNjqo3hFKXwDVbxZFTkHxRejuuG5VBERKKCrgLjfyZ5mhCBvNB3qNm4Z9gFZ7Py3HT7bJGUCmAh"]
                }
            },"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let chain_client: &dyn ChainClient = &client;
        let tx = chain_client
            .get_transaction("5VERv8NMhCTbSNjqo3hFKXwDVbxZFTkHxRejuuG5VBERKKCrgLjfyZ5mhCBvNB3qNm4Z9gFZ7Py3HT7bJGUCmAh")
            .await
            .unwrap();
        assert!(!tx.hash.is_empty());
        assert!(tx.timestamp.is_some());
    }

    #[tokio::test]
    async fn test_chain_client_trait_get_transactions_solana() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","result":[
                {
                    "signature":"5VERv8NMhCTbSNjqo3hFKXwDVbxZFTkHxRejuuG5VBERKKCrgLjfyZ5mhCBvNB3qNm4Z9gFZ7Py3HT7bJGUCmAh",
                    "slot":200000000,
                    "blockTime":1700000000,
                    "err":null,
                    "memo":null
                }
            ],"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let chain_client: &dyn ChainClient = &client;
        let txs = chain_client
            .get_transactions(VALID_ADDRESS, 10)
            .await
            .unwrap();
        assert!(!txs.is_empty());
    }

    #[test]
    fn test_validate_solana_signature_wrong_byte_length() {
        // A valid base58 string that is 80-90 chars but decodes to wrong number of bytes
        // We use a padded version of a 32-byte key (which would be ~44 chars in base58)
        // Instead, let's create a signature-length string that decodes to wrong byte count
        // A 32-byte value encoded in base58 is ~44 chars, so we need something 80-90 chars
        // that decodes to != 64 bytes.
        // We can take a valid-length string and pad it:
        let long_sig = "1".repeat(88); // All '1' in base58 decodes to all zeros, but it will be 88 bytes of zeros which is != 64
        let result = validate_solana_signature(&long_sig);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("64 bytes") || err.contains("base58"));
    }

    #[tokio::test]
    async fn test_rpc_error_response() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid request"},"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client.get_balance(VALID_ADDRESS).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("RPC error"));
    }

    // ========================================================================
    // get_token_info tests
    // ========================================================================

    #[tokio::test]
    async fn test_get_token_info_success() {
        // SPL Token mint layout: 32 (mint_authority) + 8 (supply) + 1 (decimals)
        // Decimals at offset 40. Create 41 bytes with decimals=6.
        let mut mint_data = vec![0u8; 41];
        mint_data[40] = 6;
        let data_b64 =
            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &mint_data);

        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(format!(
                r#"{{"jsonrpc":"2.0","result":{{"value":{{"data":["{}"]}}}},"id":1}}"#,
                data_b64
            ))
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let token = client
            .get_token_info("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")
            .await
            .unwrap();
        assert_eq!(token.decimals, 6);
        assert_eq!(
            token.contract_address,
            "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
        );
        assert_eq!(token.symbol, "EPjFWd…Dt1v");
        assert_eq!(token.name, "SPL Token");
    }

    #[tokio::test]
    async fn test_get_token_info_decimals_nine() {
        let mut mint_data = vec![0u8; 41];
        mint_data[40] = 9;
        let data_b64 =
            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &mint_data);

        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(format!(
                r#"{{"jsonrpc":"2.0","result":{{"value":{{"data":["{}"]}}}},"id":1}}"#,
                data_b64
            ))
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let token = client
            .get_token_info("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")
            .await
            .unwrap();
        assert_eq!(token.decimals, 9);
        assert_eq!(token.symbol, "EPjFWd…Dt1v"); // the one abbreviation
    }

    #[tokio::test]
    async fn test_get_token_info_rpc_error() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params"},"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client
            .get_token_info("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("RPC error"));
    }

    #[tokio::test]
    async fn test_get_token_info_not_found() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":{"value":null},"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client
            .get_token_info("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[tokio::test]
    async fn test_get_token_info_no_account_data() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":{"value":{"data":null}},"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client
            .get_token_info("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("No account data"));
    }

    #[tokio::test]
    async fn test_get_token_info_empty_data_array() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":{"value":{"data":[]}},"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client
            .get_token_info("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_get_token_info_invalid_base64() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":{"value":{"data":["!!!invalid!!!"]}},"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client
            .get_token_info("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("decode"));
    }

    #[tokio::test]
    async fn test_get_token_info_data_too_short() {
        // Only 20 bytes - not enough for decimals at offset 40
        let short_data = vec![0u8; 20];
        let data_b64 =
            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &short_data);

        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(format!(
                r#"{{"jsonrpc":"2.0","result":{{"value":{{"data":["{}"]}}}},"id":1}}"#,
                data_b64
            ))
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client
            .get_token_info("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("too short"));
    }

    #[tokio::test]
    async fn test_get_token_info_invalid_address() {
        let client = SolanaClient::default();
        let result = client.get_token_info("bad").await;
        assert!(result.is_err());
    }

    // ========================================================================
    // get_transaction edge cases
    // ========================================================================

    #[tokio::test]
    async fn test_get_transaction_minimal_no_transaction_meta() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":{"slot":100},"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let tx = client.get_transaction(VALID_SIGNATURE).await.unwrap();
        assert_eq!(tx.hash, VALID_SIGNATURE);
        assert_eq!(tx.from, "");
        assert_eq!(tx.to, None);
        assert_eq!(tx.value, "0");
        assert_eq!(tx.gas_price, "0");
        assert_eq!(tx.block_number, Some(100));
        assert_eq!(tx.status, None);
    }

    #[tokio::test]
    async fn test_get_transaction_single_account_key_to_none() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":{
                "slot":100,
                "blockTime":1700000000,
                "transaction":{"message":{"accountKeys":["DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy"]}},
                "meta":{"fee":5000,"preBalances":[1000],"postBalances":[500],"err":null}
            },"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let tx = client.get_transaction(VALID_SIGNATURE).await.unwrap();
        assert_eq!(tx.from, "DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy");
        assert_eq!(tx.to, None); // Only one account key
        assert_eq!(tx.value, "0"); // pre/post len < 2
    }

    #[tokio::test]
    async fn test_get_transaction_value_zero_when_no_send() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","result":{
                "slot":100,
                "transaction":{"message":{"accountKeys":["A","B"]}},
                "meta":{"fee":5000,"preBalances":[1000,500],"postBalances":[1000,500],"err":null}
            },"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let tx = client.get_transaction(VALID_SIGNATURE).await.unwrap();
        assert_eq!(tx.value, "0"); // pre[0]-post[0]-fee = 1000-1000-500 = 0 (saturating)
    }

    #[tokio::test]
    async fn test_get_transaction_meta_no_fee() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","result":{
                "slot":100,
                "transaction":{"message":{"accountKeys":["A","B"]}},
                "meta":{"preBalances":[10000000000,0],"postBalances":[8999995000,1000005000],"err":null}
            },"id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let tx = client.get_transaction(VALID_SIGNATURE).await.unwrap();
        assert_eq!(tx.gas_price, "0"); // fee is None, default 0
    }

    #[tokio::test]
    async fn test_get_transaction_invalid_signature() {
        let client = SolanaClient::default();
        let result = client.get_transaction("invalid").await;
        assert!(result.is_err());
    }

    // ========================================================================
    // get_signatures and get_transactions error paths
    // ========================================================================

    #[tokio::test]
    async fn test_get_signatures_empty_response() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client.get_signatures(VALID_ADDRESS, 10).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Empty RPC"));
    }

    #[tokio::test]
    async fn test_get_signatures_invalid_address() {
        let client = SolanaClient::default();
        let result = client.get_signatures("x", 10).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_get_signatures_rpc_error() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid address"},"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client.get_signatures(VALID_ADDRESS, 10).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_get_transactions_invalid_address() {
        let client = SolanaClient::default();
        let result = client.get_transactions("invalid-addr", 10).await;
        assert!(result.is_err());
    }

    // ========================================================================
    // get_slot empty response
    // ========================================================================

    #[tokio::test]
    async fn test_get_slot_empty_response() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"jsonrpc":"2.0","id":1}"#)
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let result = client.get_slot().await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Empty RPC"));
    }

    // ========================================================================
    // Token balance uiAmount null and struct tests
    // ========================================================================

    #[tokio::test]
    async fn test_get_token_balances_ui_amount_null() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","result":{"value":[{
                    "pubkey":"TokenAccAddr1",
                    "account":{
                        "data":{
                            "parsed":{
                                "info":{
                                    "mint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
                                    "tokenAmount":{
                                        "amount":"0",
                                        "decimals":6,
                                        "uiAmount":null,
                                        "uiAmountString":"0"
                                    }
                                }
                            }
                        }
                    }
                }]},"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let balances = client.get_token_balances(VALID_ADDRESS).await.unwrap();
        // uiAmount null -> unwrap_or(0.0) -> filtered out
        assert_eq!(balances.len(), 0);
    }

    #[test]
    fn test_token_balance_serialization() {
        let tb = TokenBalance {
            mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v".to_string(),
            token_account: "TokenAcc1".to_string(),
            raw_amount: "1000000".to_string(),
            ui_amount: 1.5,
            decimals: 6,
            symbol: Some("USDC".to_string()),
            name: Some("USD Coin".to_string()),
        };
        let json = serde_json::to_string(&tb).unwrap();
        assert!(json.contains("USDC"));
        assert!(json.contains("1000000"));
    }

    #[tokio::test]
    async fn test_chain_client_get_token_balances_short_mint() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","result":{"value":[{
                    "pubkey":"TokenAcc1",
                    "account":{
                        "data":{
                            "parsed":{
                                "info":{
                                    "mint":"Short",
                                    "tokenAmount":{
                                        "amount":"100",
                                        "decimals":2,
                                        "uiAmount":1.0,
                                        "uiAmountString":"1"
                                    }
                                }
                            }
                        }
                    }
                }]},"id":1}"#,
            )
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let chain_client: &dyn ChainClient = &client;
        let balances = chain_client
            .get_token_balances("DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy")
            .await
            .unwrap();
        assert_eq!(balances.len(), 1);
        // Short mint "Short" (5 chars) -> symbol uses mint[..5] = "Short"
        assert_eq!(balances[0].token.symbol, "Short");
    }

    // ========================================================================
    // validate_solana_signature too_long
    // ========================================================================

    #[test]
    fn test_validate_solana_signature_too_long() {
        let too_long = "1".repeat(91);
        let result = validate_solana_signature(&too_long);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("80-90"));
    }

    // ========================================================================
    // enrich_balance_usd (balance.raw parse failure)
    // ========================================================================

    #[tokio::test]
    async fn test_enrich_balance_usd_invalid_raw_does_not_panic() {
        let client = SolanaClient::default();
        let mut balance = Balance {
            raw: "not-a-number".to_string(),
            formatted: "0 SOL".to_string(),
            decimals: 9,
            symbol: "SOL".to_string(),
            usd_value: None,
        };
        // Should not panic - unwrap_or(0.0) handles parse failure
        client.enrich_balance_usd(&mut balance).await;
        // Balance unchanged when parse fails (or DexScreener fails)
        assert!(balance.usd_value.is_none() || balance.usd_value == Some(0.0));
    }

    #[tokio::test]
    async fn test_chain_client_trait_enrich_balance_usd() {
        let client = SolanaClient::default();
        let chain_client: &dyn ChainClient = &client;
        let mut balance = Balance {
            raw: "not-a-number".to_string(),
            formatted: "0 SOL".to_string(),
            decimals: 9,
            symbol: "SOL".to_string(),
            usd_value: None,
        };
        chain_client.enrich_balance_usd(&mut balance).await;
        assert!(balance.usd_value.is_none() || balance.usd_value == Some(0.0));
    }

    #[tokio::test]
    async fn test_chain_client_trait_get_token_info() {
        let mut mint_data = vec![0u8; 41];
        mint_data[40] = 18;
        let data_b64 =
            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &mint_data);

        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(format!(
                r#"{{"jsonrpc":"2.0","result":{{"value":{{"data":["{}"]}}}},"id":1}}"#,
                data_b64
            ))
            .create_async()
            .await;

        let client = SolanaClient::with_rpc_url(&server.url());
        let chain_client: &dyn ChainClient = &client;
        let token = chain_client
            .get_token_info("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")
            .await
            .unwrap();
        assert_eq!(token.decimals, 18);
    }

    // ========================================================================
    // SolscanAccountInfo deserialization (dead_code struct)
    // ========================================================================

    #[test]
    fn test_solscan_account_info_deserialization() {
        let json = r#"{"lamports":1000000,"type":"account"}"#;
        let info: SolscanAccountInfo = serde_json::from_str(json).unwrap();
        assert_eq!(info.lamports, 1000000);
        assert_eq!(info.account_type, Some("account".to_string()));
    }
}