fynd-rpc-types 0.46.0

Shared DTO types for the Fynd RPC API (request/response wire format)
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
#![deny(missing_docs)]
//! Wire-format types for the [Fynd](https://fynd.xyz) RPC HTTP API.
//!
//! This crate contains only the serialisation types shared between the Fynd RPC server
//! (`fynd-rpc`) and its clients (`fynd-client`). It has no server-side infrastructure
//! dependencies (no actix-web, no server logic).
//!
//! For documentation and API reference see **<https://docs.fynd.xyz/>**.
//!
//! ## Features
//!
//! - **`openapi`** — derives `utoipa::ToSchema` on all types for OpenAPI spec generation.
//! - **`core`** — enables `Into` conversions between wire DTOs and `fynd-core` domain types.

use num_bigint::BigUint;
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, DisplayFromStr};
use uuid::Uuid;

// ── Primitive byte types ──────────────────────────────────────────────────────
//
// Wire-format: `"0x{lowercase hex}"` on serialize; accepts with or without the
// `0x` prefix on deserialize. Replaces the unconditional tycho-simulation dep
// so crates that don't need the `core` feature (e.g. fynd-client) compile
// without the full simulation stack.

mod hex_bytes_serde {
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(x: &bytes::Bytes, s: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        s.serialize_str(&format!("0x{}", hex::encode(x.as_ref())))
    }

    pub fn deserialize<'de, D>(d: D) -> Result<bytes::Bytes, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(d)?;
        let stripped = s.strip_prefix("0x").unwrap_or(&s);
        hex::decode(stripped)
            .map(bytes::Bytes::from)
            .map_err(serde::de::Error::custom)
    }
}

/// A byte sequence that serializes as `"0x{lowercase hex}"` in JSON.
///
/// Deserialization accepts hex strings with or without the `0x` prefix.
///
/// The inner `bytes::Bytes` is `pub` to allow zero-copy conversions with other
/// crates that also wrap `bytes::Bytes` (e.g. the `core` feature bridge to tycho).
#[derive(Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Bytes(#[serde(with = "hex_bytes_serde")] pub bytes::Bytes);

impl Bytes {
    /// Returns the number of bytes.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns `true` if the byte sequence is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl std::fmt::Debug for Bytes {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Bytes(0x{})", hex::encode(self.0.as_ref()))
    }
}

impl AsRef<[u8]> for Bytes {
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}

impl From<&[u8]> for Bytes {
    fn from(src: &[u8]) -> Self {
        Self(bytes::Bytes::copy_from_slice(src))
    }
}

impl From<Vec<u8>> for Bytes {
    fn from(src: Vec<u8>) -> Self {
        Self(src.into())
    }
}

impl From<bytes::Bytes> for Bytes {
    fn from(src: bytes::Bytes) -> Self {
        Self(src)
    }
}

impl<const N: usize> From<[u8; N]> for Bytes {
    fn from(src: [u8; N]) -> Self {
        Self(bytes::Bytes::copy_from_slice(&src))
    }
}

/// An EVM address — 20 bytes, same wire format as `Bytes`.
pub type Address = Bytes;

// ============================================================================
// REQUEST TYPES
// ============================================================================

/// Request to solve one or more swap orders.
#[must_use]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct QuoteRequest {
    /// Orders to solve.
    orders: Vec<Order>,
    /// Optional solving parameters that apply to all orders.
    #[serde(default)]
    options: QuoteOptions,
}

impl QuoteRequest {
    /// Create a new quote request for the given orders with default options.
    pub fn new(orders: Vec<Order>) -> Self {
        Self { orders, options: QuoteOptions::default() }
    }

    /// Override the solving options.
    pub fn with_options(mut self, options: QuoteOptions) -> Self {
        self.options = options;
        self
    }

    /// Orders to solve.
    pub fn orders(&self) -> &[Order] {
        &self.orders
    }

    /// Solving options.
    pub fn options(&self) -> &QuoteOptions {
        &self.options
    }
}

/// Options to customize the solving behavior.
#[must_use]
#[serde_as]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct QuoteOptions {
    /// Timeout in milliseconds. If `None`, uses server default.
    #[cfg_attr(feature = "openapi", schema(example = 2000))]
    timeout_ms: Option<u64>,
    /// Minimum number of solver responses to wait for before returning.
    /// If `None` or `0`, waits for all solvers to respond (or timeout).
    ///
    /// Use the `/health` endpoint to check `num_solver_pools` before setting this value.
    /// Values exceeding the number of active solver pools are clamped internally.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    min_responses: Option<usize>,
    /// Maximum gas cost allowed for a solution. Quotes exceeding this are filtered out.
    #[serde_as(as = "Option<DisplayFromStr>")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<String>, example = "500000"))]
    max_gas: Option<BigUint>,
    /// Options during encoding. If None, quote will be returned without calldata.
    encoding_options: Option<EncodingOptions>,
    /// Per-request price guard overrides. If `None`, uses server defaults.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    price_guard: Option<PriceGuardConfig>,
}

impl QuoteOptions {
    /// Set the timeout in milliseconds.
    pub fn with_timeout_ms(mut self, ms: u64) -> Self {
        self.timeout_ms = Some(ms);
        self
    }

    /// Set the minimum number of solver responses to wait for.
    pub fn with_min_responses(mut self, n: usize) -> Self {
        self.min_responses = Some(n);
        self
    }

    /// Set the maximum gas cost allowed for a solution.
    pub fn with_max_gas(mut self, gas: BigUint) -> Self {
        self.max_gas = Some(gas);
        self
    }

    /// Set the encoding options (required for calldata to be returned).
    pub fn with_encoding_options(mut self, opts: EncodingOptions) -> Self {
        self.encoding_options = Some(opts);
        self
    }

    /// Timeout in milliseconds, if set.
    pub fn timeout_ms(&self) -> Option<u64> {
        self.timeout_ms
    }

    /// Minimum solver responses to await, if set.
    pub fn min_responses(&self) -> Option<usize> {
        self.min_responses
    }

    /// Maximum allowed gas cost, if set.
    pub fn max_gas(&self) -> Option<&BigUint> {
        self.max_gas.as_ref()
    }

    /// Encoding options, if set.
    pub fn encoding_options(&self) -> Option<&EncodingOptions> {
        self.encoding_options.as_ref()
    }

    /// Set per-request price guard overrides.
    pub fn with_price_guard(mut self, config: PriceGuardConfig) -> Self {
        self.price_guard = Some(config);
        self
    }

    /// Per-request price guard config, if set.
    pub fn price_guard(&self) -> Option<&PriceGuardConfig> {
        self.price_guard.as_ref()
    }
}

/// Per-request overrides for price guard validation.
///
/// All fields are optional. When `None`, the server's configured defaults are used.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct PriceGuardConfig {
    /// Maximum allowed deviation when `amount_out < expected`, in basis points.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = 300))]
    lower_tolerance_bps: Option<u32>,
    /// Maximum allowed deviation when `amount_out >= expected`, in basis points.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = 10000))]
    upper_tolerance_bps: Option<u32>,
    /// Whether to let solutions pass when no provider can return a price.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    allow_on_provider_error: Option<bool>,
    /// Whether to let solutions pass when no provider returns price for token pair.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    allow_on_token_price_not_found: Option<bool>,
    /// Whether price guard validation is enabled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    enabled: Option<bool>,
}

impl PriceGuardConfig {
    /// Set the lower tolerance in basis points.
    pub fn with_lower_tolerance_bps(mut self, bps: u32) -> Self {
        self.lower_tolerance_bps = Some(bps);
        self
    }

    /// Set the upper tolerance in basis points.
    pub fn with_upper_tolerance_bps(mut self, bps: u32) -> Self {
        self.upper_tolerance_bps = Some(bps);
        self
    }

    /// Set whether to allow solutions when providers error.
    pub fn with_allow_on_provider_error(mut self, allow: bool) -> Self {
        self.allow_on_provider_error = Some(allow);
        self
    }

    /// Set whether to allow solutions when no provider returns price for token pair.
    pub fn with_allow_on_token_price_not_found(mut self, allow: bool) -> Self {
        self.allow_on_token_price_not_found = Some(allow);
        self
    }

    /// Set whether price guard validation is enabled.
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = Some(enabled);
        self
    }

    /// Lower tolerance in basis points, if set.
    pub fn lower_tolerance_bps(&self) -> Option<u32> {
        self.lower_tolerance_bps
    }

    /// Upper tolerance in basis points, if set.
    pub fn upper_tolerance_bps(&self) -> Option<u32> {
        self.upper_tolerance_bps
    }

    /// Whether to allow on provider error, if set.
    pub fn allow_on_provider_error(&self) -> Option<bool> {
        self.allow_on_provider_error
    }

    /// Whether to allow on token price not found, if set.
    pub fn allow_on_token_price_not_found(&self) -> Option<bool> {
        self.allow_on_token_price_not_found
    }

    /// Whether price guard is enabled, if set.
    pub fn enabled(&self) -> Option<bool> {
        self.enabled
    }
}

/// Token transfer method for moving funds into Tycho execution.
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum UserTransferType {
    /// Use Permit2 for token transfer. Requires `permit` and `signature`.
    TransferFromPermit2,
    /// Use standard ERC-20 approval and `transferFrom`. Default.
    #[default]
    TransferFrom,
    /// Use funds from the Tycho Router vault (no transfer performed).
    UseVaultsFunds,
}

/// Client fee configuration for the Tycho Router.
///
/// When provided, the router charges a client fee on the swap output. The `signature`
/// must be an EIP-712 signature by the `receiver` over the `ClientFee` typed data.
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct ClientFeeParams {
    /// Fee in basis points (0–10,000). 100 = 1%.
    #[cfg_attr(feature = "openapi", schema(example = 100))]
    bps: u16,
    /// Address that receives the fee (also the required EIP-712 signer).
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, example = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045")
    )]
    receiver: Bytes,
    /// Maximum subsidy from the client's vault balance.
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "0"))]
    max_contribution: BigUint,
    /// Unix timestamp after which the signature is invalid.
    #[cfg_attr(feature = "openapi", schema(example = 1893456000))]
    deadline: u64,
    /// 65-byte EIP-712 ECDSA signature by `receiver` (hex-encoded).
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "0xabcd..."))]
    signature: Bytes,
}

impl ClientFeeParams {
    /// Create new client fee params.
    pub fn new(
        bps: u16,
        receiver: Bytes,
        max_contribution: BigUint,
        deadline: u64,
        signature: Bytes,
    ) -> Self {
        Self { bps, receiver, max_contribution, deadline, signature }
    }

    /// Fee in basis points.
    pub fn bps(&self) -> u16 {
        self.bps
    }

    /// Address that receives the fee.
    pub fn receiver(&self) -> &Bytes {
        &self.receiver
    }

    /// Maximum subsidy from client vault.
    pub fn max_contribution(&self) -> &BigUint {
        &self.max_contribution
    }

    /// Signature deadline timestamp.
    pub fn deadline(&self) -> u64 {
        self.deadline
    }

    /// EIP-712 signature by the receiver.
    pub fn signature(&self) -> &Bytes {
        &self.signature
    }
}

/// Breakdown of fees applied to the swap output by the on-chain FeeCalculator.
///
/// All amounts are absolute values in output token units.
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct FeeBreakdown {
    /// Router protocol fee (fee on output + router's share of client fee).
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "350000"))]
    router_fee: BigUint,
    /// Client's portion of the fee (after the router takes its share).
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "2800000"))]
    client_fee: BigUint,
    /// Maximum slippage: (amount_out - router_fee - client_fee) * slippage.
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "3496850"))]
    max_slippage: BigUint,
    /// Minimum amount the user receives on-chain.
    /// Equal to amount_out - router_fee - client_fee - max_slippage.
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "3493353150"))]
    min_amount_received: BigUint,
}

impl FeeBreakdown {
    /// Router protocol fee amount.
    pub fn router_fee(&self) -> &BigUint {
        &self.router_fee
    }

    /// Client fee amount.
    pub fn client_fee(&self) -> &BigUint {
        &self.client_fee
    }

    /// Maximum slippage amount.
    pub fn max_slippage(&self) -> &BigUint {
        &self.max_slippage
    }

    /// Minimum amount the user receives on-chain.
    pub fn min_amount_received(&self) -> &BigUint {
        &self.min_amount_received
    }
}

/// Options to customize the encoding behavior.
#[must_use]
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct EncodingOptions {
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(example = "0.001"))]
    slippage: f64,
    /// Token transfer method. Defaults to `transfer_from`.
    #[serde(default)]
    transfer_type: UserTransferType,
    /// Permit2 single-token authorization. Required when using `transfer_from_permit2`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    permit: Option<PermitSingle>,
    /// Permit2 signature (65 bytes, hex-encoded). Required when `permit` is set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<String>, example = "0xabcd..."))]
    permit2_signature: Option<Bytes>,
    /// Client fee configuration. When absent, no fee is charged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    client_fee_params: Option<ClientFeeParams>,
}

impl EncodingOptions {
    /// Create encoding options with the given slippage and default transfer type.
    pub fn new(slippage: f64) -> Self {
        Self {
            slippage,
            transfer_type: UserTransferType::default(),
            permit: None,
            permit2_signature: None,
            client_fee_params: None,
        }
    }

    /// Override the token transfer method.
    pub fn with_transfer_type(mut self, t: UserTransferType) -> Self {
        self.transfer_type = t;
        self
    }

    /// Set the Permit2 single-token authorization and its signature.
    pub fn with_permit2(mut self, permit: PermitSingle, sig: Bytes) -> Self {
        self.permit = Some(permit);
        self.permit2_signature = Some(sig);
        self
    }

    /// Slippage tolerance (e.g. `0.001` = 0.1%).
    pub fn slippage(&self) -> f64 {
        self.slippage
    }

    /// Token transfer method.
    pub fn transfer_type(&self) -> &UserTransferType {
        &self.transfer_type
    }

    /// Permit2 single-token authorization, if set.
    pub fn permit(&self) -> Option<&PermitSingle> {
        self.permit.as_ref()
    }

    /// Permit2 signature, if set.
    pub fn permit2_signature(&self) -> Option<&Bytes> {
        self.permit2_signature.as_ref()
    }

    /// Set the client fee params.
    pub fn with_client_fee_params(mut self, params: ClientFeeParams) -> Self {
        self.client_fee_params = Some(params);
        self
    }

    /// Client fee params, if set.
    pub fn client_fee_params(&self) -> Option<&ClientFeeParams> {
        self.client_fee_params.as_ref()
    }
}

/// A single permit for permit2 token transfer authorization.
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct PermitSingle {
    /// The permit details (token, amount, expiration, nonce).
    details: PermitDetails,
    /// Address authorized to spend the tokens (typically the router).
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"))]
    spender: Bytes,
    /// Deadline timestamp for the permit signature.
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "1893456000"))]
    sig_deadline: BigUint,
}

impl PermitSingle {
    /// Create a new permit with the given details, spender, and signature deadline.
    pub fn new(details: PermitDetails, spender: Bytes, sig_deadline: BigUint) -> Self {
        Self { details, spender, sig_deadline }
    }

    /// Permit details (token, amount, expiration, nonce).
    pub fn details(&self) -> &PermitDetails {
        &self.details
    }

    /// Address authorized to spend the tokens.
    pub fn spender(&self) -> &Bytes {
        &self.spender
    }

    /// Signature deadline timestamp.
    pub fn sig_deadline(&self) -> &BigUint {
        &self.sig_deadline
    }
}

/// Details for a permit2 single-token permit.
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct PermitDetails {
    /// Token address for which the permit is granted.
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"))]
    token: Bytes,
    /// Amount of tokens approved.
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "1000000000000000000"))]
    amount: BigUint,
    /// Expiration timestamp for the permit.
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "1893456000"))]
    expiration: BigUint,
    /// Nonce to prevent replay attacks.
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "0"))]
    nonce: BigUint,
}

impl PermitDetails {
    /// Create permit details with the given token, amount, expiration, and nonce.
    pub fn new(token: Bytes, amount: BigUint, expiration: BigUint, nonce: BigUint) -> Self {
        Self { token, amount, expiration, nonce }
    }

    /// Token address for which the permit is granted.
    pub fn token(&self) -> &Bytes {
        &self.token
    }

    /// Amount of tokens approved.
    pub fn amount(&self) -> &BigUint {
        &self.amount
    }

    /// Expiration timestamp for the permit.
    pub fn expiration(&self) -> &BigUint {
        &self.expiration
    }

    /// Nonce to prevent replay attacks.
    pub fn nonce(&self) -> &BigUint {
        &self.nonce
    }
}

// ============================================================================
// RESPONSE TYPES
// ============================================================================

/// Complete solution for a [`QuoteRequest`].
///
/// Contains a solution for each order in the request, along with aggregate
/// gas estimates and timing information.
#[must_use]
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct Quote {
    /// Quotes for each order, in the same order as the request.
    orders: Vec<OrderQuote>,
    /// Total estimated gas for executing all swaps (as decimal string).
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "150000"))]
    total_gas_estimate: BigUint,
    /// Time taken to compute this solution, in milliseconds.
    #[cfg_attr(feature = "openapi", schema(example = 12))]
    solve_time_ms: u64,
}

impl Quote {
    /// Create a new quote.
    pub fn new(orders: Vec<OrderQuote>, total_gas_estimate: BigUint, solve_time_ms: u64) -> Self {
        Self { orders, total_gas_estimate, solve_time_ms }
    }

    /// Quotes for each order.
    pub fn orders(&self) -> &[OrderQuote] {
        &self.orders
    }

    /// Consume this quote and return the order quotes.
    pub fn into_orders(self) -> Vec<OrderQuote> {
        self.orders
    }

    /// Total estimated gas for executing all swaps.
    pub fn total_gas_estimate(&self) -> &BigUint {
        &self.total_gas_estimate
    }

    /// Time taken to compute this solution, in milliseconds.
    pub fn solve_time_ms(&self) -> u64 {
        self.solve_time_ms
    }
}

/// A single swap order to be solved.
///
/// An order specifies an intent to swap one token for another.
#[must_use]
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct Order {
    /// Unique identifier for this order.
    ///
    /// Auto-generated by the API.
    #[serde(default = "generate_order_id", skip_deserializing)]
    id: String,
    /// Input token address (the token being sold).
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, example = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2")
    )]
    token_in: Address,
    /// Output token address (the token being bought).
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, example = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")
    )]
    token_out: Address,
    /// Amount to swap, interpreted according to `side` (in token units, as decimal string).
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, example = "1000000000000000000")
    )]
    amount: BigUint,
    /// Whether this is a sell (exact input) or buy (exact output) order.
    side: OrderSide,
    /// Address that will send the input tokens.
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, example = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045")
    )]
    sender: Address,
    /// Address that will receive the output tokens.
    ///
    /// Defaults to `sender` if not specified.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = Option<String>, example = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045")
    )]
    receiver: Option<Address>,
}

impl Order {
    /// Create a new order. The `id` is left empty and filled by the server on receipt.
    pub fn new(
        token_in: Address,
        token_out: Address,
        amount: BigUint,
        side: OrderSide,
        sender: Address,
    ) -> Self {
        Self { id: String::new(), token_in, token_out, amount, side, sender, receiver: None }
    }

    /// Override the order ID (used in tests and internal conversions).
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.id = id.into();
        self
    }

    /// Set the receiver address (defaults to sender if not set).
    pub fn with_receiver(mut self, receiver: Address) -> Self {
        self.receiver = Some(receiver);
        self
    }

    /// Order ID.
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Input token address.
    pub fn token_in(&self) -> &Address {
        &self.token_in
    }

    /// Output token address.
    pub fn token_out(&self) -> &Address {
        &self.token_out
    }

    /// Amount to swap.
    pub fn amount(&self) -> &BigUint {
        &self.amount
    }

    /// Order side (sell or buy).
    pub fn side(&self) -> OrderSide {
        self.side
    }

    /// Sender address.
    pub fn sender(&self) -> &Address {
        &self.sender
    }

    /// Receiver address, if set.
    pub fn receiver(&self) -> Option<&Address> {
        self.receiver.as_ref()
    }
}

/// Specifies the side of an order: sell (exact input) or buy (exact output).
///
/// Currently only `Sell` is supported. `Buy` will be added in a future version.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum OrderSide {
    /// Sell exactly the specified amount of the input token.
    Sell,
}

/// Quote for a single [`Order`].
///
/// Contains the route to execute (if found), along with expected amounts,
/// gas estimates, and status information.
#[must_use]
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct OrderQuote {
    /// ID of the order this solution corresponds to.
    #[cfg_attr(feature = "openapi", schema(example = "f47ac10b-58cc-4372-a567-0e02b2c3d479"))]
    order_id: String,
    /// Status indicating whether a route was found.
    status: QuoteStatus,
    /// The route to execute, if a valid route was found.
    #[serde(skip_serializing_if = "Option::is_none")]
    route: Option<Route>,
    /// Amount of input token (in token units, as decimal string).
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, example = "1000000000000000000")
    )]
    amount_in: BigUint,
    /// Amount of output token (in token units, as decimal string).
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "3500000000"))]
    amount_out: BigUint,
    /// Estimated gas cost for executing this route (as decimal string).
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "150000"))]
    gas_estimate: BigUint,
    /// Price impact in basis points (1 bip = 0.01%).
    #[serde(skip_serializing_if = "Option::is_none")]
    price_impact_bps: Option<i32>,
    /// Amount out minus gas cost in output token terms.
    /// Used by WorkerPoolRouter to compare solutions from different solvers.
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "3498000000"))]
    amount_out_net_gas: BigUint,
    /// Block at which this quote was computed.
    block: BlockInfo,
    /// Effective gas price (in wei) at the time the route was computed.
    #[serde_as(as = "Option<DisplayFromStr>")]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<String>, example = "20000000000"))]
    gas_price: Option<BigUint>,
    /// An encoded EVM transaction ready to be submitted on-chain.
    transaction: Option<Transaction>,
    /// Fee breakdown (populated when encoding options are provided).
    #[serde(skip_serializing_if = "Option::is_none")]
    fee_breakdown: Option<FeeBreakdown>,
}

impl OrderQuote {
    /// Order ID this solution corresponds to.
    pub fn order_id(&self) -> &str {
        &self.order_id
    }

    /// Status indicating whether a route was found.
    pub fn status(&self) -> QuoteStatus {
        self.status
    }

    /// The route to execute, if a valid route was found.
    pub fn route(&self) -> Option<&Route> {
        self.route.as_ref()
    }

    /// Amount of input token.
    pub fn amount_in(&self) -> &BigUint {
        &self.amount_in
    }

    /// Amount of output token.
    pub fn amount_out(&self) -> &BigUint {
        &self.amount_out
    }

    /// Estimated gas cost for executing this route.
    pub fn gas_estimate(&self) -> &BigUint {
        &self.gas_estimate
    }

    /// Price impact in basis points, if available.
    pub fn price_impact_bps(&self) -> Option<i32> {
        self.price_impact_bps
    }

    /// Amount out minus gas cost in output token terms.
    pub fn amount_out_net_gas(&self) -> &BigUint {
        &self.amount_out_net_gas
    }

    /// Block at which this quote was computed.
    pub fn block(&self) -> &BlockInfo {
        &self.block
    }

    /// Effective gas price at the time the route was computed, if available.
    pub fn gas_price(&self) -> Option<&BigUint> {
        self.gas_price.as_ref()
    }

    /// Encoded EVM transaction, if encoding options were provided in the request.
    pub fn transaction(&self) -> Option<&Transaction> {
        self.transaction.as_ref()
    }

    /// Fee breakdown, if encoding options were provided in the request.
    pub fn fee_breakdown(&self) -> Option<&FeeBreakdown> {
        self.fee_breakdown.as_ref()
    }
}

/// Status of an order quote.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum QuoteStatus {
    /// A valid route was found.
    Success,
    /// No route exists between the specified tokens.
    NoRouteFound,
    /// A route exists but available liquidity is insufficient.
    InsufficientLiquidity,
    /// The solver timed out before finding a route.
    Timeout,
    /// No solver workers are ready (e.g., market data not yet initialized).
    NotReady,
    /// The solution failed external price validation.
    PriceCheckFailed,
}

/// Block information at which a quote was computed.
///
/// Quotes are only valid for the block at which they were computed. Market
/// conditions may change in subsequent blocks.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct BlockInfo {
    /// Block number.
    #[cfg_attr(feature = "openapi", schema(example = 21000000))]
    number: u64,
    /// Block hash as a hex string.
    #[cfg_attr(
        feature = "openapi",
        schema(example = "0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd")
    )]
    hash: String,
    /// Block timestamp in Unix seconds.
    #[cfg_attr(feature = "openapi", schema(example = 1730000000))]
    timestamp: u64,
}

impl BlockInfo {
    /// Create a new block info.
    pub fn new(number: u64, hash: String, timestamp: u64) -> Self {
        Self { number, hash, timestamp }
    }

    /// Block number.
    pub fn number(&self) -> u64 {
        self.number
    }

    /// Block hash as a hex string.
    pub fn hash(&self) -> &str {
        &self.hash
    }

    /// Block timestamp in Unix seconds.
    pub fn timestamp(&self) -> u64 {
        self.timestamp
    }
}

// ============================================================================
// ROUTE & SWAP TYPES
// ============================================================================

/// A route consisting of one or more sequential swaps.
///
/// A route describes the path through liquidity pools to execute a swap.
/// For multi-hop swaps, the output of each swap becomes the input of the next.
#[must_use]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct Route {
    /// Ordered sequence of swaps to execute.
    swaps: Vec<Swap>,
}

impl Route {
    /// Create a route from an ordered sequence of swaps.
    pub fn new(swaps: Vec<Swap>) -> Self {
        Self { swaps }
    }

    /// Ordered sequence of swaps to execute.
    pub fn swaps(&self) -> &[Swap] {
        &self.swaps
    }

    /// Consume this route and return the swaps.
    pub fn into_swaps(self) -> Vec<Swap> {
        self.swaps
    }
}

/// A single swap within a route.
///
/// Represents an atomic swap on a specific liquidity pool (component).
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct Swap {
    /// Identifier of the liquidity pool component.
    #[cfg_attr(
        feature = "openapi",
        schema(example = "0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc")
    )]
    component_id: String,
    /// Protocol system identifier (e.g., "uniswap_v2", "uniswap_v3", "vm:balancer").
    #[cfg_attr(feature = "openapi", schema(example = "uniswap_v2"))]
    protocol: String,
    /// Input token address.
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, example = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2")
    )]
    token_in: Address,
    /// Output token address.
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, example = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")
    )]
    token_out: Address,
    /// Amount of input token (in token units, as decimal string).
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, example = "1000000000000000000")
    )]
    amount_in: BigUint,
    /// Amount of output token (in token units, as decimal string).
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "3500000000"))]
    amount_out: BigUint,
    /// Estimated gas cost for this swap (as decimal string).
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "150000"))]
    gas_estimate: BigUint,
    /// Decimal of the amount to be swapped in this operation (for example, 0.5 means 50%)
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(example = "0.0"))]
    split: f64,
}

impl Swap {
    /// Create a new swap.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        component_id: String,
        protocol: String,
        token_in: Address,
        token_out: Address,
        amount_in: BigUint,
        amount_out: BigUint,
        gas_estimate: BigUint,
        split: f64,
    ) -> Self {
        Self {
            component_id,
            protocol,
            token_in,
            token_out,
            amount_in,
            amount_out,
            gas_estimate,
            split,
        }
    }

    /// Liquidity pool component identifier.
    pub fn component_id(&self) -> &str {
        &self.component_id
    }

    /// Protocol system identifier.
    pub fn protocol(&self) -> &str {
        &self.protocol
    }

    /// Input token address.
    pub fn token_in(&self) -> &Address {
        &self.token_in
    }

    /// Output token address.
    pub fn token_out(&self) -> &Address {
        &self.token_out
    }

    /// Amount of input token.
    pub fn amount_in(&self) -> &BigUint {
        &self.amount_in
    }

    /// Amount of output token.
    pub fn amount_out(&self) -> &BigUint {
        &self.amount_out
    }

    /// Estimated gas cost for this swap.
    pub fn gas_estimate(&self) -> &BigUint {
        &self.gas_estimate
    }

    /// Fraction of the total amount routed through this swap.
    pub fn split(&self) -> f64 {
        self.split
    }
}

// ============================================================================
// HEALTH CHECK TYPES
// ============================================================================

/// Health check response.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct HealthStatus {
    /// Whether the service is healthy.
    #[cfg_attr(feature = "openapi", schema(example = true))]
    healthy: bool,
    /// Time since last market update in milliseconds.
    #[cfg_attr(feature = "openapi", schema(example = 1250))]
    last_update_ms: u64,
    /// Number of active solver pools.
    #[cfg_attr(feature = "openapi", schema(example = 2))]
    num_solver_pools: usize,
    /// Whether derived data has been computed at least once.
    ///
    /// This indicates overall readiness, not per-block freshness. Some algorithms
    /// require fresh derived data for each block — they are ready to receive orders
    /// but will wait for recomputation before solving.
    #[serde(default)]
    #[cfg_attr(feature = "openapi", schema(example = true))]
    derived_data_ready: bool,
    /// Time since last gas price update in milliseconds, if available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = 12000))]
    gas_price_age_ms: Option<u64>,
}

impl HealthStatus {
    /// Create a new health status.
    pub fn new(
        healthy: bool,
        last_update_ms: u64,
        num_solver_pools: usize,
        derived_data_ready: bool,
        gas_price_age_ms: Option<u64>,
    ) -> Self {
        Self { healthy, last_update_ms, num_solver_pools, derived_data_ready, gas_price_age_ms }
    }

    /// Whether the service is healthy.
    pub fn healthy(&self) -> bool {
        self.healthy
    }

    /// Time since last market update in milliseconds.
    pub fn last_update_ms(&self) -> u64 {
        self.last_update_ms
    }

    /// Number of active solver pools.
    pub fn num_solver_pools(&self) -> usize {
        self.num_solver_pools
    }

    /// Whether derived data has been computed at least once.
    pub fn derived_data_ready(&self) -> bool {
        self.derived_data_ready
    }

    /// Time since last gas price update in milliseconds, if available.
    pub fn gas_price_age_ms(&self) -> Option<u64> {
        self.gas_price_age_ms
    }
}

/// Static metadata about this Fynd instance, returned by `GET /v1/info`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct InstanceInfo {
    /// EIP-155 chain ID (e.g. 1 for Ethereum mainnet).
    #[cfg_attr(feature = "openapi", schema(example = 1))]
    chain_id: u64,
    /// Address of the Tycho Router contract on this chain.
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, example = "0xfD0b31d2E955fA55e3fa641Fe90e08b677188d35")
    )]
    router_address: Bytes,
    /// Address of the canonical Permit2 contract (same on all EVM chains).
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, example = "0x000000000022D473030F116dDEE9F6B43aC78BA3")
    )]
    permit2_address: Bytes,
}

impl InstanceInfo {
    /// Creates a new instance info.
    pub fn new(chain_id: u64, router_address: Bytes, permit2_address: Bytes) -> Self {
        Self { chain_id, router_address, permit2_address }
    }

    /// EIP-155 chain ID.
    pub fn chain_id(&self) -> u64 {
        self.chain_id
    }

    /// Address of the Tycho Router contract.
    pub fn router_address(&self) -> &Bytes {
        &self.router_address
    }

    /// Address of the canonical Permit2 contract.
    pub fn permit2_address(&self) -> &Bytes {
        &self.permit2_address
    }
}

/// Error response body.
#[must_use]
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct ErrorResponse {
    #[cfg_attr(feature = "openapi", schema(example = "bad request: no orders provided"))]
    error: String,
    #[cfg_attr(feature = "openapi", schema(example = "BAD_REQUEST"))]
    code: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    details: Option<serde_json::Value>,
}

impl ErrorResponse {
    /// Create an error response with the given message and code.
    pub fn new(error: String, code: String) -> Self {
        Self { error, code, details: None }
    }

    /// Add structured details to the error response.
    pub fn with_details(mut self, details: serde_json::Value) -> Self {
        self.details = Some(details);
        self
    }

    /// Human-readable error message.
    pub fn error(&self) -> &str {
        &self.error
    }

    /// Machine-readable error code.
    pub fn code(&self) -> &str {
        &self.code
    }

    /// Structured error details, if present.
    pub fn details(&self) -> Option<&serde_json::Value> {
        self.details.as_ref()
    }
}

// ============================================================================
// ENCODING TYPES
// ============================================================================

/// An encoded EVM transaction ready to be submitted on-chain.
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct Transaction {
    /// Contract address to call.
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"))]
    to: Bytes,
    /// Native token value to send with the transaction (as decimal string).
    #[serde_as(as = "DisplayFromStr")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "0"))]
    value: BigUint,
    /// ABI-encoded calldata as hex string.
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "0x1234567890abcdef"))]
    #[serde(serialize_with = "serialize_bytes_hex", deserialize_with = "deserialize_bytes_hex")]
    data: Vec<u8>,
}

impl Transaction {
    /// Create a new transaction.
    pub fn new(to: Bytes, value: BigUint, data: Vec<u8>) -> Self {
        Self { to, value, data }
    }

    /// Contract address to call.
    pub fn to(&self) -> &Bytes {
        &self.to
    }

    /// Native token value to send with the transaction.
    pub fn value(&self) -> &BigUint {
        &self.value
    }

    /// ABI-encoded calldata.
    pub fn data(&self) -> &[u8] {
        &self.data
    }
}

// ============================================================================
// CUSTOM SERIALIZATION
// ============================================================================

/// Serializes Vec<u8> to hex string with 0x prefix.
fn serialize_bytes_hex<S>(bytes: &Vec<u8>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(&format!("0x{}", hex::encode(bytes)))
}

/// Deserializes hex string (with or without 0x prefix) to Vec<u8>.
fn deserialize_bytes_hex<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    let s = s.strip_prefix("0x").unwrap_or(&s);
    hex::decode(s).map_err(serde::de::Error::custom)
}

// ============================================================================
// PRIVATE HELPERS
// ============================================================================

/// Generates a unique order ID using UUID v4.
fn generate_order_id() -> String {
    Uuid::new_v4().to_string()
}

// ============================================================================
// WIRE FORMAT TESTS
// ============================================================================
//
// These tests pin the JSON wire format for the key API types. They catch
// field renames, enum case changes, wrong numeric types, and structural
// changes that would silently break API clients.

#[cfg(test)]
mod wire_format_tests {
    use num_bigint::BigUint;

    use super::*;

    // ── Bytes: accept hex without 0x prefix ───────────────────────────────────
    //
    // All other Bytes/Address format behaviour is covered implicitly by the
    // struct tests below. This case (no prefix) is the only non-obvious one
    // worth testing in isolation.

    #[test]
    fn bytes_deserializes_without_0x_prefix() {
        let b: Bytes = serde_json::from_str(r#""deadbeef""#).unwrap();
        assert_eq!(b.as_ref(), [0xDE, 0xAD, 0xBE, 0xEF]);
    }

    // ── Order: full request JSON shape ────────────────────────────────────────
    //
    // Verifies field names, side as "sell" (not "Sell"), amount as decimal
    // string (not a number), addresses as "0x..." hex, and receiver absent
    // when not set.

    #[test]
    fn order_serializes_to_full_json() {
        let order = Order::new(
            Bytes::from([0xAAu8; 20]),
            Bytes::from([0xBBu8; 20]),
            BigUint::from(1_000_000_000_000_000_000u64),
            OrderSide::Sell,
            Bytes::from([0xCCu8; 20]),
        )
        .with_id("abc");

        assert_eq!(
            serde_json::to_value(&order).unwrap(),
            serde_json::json!({
                "id": "abc",
                "token_in":  "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                "token_out": "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
                "amount":    "1000000000000000000",
                "side":      "sell",
                "sender":    "0xcccccccccccccccccccccccccccccccccccccccc"
            })
        );
    }

    // ── OrderQuote: full response JSON deserialization ────────────────────────
    //
    // Verifies that a realistic server response deserializes correctly:
    // status as "success", BigUint fields from decimal strings, nested block,
    // route with a Swap whose token addresses are hex and split is a string.

    #[test]
    fn order_quote_deserializes_from_json() {
        let json = r#"{
            "order_id": "order-1",
            "status": "success",
            "amount_in": "1000000000000000000",
            "amount_out": "2000000000",
            "gas_estimate": "150000",
            "amount_out_net_gas": "1999000000",
            "price_impact_bps": 5,
            "block": { "number": 21000000, "hash": "0xdeadbeef", "timestamp": 1700000000 },
            "route": { "swaps": [{
                "component_id": "pool-1",
                "protocol": "uniswap_v3",
                "token_in":  "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                "token_out": "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
                "amount_in": "1000000000000000000",
                "amount_out": "2000000000",
                "gas_estimate": "150000",
                "split": "0"
            }]}
        }"#;

        let quote: OrderQuote = serde_json::from_str(json).unwrap();

        assert_eq!(quote.status(), QuoteStatus::Success);
        assert_eq!(*quote.amount_in(), BigUint::from(1_000_000_000_000_000_000u64));
        assert_eq!(quote.price_impact_bps(), Some(5));
        assert_eq!(quote.block().number(), 21_000_000);

        let swap = &quote.route().unwrap().swaps()[0];
        assert_eq!(swap.token_in().as_ref(), [0xAAu8; 20]);
        assert_eq!(swap.token_out().as_ref(), [0xBBu8; 20]);
        assert_eq!(swap.split(), 0.0);
    }

    // ── EncodingOptions: full request JSON shape ──────────────────────────────
    //
    // Verifies transfer_type serializes as "transfer_from" (snake_case, not
    // "TransferFrom"), slippage is a float, and optional fields are absent
    // when not set.

    #[test]
    fn encoding_options_serializes_to_full_json() {
        assert_eq!(
            serde_json::to_value(EncodingOptions::new(0.005)).unwrap(),
            serde_json::json!({
                "slippage":      "0.005",
                "transfer_type": "transfer_from"
            })
        );
    }

    // ── InstanceInfo: response deserialization with forward compat ────────────
    //
    // Verifies the /info endpoint response deserializes correctly, and that
    // unknown fields added in future server versions are silently ignored
    // (no #[serde(deny_unknown_fields)] on this type).

    #[test]
    fn instance_info_deserializes_and_ignores_unknown_fields() {
        let json = r#"{
            "chain_id": 1,
            "router_address": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            "permit2_address": "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
            "future_field": "ignored"
        }"#;

        let info: InstanceInfo = serde_json::from_str(json).unwrap();
        assert_eq!(info.chain_id(), 1);
        assert_eq!(info.router_address().as_ref(), [0xAAu8; 20]);
        assert_eq!(info.permit2_address().as_ref(), [0xBBu8; 20]);
    }
}

// ============================================================================
// CONVERSIONS: fynd-core integration (feature = "core")
// ============================================================================

/// Conversions between DTO types and [`fynd_core`] domain types.
///
/// - [`From<fynd_core::X>`] for DTO types handles the Core → DTO direction.
/// - [`Into<fynd_core::X>`] for DTO types handles the DTO → Core direction. (`From` cannot be used
///   in that direction: `fynd_core` types are external, so implementing `From<DTO>` on them would
///   violate the orphan rule.)
#[cfg(feature = "core")]
mod conversions {
    use tycho_simulation::tycho_core::Bytes as TychoBytes;

    use super::*;

    // ── Byte-type bridge ─────────────────────────────────────────────────────
    //
    // Both types wrap `bytes::Bytes` and share the same wire format. The inner
    // field is `pub` on TychoBytes, so the conversion is zero-copy.

    impl From<TychoBytes> for Bytes {
        fn from(b: TychoBytes) -> Self {
            Self(b.0)
        }
    }

    impl From<Bytes> for TychoBytes {
        fn from(b: Bytes) -> Self {
            Self(b.0)
        }
    }

    // -------------------------------------------------------------------------
    // DTO → Core  (use Into; From<DTO> on core types would violate orphan rules)
    // -------------------------------------------------------------------------

    impl Into<fynd_core::QuoteRequest> for QuoteRequest {
        fn into(self) -> fynd_core::QuoteRequest {
            fynd_core::QuoteRequest::new(
                self.orders
                    .into_iter()
                    .map(Into::into)
                    .collect(),
                self.options.into(),
            )
        }
    }

    impl Into<fynd_core::QuoteOptions> for QuoteOptions {
        fn into(self) -> fynd_core::QuoteOptions {
            let mut opts = fynd_core::QuoteOptions::default();
            if let Some(ms) = self.timeout_ms {
                opts = opts.with_timeout_ms(ms);
            }
            if let Some(n) = self.min_responses {
                opts = opts.with_min_responses(n);
            }
            if let Some(gas) = self.max_gas {
                opts = opts.with_max_gas(gas);
            }
            if let Some(enc) = self.encoding_options {
                opts = opts.with_encoding_options(enc.into());
            }
            if let Some(pg) = self.price_guard {
                opts = opts.with_price_guard(pg.into());
            }
            opts
        }
    }

    impl Into<fynd_core::PriceGuardConfig> for PriceGuardConfig {
        fn into(self) -> fynd_core::PriceGuardConfig {
            let mut config = fynd_core::PriceGuardConfig::default();
            if let Some(bps) = self.lower_tolerance_bps {
                config = config.with_lower_tolerance_bps(bps);
            }
            if let Some(bps) = self.upper_tolerance_bps {
                config = config.with_upper_tolerance_bps(bps);
            }
            if let Some(allow) = self.allow_on_provider_error {
                config = config.with_allow_on_provider_error(allow);
            }
            if let Some(allow) = self.allow_on_token_price_not_found {
                config = config.with_allow_on_token_price_not_found(allow);
            }
            if let Some(enabled) = self.enabled {
                config = config.with_enabled(enabled);
            }
            config
        }
    }

    impl Into<fynd_core::EncodingOptions> for EncodingOptions {
        fn into(self) -> fynd_core::EncodingOptions {
            let mut opts = fynd_core::EncodingOptions::new(self.slippage)
                .with_transfer_type(self.transfer_type.into());
            if let (Some(permit), Some(sig)) = (self.permit, self.permit2_signature) {
                opts = opts
                    .with_permit(permit.into())
                    .with_signature(sig.into());
            }
            if let Some(fee) = self.client_fee_params {
                opts = opts.with_client_fee_params(fee.into());
            }
            opts
        }
    }

    impl Into<fynd_core::ClientFeeParams> for ClientFeeParams {
        fn into(self) -> fynd_core::ClientFeeParams {
            fynd_core::ClientFeeParams::new(
                self.bps,
                self.receiver.into(),
                self.max_contribution,
                self.deadline,
                self.signature.into(),
            )
        }
    }

    impl Into<fynd_core::UserTransferType> for UserTransferType {
        fn into(self) -> fynd_core::UserTransferType {
            match self {
                UserTransferType::TransferFromPermit2 => {
                    fynd_core::UserTransferType::TransferFromPermit2
                }
                UserTransferType::TransferFrom => fynd_core::UserTransferType::TransferFrom,
                UserTransferType::UseVaultsFunds => fynd_core::UserTransferType::UseVaultsFunds,
            }
        }
    }

    impl Into<fynd_core::PermitSingle> for PermitSingle {
        fn into(self) -> fynd_core::PermitSingle {
            fynd_core::PermitSingle::new(
                self.details.into(),
                self.spender.into(),
                self.sig_deadline,
            )
        }
    }

    impl Into<fynd_core::PermitDetails> for PermitDetails {
        fn into(self) -> fynd_core::PermitDetails {
            fynd_core::PermitDetails::new(
                self.token.into(),
                self.amount,
                self.expiration,
                self.nonce,
            )
        }
    }

    impl Into<fynd_core::Order> for Order {
        fn into(self) -> fynd_core::Order {
            let mut order = fynd_core::Order::new(
                self.token_in.into(),
                self.token_out.into(),
                self.amount,
                self.side.into(),
                self.sender.into(),
            )
            .with_id(self.id);
            if let Some(r) = self.receiver {
                order = order.with_receiver(r.into());
            }
            order
        }
    }

    impl Into<fynd_core::OrderSide> for OrderSide {
        fn into(self) -> fynd_core::OrderSide {
            match self {
                OrderSide::Sell => fynd_core::OrderSide::Sell,
            }
        }
    }

    // -------------------------------------------------------------------------
    // Core → DTO  (From is fine; DTO types are local to this crate)
    // -------------------------------------------------------------------------

    impl From<fynd_core::Quote> for Quote {
        fn from(core: fynd_core::Quote) -> Self {
            let solve_time_ms = core.solve_time_ms();
            let total_gas_estimate = core.total_gas_estimate().clone();
            Self {
                orders: core
                    .into_orders()
                    .into_iter()
                    .map(Into::into)
                    .collect(),
                total_gas_estimate,
                solve_time_ms,
            }
        }
    }

    impl From<fynd_core::OrderQuote> for OrderQuote {
        fn from(core: fynd_core::OrderQuote) -> Self {
            let order_id = core.order_id().to_string();
            let status = core.status().into();
            let amount_in = core.amount_in().clone();
            let amount_out = core.amount_out().clone();
            let gas_estimate = core.gas_estimate().clone();
            let price_impact_bps = core.price_impact_bps();
            let amount_out_net_gas = core.amount_out_net_gas().clone();
            let block = core.block().clone().into();
            let gas_price = core.gas_price().cloned();
            let transaction = core
                .transaction()
                .cloned()
                .map(Into::into);
            let fee_breakdown = core
                .fee_breakdown()
                .cloned()
                .map(Into::into);
            let route = core.into_route().map(Into::into);
            Self {
                order_id,
                status,
                route,
                amount_in,
                amount_out,
                gas_estimate,
                price_impact_bps,
                amount_out_net_gas,
                block,
                gas_price,
                transaction,
                fee_breakdown,
            }
        }
    }

    impl From<fynd_core::QuoteStatus> for QuoteStatus {
        fn from(core: fynd_core::QuoteStatus) -> Self {
            match core {
                fynd_core::QuoteStatus::Success => Self::Success,
                fynd_core::QuoteStatus::NoRouteFound => Self::NoRouteFound,
                fynd_core::QuoteStatus::InsufficientLiquidity => Self::InsufficientLiquidity,
                fynd_core::QuoteStatus::Timeout => Self::Timeout,
                fynd_core::QuoteStatus::NotReady => Self::NotReady,
                fynd_core::QuoteStatus::PriceCheckFailed => Self::PriceCheckFailed,
                // Fallback for future variants added to fynd_core::QuoteStatus.
                _ => Self::NotReady,
            }
        }
    }

    impl From<fynd_core::BlockInfo> for BlockInfo {
        fn from(core: fynd_core::BlockInfo) -> Self {
            Self {
                number: core.number(),
                hash: core.hash().to_string(),
                timestamp: core.timestamp(),
            }
        }
    }

    impl From<fynd_core::Route> for Route {
        fn from(core: fynd_core::Route) -> Self {
            Self {
                swaps: core
                    .into_swaps()
                    .into_iter()
                    .map(Into::into)
                    .collect(),
            }
        }
    }

    impl From<fynd_core::Swap> for Swap {
        fn from(core: fynd_core::Swap) -> Self {
            Self {
                component_id: core.component_id().to_string(),
                protocol: core.protocol().to_string(),
                token_in: core.token_in().clone().into(),
                token_out: core.token_out().clone().into(),
                amount_in: core.amount_in().clone(),
                amount_out: core.amount_out().clone(),
                gas_estimate: core.gas_estimate().clone(),
                split: *core.split(),
            }
        }
    }

    impl From<fynd_core::Transaction> for Transaction {
        fn from(core: fynd_core::Transaction) -> Self {
            Self {
                to: core.to().clone().into(),
                value: core.value().clone(),
                data: core.data().to_vec(),
            }
        }
    }

    impl From<fynd_core::FeeBreakdown> for FeeBreakdown {
        fn from(core: fynd_core::FeeBreakdown) -> Self {
            Self {
                router_fee: core.router_fee().clone(),
                client_fee: core.client_fee().clone(),
                max_slippage: core.max_slippage().clone(),
                min_amount_received: core.min_amount_received().clone(),
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use num_bigint::BigUint;

        use super::*;

        fn make_address(byte: u8) -> Address {
            Address::from([byte; 20])
        }

        #[test]
        fn test_quote_request_roundtrip() {
            let dto = QuoteRequest {
                orders: vec![Order {
                    id: "test-id".to_string(),
                    token_in: make_address(0x01),
                    token_out: make_address(0x02),
                    amount: BigUint::from(1000u64),
                    side: OrderSide::Sell,
                    sender: make_address(0xAA),
                    receiver: None,
                }],
                options: QuoteOptions {
                    timeout_ms: Some(5000),
                    min_responses: None,
                    max_gas: None,
                    encoding_options: None,
                    price_guard: None,
                },
            };

            let core: fynd_core::QuoteRequest = dto.clone().into();
            assert_eq!(core.orders().len(), 1);
            assert_eq!(core.orders()[0].id(), "test-id");
            assert_eq!(core.options().timeout_ms(), Some(5000));
        }

        #[test]
        fn test_quote_from_core() {
            let core: fynd_core::Quote = serde_json::from_str(
                r#"{"orders":[],"total_gas_estimate":"100000","solve_time_ms":50}"#,
            )
            .unwrap();

            let dto = Quote::from(core);
            assert_eq!(dto.total_gas_estimate, BigUint::from(100_000u64));
            assert_eq!(dto.solve_time_ms, 50);
        }

        #[test]
        fn test_order_side_into_core() {
            let core: fynd_core::OrderSide = OrderSide::Sell.into();
            assert_eq!(core, fynd_core::OrderSide::Sell);
        }

        #[test]
        fn test_client_fee_params_into_core() {
            let dto = ClientFeeParams::new(
                200,
                Bytes::from(make_address(0xBB).as_ref()),
                BigUint::from(1_000_000u64),
                1_893_456_000u64,
                Bytes::from(vec![0xABu8; 65]),
            );
            let core: fynd_core::ClientFeeParams = dto.into();
            assert_eq!(core.bps(), 200);
            assert_eq!(*core.max_contribution(), BigUint::from(1_000_000u64));
            assert_eq!(core.deadline(), 1_893_456_000u64);
            assert_eq!(core.signature().len(), 65);
        }

        #[test]
        fn test_encoding_options_with_client_fee_into_core() {
            let fee = ClientFeeParams::new(
                100,
                Bytes::from(make_address(0xCC).as_ref()),
                BigUint::from(500u64),
                9_999u64,
                Bytes::from(vec![0xDEu8; 65]),
            );
            let dto = EncodingOptions::new(0.005).with_client_fee_params(fee);
            let core: fynd_core::EncodingOptions = dto.into();

            assert!(core.client_fee_params().is_some());
            let core_fee = core.client_fee_params().unwrap();
            assert_eq!(core_fee.bps(), 100);
            assert_eq!(*core_fee.max_contribution(), BigUint::from(500u64));
        }

        #[test]
        fn test_client_fee_params_serde_roundtrip() {
            let fee = ClientFeeParams::new(
                150,
                Bytes::from(make_address(0xDD).as_ref()),
                BigUint::from(999_999u64),
                1_700_000_000u64,
                Bytes::from(vec![0xFFu8; 65]),
            );
            let json = serde_json::to_string(&fee).unwrap();
            assert!(json.contains(r#""max_contribution":"999999""#));
            assert!(json.contains(r#""deadline":1700000000"#));

            let deserialized: ClientFeeParams = serde_json::from_str(&json).unwrap();
            assert_eq!(deserialized.bps(), 150);
            assert_eq!(*deserialized.max_contribution(), BigUint::from(999_999u64));
        }

        #[test]
        fn test_price_guard_config_into_core() {
            let dto = PriceGuardConfig::default()
                .with_lower_tolerance_bps(200)
                .with_upper_tolerance_bps(5000)
                .with_allow_on_provider_error(true)
                .with_enabled(false);

            let core: fynd_core::PriceGuardConfig = dto.into();
            assert_eq!(core.lower_tolerance_bps(), 200);
            assert_eq!(core.upper_tolerance_bps(), 5000);
            assert!(core.allow_on_provider_error());
            assert!(!core.enabled());
        }

        #[test]
        fn test_price_guard_config_defaults_preserved() {
            let dto = PriceGuardConfig::default().with_lower_tolerance_bps(100);
            let core: fynd_core::PriceGuardConfig = dto.into();

            assert_eq!(core.lower_tolerance_bps(), 100);
            // Unset fields get core defaults
            assert_eq!(core.upper_tolerance_bps(), 10_000);
            assert!(!core.allow_on_provider_error());
            assert!(!core.enabled());
        }

        #[test]
        fn test_quote_options_with_price_guard_roundtrip() {
            let dto = QuoteRequest {
                orders: vec![Order {
                    id: "pg-test".to_string(),
                    token_in: make_address(0x01),
                    token_out: make_address(0x02),
                    amount: BigUint::from(1000u64),
                    side: OrderSide::Sell,
                    sender: make_address(0xAA),
                    receiver: None,
                }],
                options: QuoteOptions::default()
                    .with_price_guard(PriceGuardConfig::default().with_enabled(false)),
            };

            let core: fynd_core::QuoteRequest = dto.into();
            let pg = core
                .options()
                .price_guard()
                .expect("price_guard should be set");
            assert!(!pg.enabled());
        }

        #[test]
        fn test_quote_status_from_core() {
            let cases = [
                (fynd_core::QuoteStatus::Success, QuoteStatus::Success),
                (fynd_core::QuoteStatus::NoRouteFound, QuoteStatus::NoRouteFound),
                (fynd_core::QuoteStatus::InsufficientLiquidity, QuoteStatus::InsufficientLiquidity),
                (fynd_core::QuoteStatus::Timeout, QuoteStatus::Timeout),
                (fynd_core::QuoteStatus::NotReady, QuoteStatus::NotReady),
            ];

            for (core, expected) in cases {
                assert_eq!(QuoteStatus::from(core), expected);
            }
        }
    }
}