scope-bca-core 0.8.2

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
//! # DEX Aggregator Client
//!
//! This module provides a client for fetching token price and volume data
//! from DEX aggregator APIs like DexScreener.
//!
//! ## Supported APIs
//!
//! - **DexScreener** (primary): Free API, no key required
//!   - Token data: `GET https://api.dexscreener.com/latest/dex/tokens/{address}`
//!   - Pair data: `GET https://api.dexscreener.com/latest/dex/pairs/{chain}/{pair}`
//!   - Token search: `GET https://api.dexscreener.com/latest/dex/search?q={query}`
//!
//! ## Features
//!
//! - Comprehensive token data aggregation across all DEX pairs
//! - Native token price lookups for USD valuation (ETH, SOL, BNB, MATIC, etc.)
//! - Individual token price lookups by contract address
//! - Token search with chain filtering
//! - Historical price and volume data interpolation
//!
//! ## Usage
//!
//! ```rust,no_run
//! use scope::chains::DexClient;
//!
//! #[tokio::main]
//! async fn main() -> scope::Result<()> {
//!     let http = scope::http::build(&scope::Config::default())?.client;
//!     let client = DexClient::new_with_http(http);
//!     
//!     // Fetch token data by address
//!     let data = client.get_token_data("ethereum", "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").await?;
//!     println!("Price: ${}", data.price_usd);
//!     
//!     // Get native token price for USD valuation
//!     if let Some(eth_price) = client.get_native_token_price("ethereum").await {
//!         println!("ETH: ${:.2}", eth_price);
//!     }
//!     
//!     Ok(())
//! }
//! ```

use crate::chains::{DexPair, PricePoint, VolumePoint};
use crate::error::{Result, ScopeError};
use crate::http::{HttpClient, Request};
use async_trait::async_trait;
use serde::Deserialize;
use std::sync::Arc;

/// DexScreener API base URL.
const DEXSCREENER_API_BASE: &str = "https://api.dexscreener.com";

/// Trait for DEX data providers (prices, token data, search).
///
/// Abstracts the DexScreener API to enable dependency injection and testing.
#[async_trait]
pub trait DexDataSource: Send + Sync {
    /// Fetches the price for a specific token on a chain.
    async fn get_token_price(&self, chain: &str, address: &str) -> Option<f64>;

    /// Fetches the native token price for a chain (e.g., ETH for ethereum).
    async fn get_native_token_price(&self, chain: &str) -> Option<f64>;

    /// Fetches comprehensive token data including pairs, volume, liquidity.
    async fn get_token_data(&self, chain: &str, address: &str) -> Result<DexTokenData>;

    /// Searches for tokens by query string with optional chain filter.
    async fn search_tokens(
        &self,
        query: &str,
        chain: Option<&str>,
    ) -> Result<Vec<TokenSearchResult>>;
}

/// Client for fetching DEX aggregator data.
#[derive(Clone)]
pub struct DexClient {
    http: Arc<dyn HttpClient>,
    base_url: String,
}

/// Response from DexScreener token endpoint.
#[derive(Debug, Deserialize)]
struct DexScreenerTokenResponse {
    pairs: Option<Vec<DexScreenerPair>>,
}

/// A trading pair from DexScreener.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct DexScreenerPair {
    chain_id: String,
    dex_id: String,
    pair_address: String,
    base_token: DexScreenerToken,
    quote_token: DexScreenerToken,
    #[serde(default)]
    price_usd: Option<String>,
    #[serde(default)]
    price_change: Option<DexScreenerPriceChange>,
    #[serde(default)]
    volume: Option<DexScreenerVolume>,
    #[serde(default)]
    liquidity: Option<DexScreenerLiquidity>,
    #[serde(default)]
    fdv: Option<f64>,
    #[serde(default)]
    market_cap: Option<f64>,
    /// Direct URL to the pair on DexScreener.
    #[serde(default)]
    url: Option<String>,
    /// Timestamp when the pair was created.
    #[serde(default)]
    pair_created_at: Option<i64>,
    /// Transaction counts for buy/sell analysis.
    #[serde(default)]
    txns: Option<DexScreenerTxns>,
    /// Token metadata including socials and websites.
    #[serde(default)]
    info: Option<DexScreenerInfo>,
}

/// Token info from DexScreener.
#[derive(Debug, Deserialize)]
struct DexScreenerToken {
    address: String,
    name: String,
    symbol: String,
}

/// Price change percentages from DexScreener.
#[derive(Debug, Deserialize)]
struct DexScreenerPriceChange {
    h24: Option<f64>,
    h6: Option<f64>,
    h1: Option<f64>,
    m5: Option<f64>,
}

/// Volume data from DexScreener.
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct DexScreenerVolume {
    h24: Option<f64>,
    h6: Option<f64>,
    h1: Option<f64>,
    m5: Option<f64>,
}

/// Liquidity data from DexScreener.
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct DexScreenerLiquidity {
    usd: Option<f64>,
    base: Option<f64>,
    quote: Option<f64>,
}

/// Transaction counts from DexScreener (buy/sell activity).
#[derive(Debug, Deserialize, Default)]
#[allow(dead_code)]
struct DexScreenerTxns {
    #[serde(default)]
    h24: Option<TxnCounts>,
    #[serde(default)]
    h6: Option<TxnCounts>,
    #[serde(default)]
    h1: Option<TxnCounts>,
    #[serde(default)]
    m5: Option<TxnCounts>,
}

/// Buy/sell transaction counts for a time period.
#[derive(Debug, Deserialize, Clone, Default)]
struct TxnCounts {
    #[serde(default)]
    buys: u64,
    #[serde(default)]
    sells: u64,
}

/// Token metadata from DexScreener info endpoint.
#[derive(Debug, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
struct DexScreenerInfo {
    #[serde(default)]
    image_url: Option<String>,
    #[serde(default)]
    websites: Option<Vec<DexScreenerWebsite>>,
    #[serde(default)]
    socials: Option<Vec<DexScreenerSocial>>,
}

/// Website info from DexScreener.
#[derive(Debug, Deserialize, Clone)]
#[allow(dead_code)]
struct DexScreenerWebsite {
    #[serde(default)]
    label: Option<String>,
    #[serde(default)]
    url: Option<String>,
}

/// Social media info from DexScreener.
#[derive(Debug, Deserialize, Clone)]
struct DexScreenerSocial {
    #[serde(rename = "type", default)]
    platform: Option<String>,
    #[serde(default)]
    url: Option<String>,
}

/// Aggregated token data from DEX sources.
#[derive(Debug, Clone)]
pub struct DexTokenData {
    /// Token contract address.
    pub address: String,

    /// Token symbol.
    pub symbol: String,

    /// Token name.
    pub name: String,

    /// Current price in USD.
    pub price_usd: f64,

    /// 24-hour price change percentage.
    pub price_change_24h: f64,

    /// 6-hour price change percentage.
    pub price_change_6h: f64,

    /// 1-hour price change percentage.
    pub price_change_1h: f64,

    /// 5-minute price change percentage.
    pub price_change_5m: f64,

    /// 24-hour trading volume in USD.
    pub volume_24h: f64,

    /// 6-hour trading volume in USD.
    pub volume_6h: f64,

    /// 1-hour trading volume in USD.
    pub volume_1h: f64,

    /// Total liquidity across all pairs in USD.
    pub liquidity_usd: f64,

    /// Market capitalization (if available).
    pub market_cap: Option<f64>,

    /// Fully diluted valuation (if available).
    pub fdv: Option<f64>,

    /// All trading pairs for this token.
    pub pairs: Vec<DexPair>,

    /// Historical price points (derived from multiple time frames).
    pub price_history: Vec<PricePoint>,

    /// Historical volume points (derived from multiple time frames).
    pub volume_history: Vec<VolumePoint>,

    /// Total buy transactions in 24 hours.
    pub total_buys_24h: u64,

    /// Total sell transactions in 24 hours.
    pub total_sells_24h: u64,

    /// Total buy transactions in 6 hours.
    pub total_buys_6h: u64,

    /// Total sell transactions in 6 hours.
    pub total_sells_6h: u64,

    /// Total buy transactions in 1 hour.
    pub total_buys_1h: u64,

    /// Total sell transactions in 1 hour.
    pub total_sells_1h: u64,

    /// Earliest pair creation timestamp (token age indicator).
    pub earliest_pair_created_at: Option<i64>,

    /// Token image URL.
    pub image_url: Option<String>,

    /// Token website URLs.
    pub websites: Vec<String>,

    /// Token social media links.
    pub socials: Vec<TokenSocial>,

    /// DexScreener URL for the token.
    pub dexscreener_url: Option<String>,
}

/// Social media link for a token.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TokenSocial {
    /// Platform name (twitter, telegram, discord, etc.)
    pub platform: String,
    /// URL or handle for the social account.
    pub url: String,
}

/// A token search result from DEX aggregator.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TokenSearchResult {
    /// Token contract address.
    pub address: String,

    /// Token symbol.
    pub symbol: String,

    /// Token name.
    pub name: String,

    /// Blockchain network.
    pub chain: String,

    /// Current price in USD (if available).
    pub price_usd: Option<f64>,

    /// 24-hour trading volume in USD.
    pub volume_24h: f64,

    /// Total liquidity in USD.
    pub liquidity_usd: f64,

    /// Market cap (if available).
    pub market_cap: Option<f64>,
}

/// A discovered token from DexScreener (profiles, boosts, etc.)
#[derive(Debug, Clone, serde::Serialize)]
pub struct DiscoverToken {
    pub chain_id: String,
    pub token_address: String,
    pub url: String,
    pub description: Option<String>,
    pub links: Vec<DiscoverLink>,
}

#[derive(Debug, Clone, serde::Serialize)]
pub struct DiscoverLink {
    pub label: Option<String>,
    pub link_type: Option<String>,
    pub url: String,
}

/// Response from DexScreener search endpoint.
#[derive(Debug, Deserialize)]
struct DexScreenerSearchResponse {
    pairs: Option<Vec<DexScreenerPair>>,
}

impl DexClient {
    /// Creates a new DEX client with a transport built from the environment.
    #[deprecated(
        since = "0.8.0",
        note = "pass the transport: use `DexClient::new_with_http`"
    )]
    pub fn new() -> Self {
        Self::new_with_http(crate::http::shared::fallback())
    }

    /// Creates a new DEX client with a pre-built HTTP transport.
    pub fn new_with_http(http: Arc<dyn HttpClient>) -> Self {
        Self {
            http,
            base_url: DEXSCREENER_API_BASE.to_string(),
        }
    }

    /// Creates a new DEX client with a custom base URL (for testing).
    #[cfg(any(test, feature = "test-support"))]
    pub fn with_base_url(base_url: &str) -> Self {
        Self {
            http: crate::http::shared::fallback(),
            base_url: base_url.to_string(),
        }
    }

    /// Maps chain names to DexScreener chain IDs.
    fn map_chain_to_dexscreener(chain: &str) -> String {
        super::registry::chain(chain)
            .and_then(|c| c.dexscreener_id)
            .map_or_else(|| chain.to_lowercase(), str::to_string)
    }

    /// Fetches the USD price of a token by its address.
    ///
    /// Returns `None` if the token is not found or has no price data.
    pub async fn get_token_price(&self, chain: &str, token_address: &str) -> Option<f64> {
        let url = format!("{}/latest/dex/tokens/{}", self.base_url, token_address);

        let resp = self.http.send(Request::get(&url)).await.ok()?;
        let dex_response: DexScreenerTokenResponse = resp.json().ok()?;

        let dex_chain = Self::map_chain_to_dexscreener(chain);

        dex_response
            .pairs
            .as_ref()?
            .iter()
            .filter(|p| p.chain_id.to_lowercase() == dex_chain)
            .filter_map(|p| p.price_usd.as_ref()?.parse::<f64>().ok())
            .next()
    }

    /// Fetches the native token price for a chain.
    ///
    /// Uses well-known wrapped token addresses to determine the native token price.
    pub async fn get_native_token_price(&self, chain: &str) -> Option<f64> {
        let c = super::registry::chain(chain)?;
        let (search_chain, token_address) = (c.dexscreener_id?, c.wrapped_native?);

        self.get_token_price(search_chain, token_address).await
    }

    /// Fetches token data from DexScreener.
    ///
    /// # Arguments
    ///
    /// * `chain` - The blockchain name (e.g., "ethereum", "bsc")
    /// * `token_address` - The token contract address
    ///
    /// # Returns
    ///
    /// Returns aggregated token data from all DEX pairs.
    pub async fn get_token_data(&self, chain: &str, token_address: &str) -> Result<DexTokenData> {
        let url = format!("{}/latest/dex/tokens/{}", self.base_url, token_address);

        tracing::debug!(url = %url, "Fetching token data from DexScreener");

        let resp = self.http.send(Request::get(&url)).await?;

        if !resp.is_success() {
            return Err(ScopeError::Api(format!(
                "DexScreener API error: {}",
                resp.status_code
            )));
        }

        let data: DexScreenerTokenResponse = resp
            .json()
            .map_err(|e| ScopeError::Api(format!("Failed to parse DexScreener response: {}", e)))?;

        let pairs = data.pairs.unwrap_or_default();

        if pairs.is_empty() {
            return Err(ScopeError::NotFound(format!(
                "No DEX pairs found for token {}",
                token_address
            )));
        }

        // Filter pairs by chain
        let chain_id = Self::map_chain_to_dexscreener(chain);
        let chain_pairs: Vec<_> = pairs
            .iter()
            .filter(|p| p.chain_id.to_lowercase() == chain_id)
            .collect();

        // Use all pairs if no chain-specific pairs found
        let relevant_pairs = if chain_pairs.is_empty() {
            pairs.iter().collect()
        } else {
            chain_pairs
        };

        // Get token info from first pair
        let first_pair = &relevant_pairs[0];
        let is_base_token =
            first_pair.base_token.address.to_lowercase() == token_address.to_lowercase();
        let token_info = if is_base_token {
            &first_pair.base_token
        } else {
            &first_pair.quote_token
        };

        // Aggregate data from all pairs
        let mut total_volume_24h = 0.0;
        let mut total_volume_6h = 0.0;
        let mut total_volume_1h = 0.0;
        let mut total_liquidity = 0.0;
        let mut weighted_price_sum = 0.0;
        let mut liquidity_weight_sum = 0.0;
        let mut dex_pairs = Vec::new();

        for pair in &relevant_pairs {
            let pair_liquidity = pair.liquidity.as_ref().and_then(|l| l.usd).unwrap_or(0.0);

            let pair_price = pair
                .price_usd
                .as_ref()
                .and_then(|p| p.parse::<f64>().ok())
                .unwrap_or(0.0);

            if let Some(vol) = &pair.volume {
                total_volume_24h += vol.h24.unwrap_or(0.0);
                total_volume_6h += vol.h6.unwrap_or(0.0);
                total_volume_1h += vol.h1.unwrap_or(0.0);
            }

            total_liquidity += pair_liquidity;

            // Weight price by liquidity for more accurate average
            if pair_liquidity > 0.0 && pair_price > 0.0 {
                weighted_price_sum += pair_price * pair_liquidity;
                liquidity_weight_sum += pair_liquidity;
            }

            let price_change = pair
                .price_change
                .as_ref()
                .and_then(|pc| pc.h24)
                .unwrap_or(0.0);

            // Extract transaction counts
            let txn_counts_24h = pair.txns.as_ref().and_then(|t| t.h24.clone());
            let txn_counts_6h = pair.txns.as_ref().and_then(|t| t.h6.clone());
            let txn_counts_1h = pair.txns.as_ref().and_then(|t| t.h1.clone());

            dex_pairs.push(DexPair {
                dex_name: pair.dex_id.clone(),
                pair_address: pair.pair_address.clone(),
                base_token: pair.base_token.symbol.clone(),
                quote_token: pair.quote_token.symbol.clone(),
                price_usd: pair_price,
                volume_24h: pair.volume.as_ref().and_then(|v| v.h24).unwrap_or(0.0),
                liquidity_usd: pair_liquidity,
                liquidity_base: pair.liquidity.as_ref().and_then(|l| l.base),
                price_change_24h: price_change,
                buys_24h: txn_counts_24h.as_ref().map(|t| t.buys).unwrap_or(0),
                sells_24h: txn_counts_24h.as_ref().map(|t| t.sells).unwrap_or(0),
                buys_6h: txn_counts_6h.as_ref().map(|t| t.buys).unwrap_or(0),
                sells_6h: txn_counts_6h.as_ref().map(|t| t.sells).unwrap_or(0),
                buys_1h: txn_counts_1h.as_ref().map(|t| t.buys).unwrap_or(0),
                sells_1h: txn_counts_1h.as_ref().map(|t| t.sells).unwrap_or(0),
                pair_created_at: pair.pair_created_at,
                url: pair.url.clone(),
            });
        }

        // Calculate weighted average price
        let avg_price = if liquidity_weight_sum > 0.0 {
            weighted_price_sum / liquidity_weight_sum
        } else {
            first_pair
                .price_usd
                .as_ref()
                .and_then(|p| p.parse().ok())
                .unwrap_or(0.0)
        };

        // Get price change and market data from the highest liquidity pair
        let best_pair = relevant_pairs
            .iter()
            .max_by(|a, b| {
                let liq_a = a.liquidity.as_ref().and_then(|l| l.usd).unwrap_or(0.0);
                let liq_b = b.liquidity.as_ref().and_then(|l| l.usd).unwrap_or(0.0);
                liq_a
                    .partial_cmp(&liq_b)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .unwrap();

        let price_change_24h = best_pair
            .price_change
            .as_ref()
            .and_then(|pc| pc.h24)
            .unwrap_or(0.0);

        let price_change_6h = best_pair
            .price_change
            .as_ref()
            .and_then(|pc| pc.h6)
            .unwrap_or(0.0);

        let price_change_1h = best_pair
            .price_change
            .as_ref()
            .and_then(|pc| pc.h1)
            .unwrap_or(0.0);

        let price_change_5m = best_pair
            .price_change
            .as_ref()
            .and_then(|pc| pc.m5)
            .unwrap_or(0.0);

        // Aggregate transaction counts across all pairs
        let total_buys_24h: u64 = dex_pairs.iter().map(|p| p.buys_24h).sum();
        let total_sells_24h: u64 = dex_pairs.iter().map(|p| p.sells_24h).sum();
        let total_buys_6h: u64 = dex_pairs.iter().map(|p| p.buys_6h).sum();
        let total_sells_6h: u64 = dex_pairs.iter().map(|p| p.sells_6h).sum();
        let total_buys_1h: u64 = dex_pairs.iter().map(|p| p.buys_1h).sum();
        let total_sells_1h: u64 = dex_pairs.iter().map(|p| p.sells_1h).sum();

        // Find earliest pair creation timestamp
        let earliest_pair_created_at = dex_pairs.iter().filter_map(|p| p.pair_created_at).min();

        // Extract token metadata from best pair
        let image_url = best_pair.info.as_ref().and_then(|i| i.image_url.clone());
        let websites: Vec<String> = best_pair
            .info
            .as_ref()
            .and_then(|i| i.websites.as_ref())
            .map(|ws| ws.iter().filter_map(|w| w.url.clone()).collect())
            .unwrap_or_default();
        let socials: Vec<TokenSocial> = best_pair
            .info
            .as_ref()
            .and_then(|i| i.socials.as_ref())
            .map(|ss| {
                ss.iter()
                    .filter_map(|s| {
                        Some(TokenSocial {
                            platform: s.platform.clone()?,
                            url: s.url.clone()?,
                        })
                    })
                    .collect()
            })
            .unwrap_or_default();
        let dexscreener_url = best_pair.url.clone();

        // Generate synthetic price history from change percentages
        let now = chrono::Utc::now().timestamp();
        let price_history = Self::generate_price_history(avg_price, best_pair, now);

        // Generate synthetic volume history
        let volume_history =
            Self::generate_volume_history(total_volume_24h, total_volume_6h, total_volume_1h, now);

        Ok(DexTokenData {
            address: token_address.to_string(),
            symbol: token_info.symbol.clone(),
            name: token_info.name.clone(),
            price_usd: avg_price,
            price_change_24h,
            price_change_6h,
            price_change_1h,
            price_change_5m,
            volume_24h: total_volume_24h,
            volume_6h: total_volume_6h,
            volume_1h: total_volume_1h,
            liquidity_usd: total_liquidity,
            market_cap: best_pair.market_cap,
            fdv: best_pair.fdv,
            pairs: dex_pairs,
            price_history,
            volume_history,
            total_buys_24h,
            total_sells_24h,
            total_buys_6h,
            total_sells_6h,
            total_buys_1h,
            total_sells_1h,
            earliest_pair_created_at,
            image_url,
            websites,
            socials,
            dexscreener_url,
        })
    }

    /// Searches for tokens by name or symbol.
    ///
    /// # Arguments
    ///
    /// * `query` - The search query (token name or symbol)
    /// * `chain` - Optional chain filter (e.g., "ethereum", "bsc")
    ///
    /// # Returns
    ///
    /// Returns a vector of matching tokens sorted by liquidity.
    pub async fn search_tokens(
        &self,
        query: &str,
        chain: Option<&str>,
    ) -> Result<Vec<TokenSearchResult>> {
        let url = format!(
            "{}/latest/dex/search?q={}",
            self.base_url,
            urlencoding::encode(query)
        );

        tracing::debug!(url = %url, "Searching tokens on DexScreener");

        let resp = self.http.send(Request::get(&url)).await?;

        if !resp.is_success() {
            return Err(ScopeError::Api(format!(
                "DexScreener search API error: {}",
                resp.status_code
            )));
        }

        let data: DexScreenerSearchResponse = resp
            .json()
            .map_err(|e| ScopeError::Api(format!("Failed to parse search response: {}", e)))?;

        let pairs = data.pairs.unwrap_or_default();

        if pairs.is_empty() {
            return Ok(Vec::new());
        }

        // Filter by chain if specified
        let chain_id = chain.map(Self::map_chain_to_dexscreener);
        let filtered_pairs: Vec<_> = if let Some(ref cid) = chain_id {
            pairs
                .iter()
                .filter(|p| p.chain_id.to_lowercase() == *cid)
                .collect()
        } else {
            pairs.iter().collect()
        };

        // Deduplicate tokens by address and aggregate data
        let mut token_map: std::collections::HashMap<String, TokenSearchResult> =
            std::collections::HashMap::new();

        for pair in filtered_pairs {
            // Check if the query matches base or quote token
            let base_matches = pair
                .base_token
                .symbol
                .to_lowercase()
                .contains(&query.to_lowercase())
                || pair
                    .base_token
                    .name
                    .to_lowercase()
                    .contains(&query.to_lowercase());
            let quote_matches = pair
                .quote_token
                .symbol
                .to_lowercase()
                .contains(&query.to_lowercase())
                || pair
                    .quote_token
                    .name
                    .to_lowercase()
                    .contains(&query.to_lowercase());

            let token_info = if base_matches {
                &pair.base_token
            } else if quote_matches {
                &pair.quote_token
            } else {
                // Use base token by default
                &pair.base_token
            };

            let key = format!("{}:{}", pair.chain_id, token_info.address.to_lowercase());

            let pair_liquidity = pair.liquidity.as_ref().and_then(|l| l.usd).unwrap_or(0.0);

            let pair_volume = pair.volume.as_ref().and_then(|v| v.h24).unwrap_or(0.0);

            let pair_price = pair.price_usd.as_ref().and_then(|p| p.parse::<f64>().ok());

            let entry = token_map.entry(key).or_insert_with(|| TokenSearchResult {
                address: token_info.address.clone(),
                symbol: token_info.symbol.clone(),
                name: token_info.name.clone(),
                chain: pair.chain_id.clone(),
                price_usd: pair_price,
                volume_24h: 0.0,
                liquidity_usd: 0.0,
                market_cap: pair.market_cap,
            });

            // Aggregate volume and liquidity
            entry.volume_24h += pair_volume;
            entry.liquidity_usd += pair_liquidity;

            // Update price if better data available
            if entry.price_usd.is_none() && pair_price.is_some() {
                entry.price_usd = pair_price;
            }

            // Update market cap if available
            if entry.market_cap.is_none() && pair.market_cap.is_some() {
                entry.market_cap = pair.market_cap;
            }
        }

        // Convert to vector and sort: exact symbol matches first, then by liquidity
        let query_lower = query.to_lowercase();
        let mut results: Vec<TokenSearchResult> = token_map.into_values().collect();
        results.sort_by(|a, b| {
            let a_exact = a.symbol.to_lowercase() == query_lower;
            let b_exact = b.symbol.to_lowercase() == query_lower;
            b_exact.cmp(&a_exact).then(
                b.liquidity_usd
                    .partial_cmp(&a.liquidity_usd)
                    .unwrap_or(std::cmp::Ordering::Equal),
            )
        });

        // Limit results
        results.truncate(20);

        Ok(results)
    }

    /// Fetches latest token profiles (featured tokens) from DexScreener.
    pub async fn get_token_profiles(&self) -> Result<Vec<DiscoverToken>> {
        let url = format!("{}/token-profiles/latest/v1", self.base_url);
        self.fetch_discover_tokens(&url).await
    }

    /// Fetches latest boosted tokens from DexScreener.
    pub async fn get_token_boosts(&self) -> Result<Vec<DiscoverToken>> {
        let url = format!("{}/token-boosts/latest/v1", self.base_url);
        self.fetch_discover_tokens(&url).await
    }

    /// Fetches top boosted tokens (most active boosts) from DexScreener.
    pub async fn get_token_boosts_top(&self) -> Result<Vec<DiscoverToken>> {
        let url = format!("{}/token-boosts/top/v1", self.base_url);
        self.fetch_discover_tokens(&url).await
    }

    async fn fetch_discover_tokens(&self, url: &str) -> Result<Vec<DiscoverToken>> {
        let resp = self.http.send(Request::get(url)).await?;

        if !resp.is_success() {
            return Err(ScopeError::Api(format!(
                "DexScreener API error: {}",
                resp.status_code
            )));
        }

        #[derive(Deserialize)]
        struct TokenProfileRaw {
            url: Option<String>,
            #[serde(rename = "chainId")]
            chain_id: Option<String>,
            #[serde(rename = "tokenAddress")]
            token_address: Option<String>,
            description: Option<String>,
            links: Option<Vec<LinkRaw>>,
        }

        #[derive(Deserialize)]
        struct LinkRaw {
            label: Option<String>,
            #[serde(rename = "type")]
            link_type: Option<String>,
            url: Option<String>,
        }

        let raw: Vec<TokenProfileRaw> = resp
            .json()
            .map_err(|e| ScopeError::Api(format!("Failed to parse response: {}", e)))?;

        let tokens: Vec<DiscoverToken> = raw
            .into_iter()
            .filter_map(|r| {
                let token_address = r.token_address?;
                let chain_id = r.chain_id.clone().unwrap_or_else(|| "unknown".to_string());
                let url = r.url.clone().unwrap_or_else(|| {
                    format!("https://dexscreener.com/{}/{}", chain_id, token_address)
                });
                let links: Vec<DiscoverLink> = r
                    .links
                    .unwrap_or_default()
                    .into_iter()
                    .filter_map(|l| {
                        let url = l.url?;
                        Some(DiscoverLink {
                            label: l.label,
                            link_type: l.link_type,
                            url,
                        })
                    })
                    .collect();

                Some(DiscoverToken {
                    chain_id,
                    token_address,
                    url,
                    description: r.description,
                    links,
                })
            })
            .collect();

        Ok(tokens)
    }

    /// Generates synthetic price history from change percentages.
    fn generate_price_history(
        current_price: f64,
        pair: &DexScreenerPair,
        now: i64,
    ) -> Vec<PricePoint> {
        let mut history = Vec::new();

        // Get price changes at different intervals
        let changes = pair.price_change.as_ref();
        let change_24h = changes.and_then(|c| c.h24).unwrap_or(0.0) / 100.0;
        let change_6h = changes.and_then(|c| c.h6).unwrap_or(0.0) / 100.0;
        let change_1h = changes.and_then(|c| c.h1).unwrap_or(0.0) / 100.0;
        let change_5m = changes.and_then(|c| c.m5).unwrap_or(0.0) / 100.0;

        // Calculate historical prices (working backwards)
        let price_24h_ago = current_price / (1.0 + change_24h);
        let price_6h_ago = current_price / (1.0 + change_6h);
        let price_1h_ago = current_price / (1.0 + change_1h);
        let price_5m_ago = current_price / (1.0 + change_5m);

        // Add points at known intervals
        history.push(PricePoint {
            timestamp: now - 86400, // 24h ago
            price: price_24h_ago,
        });
        history.push(PricePoint {
            timestamp: now - 21600, // 6h ago
            price: price_6h_ago,
        });
        history.push(PricePoint {
            timestamp: now - 3600, // 1h ago
            price: price_1h_ago,
        });
        history.push(PricePoint {
            timestamp: now - 300, // 5m ago
            price: price_5m_ago,
        });
        history.push(PricePoint {
            timestamp: now,
            price: current_price,
        });

        // Interpolate additional points for smoother charts
        Self::interpolate_points(&mut history, 24);

        history.sort_by_key(|p| p.timestamp);
        history
    }

    /// Generates synthetic volume history from known data points.
    fn generate_volume_history(
        volume_24h: f64,
        volume_6h: f64,
        volume_1h: f64,
        now: i64,
    ) -> Vec<VolumePoint> {
        let mut history = Vec::new();

        // Create hourly buckets for the last 24 hours
        let hourly_avg = volume_24h / 24.0;

        for i in 0..24 {
            let timestamp = now - (23 - i) * 3600;
            let hours_ago = 24 - i;

            // Adjust volume based on known data points
            let volume = if hours_ago <= 1 {
                volume_1h
            } else if hours_ago <= 6 {
                volume_6h / 6.0
            } else {
                // Use average with some variation
                hourly_avg * (0.8 + (i as f64 / 24.0) * 0.4)
            };

            history.push(VolumePoint { timestamp, volume });
        }

        history
    }

    /// Interpolates additional price points for smoother charts.
    fn interpolate_points(history: &mut Vec<PricePoint>, target_count: usize) {
        if history.len() >= target_count {
            return;
        }

        history.sort_by_key(|p| p.timestamp);

        let mut interpolated = Vec::new();
        for window in history.windows(2) {
            let p1 = &window[0];
            let p2 = &window[1];

            interpolated.push(p1.clone());

            // Add midpoint
            let mid_timestamp = (p1.timestamp + p2.timestamp) / 2;
            let mid_price = (p1.price + p2.price) / 2.0;
            interpolated.push(PricePoint {
                timestamp: mid_timestamp,
                price: mid_price,
            });
        }

        if let Some(last) = history.last() {
            interpolated.push(last.clone());
        }

        *history = interpolated;
    }

    /// Gets the 7-day volume by extrapolating from 24h data.
    ///
    /// Note: DexScreener doesn't provide 7d volume directly,
    /// so we estimate based on 24h volume.
    pub fn estimate_7d_volume(volume_24h: f64) -> f64 {
        // Simple estimation: assume consistent daily volume
        volume_24h * 7.0
    }
}

impl Default for DexClient {
    fn default() -> Self {
        Self::new_with_http(crate::http::shared::fallback())
    }
}

// ============================================================================
// DexDataSource Trait Implementation
// ============================================================================

#[async_trait]
impl DexDataSource for DexClient {
    async fn get_token_price(&self, chain: &str, address: &str) -> Option<f64> {
        self.get_token_price(chain, address).await
    }

    async fn get_native_token_price(&self, chain: &str) -> Option<f64> {
        self.get_native_token_price(chain).await
    }

    async fn get_token_data(&self, chain: &str, address: &str) -> Result<DexTokenData> {
        self.get_token_data(chain, address).await
    }

    async fn search_tokens(
        &self,
        query: &str,
        chain: Option<&str>,
    ) -> Result<Vec<TokenSearchResult>> {
        self.search_tokens(query, chain).await
    }
}

/// Builds a full DexScreener token response JSON string for testing.
#[cfg(test)]
fn build_test_pair_json(chain_id: &str, base_symbol: &str, base_addr: &str, price: &str) -> String {
    format!(
        r#"{{
        "chainId":"{}","dexId":"uniswap","pairAddress":"0xpair",
        "baseToken":{{"address":"{}","name":"{}","symbol":"{}"}},
        "quoteToken":{{"address":"0xquote","name":"USDC","symbol":"USDC"}},
        "priceUsd":"{}",
        "priceChange":{{"h24":5.2,"h6":2.1,"h1":0.5,"m5":0.1}},
        "volume":{{"h24":1000000,"h6":250000,"h1":50000,"m5":5000}},
        "liquidity":{{"usd":500000,"base":100,"quote":500000}},
        "fdv":10000000,"marketCap":8000000,
        "txns":{{"h24":{{"buys":100,"sells":80}},"h6":{{"buys":20,"sells":15}},"h1":{{"buys":5,"sells":3}}}},
        "pairCreatedAt":1690000000000,
        "url":"https://dexscreener.com/ethereum/0xpair"
    }}"#,
        chain_id, base_addr, base_symbol, base_symbol, price
    )
}

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

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

    #[test]
    fn test_dex_client_uses_the_given_transport() {
        let given = crate::http::test_transport();
        let client = DexClient::new_with_http(given.clone());
        assert!(std::sync::Arc::ptr_eq(&client.http, &given));
    }

    #[test]
    fn test_chain_mapping() {
        assert_eq!(
            DexClient::map_chain_to_dexscreener("ethereum"),
            "ethereum".to_string()
        );
        assert_eq!(
            DexClient::map_chain_to_dexscreener("ETH"),
            "ethereum".to_string()
        );
        assert_eq!(
            DexClient::map_chain_to_dexscreener("bsc"),
            "bsc".to_string()
        );
        assert_eq!(
            DexClient::map_chain_to_dexscreener("BNB"),
            "bsc".to_string()
        );
        assert_eq!(
            DexClient::map_chain_to_dexscreener("polygon"),
            "polygon".to_string()
        );
        assert_eq!(
            DexClient::map_chain_to_dexscreener("solana"),
            "solana".to_string()
        );
    }

    #[test]
    fn test_estimate_7d_volume() {
        assert_eq!(DexClient::estimate_7d_volume(1_000_000.0), 7_000_000.0);
        assert_eq!(DexClient::estimate_7d_volume(0.0), 0.0);
    }

    #[test]
    fn test_generate_volume_history() {
        let now = 1700000000;
        let history = DexClient::generate_volume_history(24000.0, 6000.0, 1000.0, now);

        assert_eq!(history.len(), 24);
        assert!(history.iter().all(|v| v.volume >= 0.0));
        assert!(history.iter().all(|v| v.timestamp <= now));
    }

    #[test]
    fn test_dex_client_default() {
        let _client = DexClient::default();
        // Just verify it doesn't panic
    }

    #[test]
    fn test_interpolate_points() {
        let mut history = vec![
            PricePoint {
                timestamp: 0,
                price: 1.0,
            },
            PricePoint {
                timestamp: 100,
                price: 2.0,
            },
        ];

        DexClient::interpolate_points(&mut history, 10);

        assert!(history.len() > 2);
        // Check midpoint was added
        assert!(history.iter().any(|p| p.timestamp == 50));
    }

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

    #[tokio::test]
    async fn test_get_token_data_success() {
        let mut server = mockito::Server::new_async().await;
        let pair = build_test_pair_json("ethereum", "WETH", "0xtoken", "2500.50");
        let body = format!(r#"{{"pairs":[{}]}}"#, pair);
        let _mock = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"/latest/dex/tokens/.*".to_string()),
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(&body)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let data = client.get_token_data("ethereum", "0xtoken").await.unwrap();
        assert_eq!(data.symbol, "WETH");
        assert!((data.price_usd - 2500.50).abs() < 0.01);
        assert!(data.volume_24h > 0.0);
        assert!(data.liquidity_usd > 0.0);
        assert_eq!(data.pairs.len(), 1);
        // The pool's base reserve feeds the synthetic AMM book (#37).
        assert_eq!(data.pairs[0].liquidity_base, Some(100.0));
        assert!(data.total_buys_24h > 0);
        assert!(data.total_sells_24h > 0);
        assert!(!data.price_history.is_empty());
        assert!(!data.volume_history.is_empty());
    }

    #[tokio::test]
    async fn test_get_token_data_no_pairs() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"/latest/dex/tokens/.*".to_string()),
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"pairs":[]}"#)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let result = client.get_token_data("ethereum", "0xunknown").await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("No DEX pairs"));
    }

    #[tokio::test]
    async fn test_get_token_data_api_error() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"/latest/dex/tokens/.*".to_string()),
            )
            .with_status(500)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let result = client.get_token_data("ethereum", "0xtoken").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_get_token_data_fallback_to_all_pairs() {
        // When no chain-specific pairs found, should use all pairs
        let mut server = mockito::Server::new_async().await;
        let pair = build_test_pair_json("bsc", "TOKEN", "0xtoken", "1.00");
        let body = format!(r#"{{"pairs":[{}]}}"#, pair);
        let _mock = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"/latest/dex/tokens/.*".to_string()),
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(&body)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        // Request for ethereum but pair is on bsc → should still get data
        let data = client.get_token_data("ethereum", "0xtoken").await.unwrap();
        assert_eq!(data.symbol, "TOKEN");
    }

    #[tokio::test]
    async fn test_get_token_data_multiple_pairs() {
        let mut server = mockito::Server::new_async().await;
        let pair1 = build_test_pair_json("ethereum", "WETH", "0xtoken", "2500.00");
        let pair2 = build_test_pair_json("ethereum", "WETH", "0xtoken", "2501.00");
        let body = format!(r#"{{"pairs":[{},{}]}}"#, pair1, pair2);
        let _mock = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"/latest/dex/tokens/.*".to_string()),
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(&body)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let data = client.get_token_data("ethereum", "0xtoken").await.unwrap();
        assert_eq!(data.pairs.len(), 2);
        // Price should be liquidity-weighted average
        assert!(data.price_usd > 2499.0 && data.price_usd < 2502.0);
    }

    #[tokio::test]
    async fn test_get_token_price() {
        let mut server = mockito::Server::new_async().await;
        let pair = build_test_pair_json("ethereum", "WETH", "0xtoken", "2500.50");
        let body = format!(r#"{{"pairs":[{}]}}"#, pair);
        let _mock = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"/latest/dex/tokens/.*".to_string()),
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(&body)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let price = client.get_token_price("ethereum", "0xtoken").await;
        assert!(price.is_some());
        assert!((price.unwrap() - 2500.50).abs() < 0.01);
    }

    #[tokio::test]
    async fn test_get_token_price_not_found() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"/latest/dex/tokens/.*".to_string()),
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"pairs":null}"#)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let price = client.get_token_price("ethereum", "0xunknown").await;
        assert!(price.is_none());
    }

    #[tokio::test]
    async fn test_search_tokens_success() {
        let mut server = mockito::Server::new_async().await;
        let pair = build_test_pair_json("ethereum", "USDC", "0xusdc", "1.00");
        let body = format!(r#"{{"pairs":[{}]}}"#, pair);
        let _mock = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"/latest/dex/search.*".to_string()),
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(&body)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let results = client.search_tokens("USDC", None).await.unwrap();
        assert!(!results.is_empty());
        assert_eq!(results[0].symbol, "USDC");
    }

    #[tokio::test]
    async fn test_search_tokens_with_chain_filter() {
        let mut server = mockito::Server::new_async().await;
        let pair_eth = build_test_pair_json("ethereum", "USDC", "0xusdc_eth", "1.00");
        let pair_bsc = build_test_pair_json("bsc", "USDC", "0xusdc_bsc", "1.00");
        let body = format!(r#"{{"pairs":[{},{}]}}"#, pair_eth, pair_bsc);
        let _mock = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"/latest/dex/search.*".to_string()),
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(&body)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let results = client
            .search_tokens("USDC", Some("ethereum"))
            .await
            .unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].chain, "ethereum");
    }

    #[tokio::test]
    async fn test_search_tokens_empty() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"/latest/dex/search.*".to_string()),
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"pairs":[]}"#)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let results = client.search_tokens("XYZNONEXIST", None).await.unwrap();
        assert!(results.is_empty());
    }

    #[tokio::test]
    async fn test_search_tokens_api_error() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"/latest/dex/search.*".to_string()),
            )
            .with_status(429)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let result = client.search_tokens("USDC", None).await;
        assert!(result.is_err());
    }

    #[test]
    fn test_generate_price_history() {
        let pair_json = r#"{
            "chainId":"ethereum","dexId":"uniswap","pairAddress":"0xpair",
            "baseToken":{"address":"0xtoken","name":"Token","symbol":"TKN"},
            "quoteToken":{"address":"0xquote","name":"USDC","symbol":"USDC"},
            "priceUsd":"100.0",
            "priceChange":{"h24":10.0,"h6":5.0,"h1":1.0,"m5":0.5}
        }"#;
        let pair: DexScreenerPair = serde_json::from_str(pair_json).unwrap();
        let history = DexClient::generate_price_history(100.0, &pair, 1700000000);
        assert!(!history.is_empty());
        // Last point should be current price
        assert!(history.iter().any(|p| (p.price - 100.0).abs() < 0.001));
    }

    #[test]
    fn test_chain_mapping_all_variants() {
        // Test all known chains
        assert_eq!(DexClient::map_chain_to_dexscreener("eth"), "ethereum");
        assert_eq!(DexClient::map_chain_to_dexscreener("matic"), "polygon");
        assert_eq!(DexClient::map_chain_to_dexscreener("arb"), "arbitrum");
        assert_eq!(DexClient::map_chain_to_dexscreener("op"), "optimism");
        assert_eq!(DexClient::map_chain_to_dexscreener("base"), "base");
        assert_eq!(DexClient::map_chain_to_dexscreener("bnb"), "bsc");
        assert_eq!(DexClient::map_chain_to_dexscreener("sol"), "solana");
        assert_eq!(DexClient::map_chain_to_dexscreener("avax"), "avalanche");
        assert_eq!(DexClient::map_chain_to_dexscreener("unknown"), "unknown");
    }

    #[tokio::test]
    async fn test_get_native_token_price_ethereum() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"pairs":[{
                "chainId":"ethereum",
                "dexId":"uniswap",
                "pairAddress":"0xpair",
                "baseToken":{"address":"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","name":"WETH","symbol":"WETH"},
                "quoteToken":{"address":"0xusdt","name":"USDT","symbol":"USDT"},
                "priceUsd":"3500.00"
            }]}"#)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let price = client.get_native_token_price("ethereum").await;
        assert!(price.is_some());
        assert!((price.unwrap() - 3500.0).abs() < 0.01);
    }

    #[tokio::test]
    async fn test_get_native_token_price_tron_returns_none() {
        let client = DexClient::with_base_url("http://localhost:1");
        let price = client.get_native_token_price("tron").await;
        assert!(price.is_none());
    }

    #[tokio::test]
    async fn test_get_native_token_price_unknown_chain() {
        let client = DexClient::with_base_url("http://localhost:1");
        let price = client.get_native_token_price("unknownchain").await;
        assert!(price.is_none());
    }

    #[tokio::test]
    async fn test_search_tokens_chain_filter_ethereum_only() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"pairs":[
                {
                    "chainId":"ethereum",
                    "dexId":"uniswap",
                    "pairAddress":"0xpair1",
                    "baseToken":{"address":"0xtoken1","name":"USD Coin","symbol":"USDC"},
                    "quoteToken":{"address":"0xweth","name":"WETH","symbol":"WETH"},
                    "priceUsd":"1.00",
                    "liquidity":{"usd":5000000.0},
                    "volume":{"h24":1000000.0}
                },
                {
                    "chainId":"bsc",
                    "dexId":"pancakeswap",
                    "pairAddress":"0xpair2",
                    "baseToken":{"address":"0xtoken2","name":"Binance USD","symbol":"BUSD"},
                    "quoteToken":{"address":"0xbnb","name":"BNB","symbol":"BNB"},
                    "priceUsd":"1.00",
                    "liquidity":{"usd":2000000.0},
                    "volume":{"h24":500000.0}
                }
            ]}"#,
            )
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        // Filter to ethereum only
        let results = client.search_tokens("USD", Some("ethereum")).await.unwrap();
        assert!(!results.is_empty());
        // All results should be on ethereum
        for r in &results {
            assert_eq!(r.chain.to_lowercase(), "ethereum");
        }
    }

    #[tokio::test]
    async fn test_search_tokens_exact_match_sorts_before_partial() {
        // Exact symbol match "USDC" should sort before "syrupUSDC" even if syrupUSDC has higher liquidity
        let mut server = mockito::Server::new_async().await;
        let pair_usdc = build_test_pair_json("ethereum", "USDC", "0xusdc", "1.00");
        let pair_syrup = r#"{
            "chainId":"ethereum","dexId":"uniswap","pairAddress":"0xpair2",
            "baseToken":{"address":"0xsyrupusdc","name":"Syrup USDC","symbol":"syrupUSDC"},
            "quoteToken":{"address":"0xquote","name":"USDT","symbol":"USDT"},
            "priceUsd":"1.00",
            "priceChange":{"h24":0.0,"h6":0.0,"h1":0.0,"m5":0.0},
            "volume":{"h24":500000,"h6":125000,"h1":25000,"m5":2500},
            "liquidity":{"usd":5000000,"base":5000000,"quote":5000000},
            "fdv":null,"marketCap":null,
            "txns":{"h24":{"buys":100,"sells":80},"h6":{"buys":20,"sells":15},"h1":{"buys":5,"sells":3}},
            "pairCreatedAt":1690000000000,
            "url":"https://dexscreener.com/ethereum/0xpair2"
        }"#;
        let body = format!(r#"{{"pairs":[{},{}]}}"#, pair_usdc, pair_syrup);
        let _mock = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"/latest/dex/search.*".to_string()),
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(&body)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let results = client.search_tokens("USDC", None).await.unwrap();
        assert!(results.len() >= 2);
        // First result must be exact match (USDC), not syrupUSDC
        assert_eq!(results[0].symbol, "USDC");
        // syrupUSDC has higher liquidity but should be second
        let syrup_pos = results
            .iter()
            .position(|r| r.symbol == "syrupUSDC")
            .unwrap();
        assert!(syrup_pos > 0);
        assert!(results[syrup_pos].liquidity_usd > results[0].liquidity_usd);
    }

    #[tokio::test]
    async fn test_search_tokens_multiple_exact_matches_sort_by_liquidity() {
        // Multiple exact "USDC" matches (different chains) should sort by liquidity among themselves
        let mut server = mockito::Server::new_async().await;
        let pair_eth = r#"{
            "chainId":"ethereum","dexId":"uniswap","pairAddress":"0xpair1",
            "baseToken":{"address":"0xusdc_eth","name":"USD Coin","symbol":"USDC"},
            "quoteToken":{"address":"0xweth","name":"WETH","symbol":"WETH"},
            "priceUsd":"1.00",
            "priceChange":{"h24":0.0,"h6":0.0,"h1":0.0,"m5":0.0},
            "volume":{"h24":1000000,"h6":250000,"h1":50000,"m5":5000},
            "liquidity":{"usd":1000000,"base":1000000,"quote":1000000},
            "fdv":null,"marketCap":null,
            "txns":{"h24":{"buys":100,"sells":80},"h6":{"buys":20,"sells":15},"h1":{"buys":5,"sells":3}},
            "pairCreatedAt":1690000000000,
            "url":"https://dexscreener.com/ethereum/0xpair1"
        }"#;
        let pair_bsc = r#"{
            "chainId":"bsc","dexId":"pancakeswap","pairAddress":"0xpair2",
            "baseToken":{"address":"0xusdc_bsc","name":"USD Coin","symbol":"USDC"},
            "quoteToken":{"address":"0xbnb","name":"BNB","symbol":"BNB"},
            "priceUsd":"1.00",
            "priceChange":{"h24":0.0,"h6":0.0,"h1":0.0,"m5":0.0},
            "volume":{"h24":2000000,"h6":500000,"h1":100000,"m5":10000},
            "liquidity":{"usd":3000000,"base":3000000,"quote":3000000},
            "fdv":null,"marketCap":null,
            "txns":{"h24":{"buys":200,"sells":150},"h6":{"buys":50,"sells":30},"h1":{"buys":10,"sells":6}},
            "pairCreatedAt":1690000000000,
            "url":"https://dexscreener.com/bsc/0xpair2"
        }"#;
        let body = format!(r#"{{"pairs":[{},{}]}}"#, pair_eth, pair_bsc);
        let _mock = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"/latest/dex/search.*".to_string()),
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(&body)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let results = client.search_tokens("USDC", None).await.unwrap();
        assert_eq!(results.len(), 2);
        // Both exact matches - should sort by liquidity descending
        assert_eq!(results[0].symbol, "USDC");
        assert_eq!(results[1].symbol, "USDC");
        assert!(results[0].liquidity_usd >= results[1].liquidity_usd);
        assert_eq!(results[0].chain, "bsc"); // BSC has 3M liquidity, should be first
        assert_eq!(results[1].chain, "ethereum"); // Ethereum has 1M, second
    }

    #[tokio::test]
    async fn test_search_tokens_aggregates_volume_and_liquidity() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"pairs":[
                {
                    "chainId":"ethereum",
                    "dexId":"uniswap",
                    "pairAddress":"0xpair1",
                    "baseToken":{"address":"0xSameToken","name":"Test Token","symbol":"TEST"},
                    "quoteToken":{"address":"0xweth","name":"WETH","symbol":"WETH"},
                    "priceUsd":"10.00",
                    "liquidity":{"usd":1000000.0},
                    "volume":{"h24":100000.0}
                },
                {
                    "chainId":"ethereum",
                    "dexId":"sushiswap",
                    "pairAddress":"0xpair2",
                    "baseToken":{"address":"0xSameToken","name":"Test Token","symbol":"TEST"},
                    "quoteToken":{"address":"0xusdc","name":"USDC","symbol":"USDC"},
                    "priceUsd":"10.05",
                    "liquidity":{"usd":500000.0},
                    "volume":{"h24":50000.0}
                }
            ]}"#,
            )
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let results = client.search_tokens("TEST", None).await.unwrap();
        assert_eq!(results.len(), 1); // Same token aggregated
        // Volume and liquidity should be summed
        assert!(results[0].volume_24h > 100000.0);
        assert!(results[0].liquidity_usd > 1000000.0);
    }

    #[tokio::test]
    async fn test_dex_data_source_trait_methods() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"pairs":[{
                "chainId":"ethereum",
                "dexId":"uniswap",
                "pairAddress":"0xpair",
                "baseToken":{"address":"0xtoken","name":"Token","symbol":"TKN"},
                "quoteToken":{"address":"0xquote","name":"USDC","symbol":"USDC"},
                "priceUsd":"50.0",
                "liquidity":{"usd":1000000.0},
                "volume":{"h24":100000.0}
            }]}"#,
            )
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        // Test through DexDataSource trait
        let trait_client: &dyn DexDataSource = &client;
        let price = trait_client.get_token_price("ethereum", "0xtoken").await;
        assert!(price.is_some());
    }

    #[tokio::test]
    async fn test_dex_data_source_trait_get_native_token_price() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"pairs":[{
                "chainId":"ethereum",
                "dexId":"uniswap",
                "pairAddress":"0xpair",
                "baseToken":{"address":"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","name":"WETH","symbol":"WETH"},
                "quoteToken":{"address":"0xquote","name":"USDC","symbol":"USDC"},
                "priceUsd":"3500.0",
                "liquidity":{"usd":10000000.0},
                "volume":{"h24":5000000.0}
            }]}"#,
            )
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let trait_client: &dyn DexDataSource = &client;
        let price = trait_client.get_native_token_price("ethereum").await;
        assert!(price.is_some());
    }

    #[tokio::test]
    async fn test_dex_data_source_trait_get_token_data() {
        let mut server = mockito::Server::new_async().await;
        let pair_json = build_test_pair_json("ethereum", "TKN", "0xtoken", "50.0");
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(format!(r#"{{"pairs":[{}]}}"#, pair_json))
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let trait_client: &dyn DexDataSource = &client;
        let data = trait_client.get_token_data("ethereum", "0xtoken").await;
        assert!(data.is_ok());
    }

    #[tokio::test]
    async fn test_dex_data_source_trait_search_tokens() {
        let mut server = mockito::Server::new_async().await;
        let pair_json = build_test_pair_json("ethereum", "TKN", "0xtoken", "50.0");
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(format!(r#"{{"pairs":[{}]}}"#, pair_json))
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let trait_client: &dyn DexDataSource = &client;
        let results = trait_client.search_tokens("TKN", None).await;
        assert!(results.is_ok());
    }

    #[tokio::test]
    async fn test_get_token_data_quote_token() {
        let mut server = mockito::Server::new_async().await;
        // Token is the quote token, not the base
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"pairs":[{
                "chainId":"ethereum","dexId":"uniswap","pairAddress":"0xpair",
                "baseToken":{"address":"0xother","name":"Other","symbol":"OTH"},
                "quoteToken":{"address":"0xmytoken","name":"MyToken","symbol":"MTK"},
                "priceUsd":"25.0",
                "priceChange":{"h24":1.0,"h6":0.5,"h1":0.2,"m5":0.05},
                "volume":{"h24":500000,"h6":100000,"h1":20000,"m5":2000},
                "liquidity":{"usd":0,"base":0,"quote":0},
                "txns":{"h24":{"buys":50,"sells":40},"h6":{"buys":10,"sells":8},"h1":{"buys":2,"sells":1}},
                "pairCreatedAt":1690000000000,
                "url":"https://dexscreener.com/ethereum/0xpair"
            }]}"#,
            )
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let data = client
            .get_token_data("ethereum", "0xmytoken")
            .await
            .unwrap();
        // Should identify the quote token
        assert_eq!(data.symbol, "MTK");
        assert_eq!(data.name, "MyToken");
        // Zero liquidity fallback for price: should use priceUsd from first pair
        assert!(data.price_usd > 0.0);
    }

    #[tokio::test]
    async fn test_get_token_data_with_socials() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"pairs":[{
                "chainId":"ethereum","dexId":"uniswap","pairAddress":"0xpair",
                "baseToken":{"address":"0xtoken","name":"Token","symbol":"TKN"},
                "quoteToken":{"address":"0xquote","name":"USDC","symbol":"USDC"},
                "priceUsd":"50.0",
                "priceChange":{"h24":5.0,"h6":2.0,"h1":1.0,"m5":0.1},
                "volume":{"h24":1000000,"h6":250000,"h1":50000,"m5":5000},
                "liquidity":{"usd":1000000,"base":100,"quote":1000000},
                "txns":{"h24":{"buys":100,"sells":80},"h6":{"buys":20,"sells":15},"h1":{"buys":5,"sells":3}},
                "pairCreatedAt":1690000000000,
                "url":"https://dexscreener.com/ethereum/0xpair",
                "info":{
                    "imageUrl":"https://example.com/logo.png",
                    "websites":[{"url":"https://example.com"}],
                    "socials":[
                        {"type":"twitter","url":"https://twitter.com/token"},
                        {"type":"telegram","url":"https://t.me/token"}
                    ]
                }
            }]}"#,
            )
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let data = client.get_token_data("ethereum", "0xtoken").await.unwrap();
        assert_eq!(data.symbol, "TKN");
        assert!(data.image_url.is_some());
        assert!(!data.websites.is_empty());
        assert!(!data.socials.is_empty());
        assert_eq!(data.socials[0].platform, "twitter");
    }

    #[tokio::test]
    async fn test_search_tokens_quote_match_and_updates() {
        let mut server = mockito::Server::new_async().await;
        // Token matches as quote, not base
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"pairs":[
                {
                    "chainId":"ethereum","dexId":"uniswap","pairAddress":"0xpair1",
                    "baseToken":{"address":"0xother","name":"Other","symbol":"OTH"},
                    "quoteToken":{"address":"0xmytk","name":"MySearch","symbol":"MSR"},
                    "liquidity":{"usd":500000.0},
                    "volume":{"h24":100000.0},
                    "marketCap":5000000
                },
                {
                    "chainId":"ethereum","dexId":"sushi","pairAddress":"0xpair2",
                    "baseToken":{"address":"0xmytk","name":"MySearch","symbol":"MSR"},
                    "quoteToken":{"address":"0xweth","name":"WETH","symbol":"WETH"},
                    "priceUsd":"10.5",
                    "liquidity":{"usd":800000.0},
                    "volume":{"h24":200000.0}
                }
            ]}"#,
            )
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let results = client.search_tokens("MySearch", None).await.unwrap();
        assert_eq!(results.len(), 1); // Same token aggregated
        assert_eq!(results[0].symbol, "MSR");
        // Volume should be aggregated
        assert!(results[0].volume_24h >= 300000.0);
        // Liquidity should be aggregated
        assert!(results[0].liquidity_usd >= 1300000.0);
        // Price should be set from the second pair
        assert!(results[0].price_usd.is_some());
        // Market cap should be carried from first pair
        assert!(results[0].market_cap.is_some());
    }

    #[test]
    fn test_interpolate_points_midpoint() {
        let mut history = vec![
            PricePoint {
                timestamp: 1000,
                price: 10.0,
            },
            PricePoint {
                timestamp: 2000,
                price: 20.0,
            },
        ];
        // Should not interpolate if already enough points
        DexClient::interpolate_points(&mut history, 2);
        assert_eq!(history.len(), 2);

        // Should add midpoints
        DexClient::interpolate_points(&mut history, 5);
        assert!(history.len() > 2);
        // Check that a midpoint was added
        let midpoints: Vec<_> = history.iter().filter(|p| p.timestamp == 1500).collect();
        assert!(!midpoints.is_empty());
        assert!((midpoints[0].price - 15.0).abs() < 0.01);
    }

    fn discover_token_json() -> &'static str {
        r#"[
            {"chainId":"ethereum","tokenAddress":"0xabc","url":"https://dexscreener.com/ethereum/0xabc","description":"Test token","links":[{"label":"Twitter","type":"twitter","url":"https://twitter.com/test"}]},
            {"chainId":"solana","tokenAddress":"So11111111111111111111111111111111111111112","url":"https://dexscreener.com/solana/So11","links":[]}
        ]"#
    }

    #[tokio::test]
    async fn test_get_token_profiles() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/token-profiles/latest/v1")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(discover_token_json())
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let tokens = client.get_token_profiles().await.unwrap();
        assert_eq!(tokens.len(), 2);
        assert_eq!(tokens[0].chain_id, "ethereum");
        assert_eq!(tokens[0].token_address, "0xabc");
        assert_eq!(tokens[0].description.as_deref(), Some("Test token"));
        assert_eq!(tokens[0].links.len(), 1);
        assert_eq!(tokens[1].chain_id, "solana");
    }

    #[tokio::test]
    async fn test_get_token_boosts() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/token-boosts/latest/v1")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(discover_token_json())
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let tokens = client.get_token_boosts().await.unwrap();
        assert_eq!(tokens.len(), 2);
    }

    #[tokio::test]
    async fn test_get_token_boosts_top() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/token-boosts/top/v1")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(discover_token_json())
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let tokens = client.get_token_boosts_top().await.unwrap();
        assert_eq!(tokens.len(), 2);
    }

    #[tokio::test]
    async fn test_fetch_discover_tokens_api_error() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(500)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let result = client.get_token_profiles().await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_fetch_discover_tokens_empty_array() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/token-profiles/latest/v1")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body("[]")
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let tokens = client.get_token_profiles().await.unwrap();
        assert!(tokens.is_empty());
    }

    #[tokio::test]
    async fn test_fetch_discover_tokens_filters_invalid_entries() {
        // Entries without tokenAddress are filtered out
        let body = r#"[{"chainId":"ethereum","url":"https://example.com"},{"chainId":"solana","tokenAddress":"0xvalid","url":"https://dexscreener.com/solana/0xvalid"}]"#;
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/token-profiles/latest/v1")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(body)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let tokens = client.get_token_profiles().await.unwrap();
        assert_eq!(tokens.len(), 1);
        assert_eq!(tokens[0].token_address, "0xvalid");
    }

    // =================================================================
    // Token search sorting: exact symbol matches first
    // =================================================================

    #[tokio::test]
    async fn test_search_tokens_exact_match_sorted_first() {
        // Set up a mock that returns two tokens: "syrupUSDC" with higher liquidity
        // and "USDC" with lower liquidity. The exact match "USDC" should come first.
        let pair_syrup = build_test_pair_json("ethereum", "syrupUSDC", "0xsyrup", "1.0");
        let pair_usdc = build_test_pair_json("ethereum", "USDC", "0xusdc", "1.0");

        let body = format!(
            r#"{{"schemaVersion":"1.0.0","pairs":[{},{}]}}"#,
            pair_syrup, pair_usdc
        );

        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/latest/dex/search")
            .match_query(mockito::Matcher::UrlEncoded("q".into(), "USDC".into()))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(&body)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let results = client.search_tokens("USDC", None).await.unwrap();

        assert!(
            results.len() >= 2,
            "expected at least 2 results, got {}",
            results.len()
        );
        // First result should be exact match "USDC", not "syrupUSDC"
        assert_eq!(
            results[0].symbol, "USDC",
            "exact symbol match should be sorted first"
        );
        assert_eq!(results[1].symbol, "syrupUSDC");
    }

    #[tokio::test]
    async fn test_search_tokens_no_results() {
        let body = r#"{"schemaVersion":"1.0.0","pairs":[]}"#;
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/latest/dex/search")
            .match_query(mockito::Matcher::UrlEncoded("q".into(), "ZZZZZ".into()))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(body)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let results = client.search_tokens("ZZZZZ", None).await.unwrap();
        assert!(results.is_empty());
    }

    #[tokio::test]
    async fn test_search_tokens_api_error_500() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/latest/dex/search")
            .match_query(mockito::Matcher::UrlEncoded("q".into(), "ERR".into()))
            .with_status(500)
            .create_async()
            .await;

        let client = DexClient::with_base_url(&server.url());
        let result = client.search_tokens("ERR", None).await;
        assert!(result.is_err());
    }
}