titan-api-types 5.8.1

Definitions of types used across the Titan API
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
//! Types and constants for version 1 of the Titan WebSocket API.
//!
//! Messages sent across the WebSocket connection are expected to be encoded using [MessagePack],
//! along with optional compression. Whether compression is enabled and which algorithm is used is
//! negotiated via the [`Sec-WebSocket-Protocol`][sec-ws-proto] header during the WebSocket handshake using the
//! various subprotocol constants defined in this module.
//!
//! Structs are encoded with field names converted to `camelCase` except where otherwise specified.
//! Specifically, many commonly-used types such as [`crate::common::AccountMeta`] have encodings with
//! shorter field names to save space.
//!
//! For optional fields in structs, if the value is not set, it should be skipped while serializing
//! to save space.
//!
//! Enumerations are encoded depending on the type of enumeration.
//! Simple enumerations are encoded as their underlying values. The enumeration definition will
//! specify exactly what this is.
//!
//! Complex enumerations (e.g. those whose values have parameters) are encoded as single-entry maps,
//! where the key is a string with the name of the enumeration kind and the value is the encoded
//! parameter(s). If the enumeration has a single parameter, the value will be that parameter's
//! encoding. If the enumeration has multiple parameters, the value will be an array containing the
//! encoded parameters.
//!
//! [MessagePack]: https://msgpack.org/index.html
//! [sec-ws-proto]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-WebSocket-Protocol

use std::collections::HashMap;

use crate::common::{
    instruction::AddressLookupTableAccount, AccountMeta, BoundedValueWithDefault, Instruction,
    Pubkey,
};

/// Major version number of this API.
pub const VERSION_MAJOR: u16 = 1;
/// Minor version number of this API.
///
/// Incremented when non-breaking changes are made to the type definitions, such as adding new
/// optional fields to request types or new fields to response types that are not crucial for the
/// client to understand.
pub const VERSION_MINOR: u16 = 10;

/// Base subprotocol identifier for this version of the WebSocket API.
///
/// For this version of the protocol, all messages are encoded via [MessagePack] with no
/// compression. Compression may be separately provided via WebSocket protocol extensions if
/// supported by both the client and server.
///
/// To be used with the [`Sec-WebSocket-Protocol`] header for sub-protocol negotiation.
///
/// [MessagePack]: https://msgpack.org/index.html
/// ['Sec-WebSocket-Protocol`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-WebSocket-Protocol
pub const WEBSOCKET_SUBPROTO_BASE: &str = "v1.api.titan.ag";

/// Subprotocol identifier for this version of the WebSocket API with [zstd] compression.
///
/// If this protocol is selected, after encoding messages using [MessagePack], messages must be
/// compressed via [zstd] with compression level 3.
///
/// [MessagePack]: https://msgpack.org/index.html
/// [zstd]: https://github.com/facebook/zstd
pub const WEBSOCKET_SUBPROTO_ZSTD: &str = "v1.api.titan.ag+zstd";

/// Subprotocol identifier for this version of the WebSocket API with [brotli] compression.
///
/// If this protocol is selected, after encoding messages using [MessagePack], messages must be
/// compressed via [brotli] with quality level 11.
///
/// [MessagePack]: https://msgpack.org/index.html
/// [brotli]: https://github.com/google/brotli
pub const WEBSOCKET_SUBPROTO_BROTLI: &str = "v1.api.titan.ag+br";

/// Subprotocol identifier for this version of the WebSocket API with [gzip] compression.
///
/// If this protocol is selected, after encoding messages using [MessagePack], messages must be
/// compressed via [gzip].
///
/// [MessagePack]: https://msgpack.org/index.html
/// [gzip]: https://www.gzip.org/
pub const WEBSOCKET_SUBPROTO_GZIP: &str = "v1.api.titan.ag+gzip";

/// Array containing all the valid WeBSocket subprotocol identifiers for this version of the API.
///
/// Protocols are ordered roughly in descending order of preference in terms of compression ratio
/// and speed.
pub const WEBSOCKET_SUBPROTOCOLS: [&str; 4] = [
    WEBSOCKET_SUBPROTO_ZSTD,
    WEBSOCKET_SUBPROTO_BROTLI,
    WEBSOCKET_SUBPROTO_GZIP,
    WEBSOCKET_SUBPROTO_BASE,
];

/// Information about the version of the protocol being spoken by the server.
///
/// Only changes to the major and minor versions affect the format of data sent across the network.
/// Patch version increases note that internal logic changes in the server have occurred that do
/// not otherwise impact the API (e.g. bug fixes).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct VersionInfo {
    /// Major version number.
    ///
    /// Incremented when the data format changes in backwards-incompatible ways.
    pub major: u16,
    /// Minor version number.
    ///
    /// Incremented when the data format changes in backwards-compatible ways.
    pub minor: u16,
    /// Patch version number.
    ///
    /// Incremented when changes to the protocol that do not affect the data format have occurred.
    /// Primarily informational.
    pub patch: u16,
}

impl VersionInfo {
    /// Constructs a new `VersionInfo` from its parts.
    pub const fn new(major: u16, minor: u16, patch: u16) -> Self {
        Self {
            major,
            minor,
            patch,
        }
    }

    /// Computes a serial number representation of this version.
    ///
    /// This is constructed in such a way that comparisons of serial numbers respect the priority
    /// of major, minor, and patch versions.
    pub const fn serial(&self) -> u64 {
        ((self.major as u64) << 32) + ((self.minor as u64) << 16) + (self.minor as u64)
    }
}

/// Type of swap to perform.
///
/// Affects how the swap `amount` is handled.
///
/// Values are encoded as strings exactly matching the names.
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SwapMode {
    /// Swap amount is the number of input tokens that should be swapped.
    #[default]
    ExactIn,
    /// Swap amount is the number of output tokens that should be received.
    ExactOut,
}

/// Which version of the swap routing engine to use.
///
/// Currently defaults to [`V2`](SwapVersion::V2). V2 will be deprecated in a future release, at
/// which point the default will switch to [`V3`](SwapVersion::V3). After the deprecation date,
/// V2 will no longer receive technical support and clients should migrate to V3.
///
/// Values are encoded as their `u8` discriminant: `2` for V2, `3` for V3.
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(into = "u8", try_from = "u8")
)]
#[repr(u8)]
pub enum SwapVersion {
    /// Version 2 of the swap routing engine (current default, will be deprecated).
    #[default]
    V2 = 2,
    /// Version 3 of the swap routing engine.
    V3 = 3,
}

impl From<SwapVersion> for u8 {
    fn from(v: SwapVersion) -> u8 {
        v as u8
    }
}

impl TryFrom<u8> for SwapVersion {
    type Error = u8;

    fn try_from(v: u8) -> Result<Self, Self::Error> {
        match v {
            2 => Ok(Self::V2),
            3 => Ok(Self::V3),
            other => Err(other),
        }
    }
}

/// Which transaction wire format the client intends to build.
///
/// Orthogonal to [`SwapVersion`]: this selects the transaction encoding, that
/// selects the Titan swap instruction set. Defaults to [`V0`](TransactionFormat::V0),
/// so clients that do not set it are unaffected.
///
/// [`V1`](TransactionFormat::V1) is the Agave 4.2 / SIMD-0385 format: 4096
/// bytes, no address lookup tables. It is not supported with
/// [`SwapVersion::V2`].
///
/// Values are encoded as their `u8` discriminant: `0` for V0, `1` for V1.
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(into = "u8", try_from = "u8")
)]
#[repr(u8)]
pub enum TransactionFormat {
    /// Versioned (v0) transaction. Address lookup tables permitted.
    #[default]
    V0 = 0,
    /// SIMD-0385 transaction. 4096 bytes, no address lookup tables.
    V1 = 1,
}

impl From<TransactionFormat> for u8 {
    fn from(v: TransactionFormat) -> u8 {
        v as u8
    }
}

impl TryFrom<u8> for TransactionFormat {
    type Error = u8;

    fn try_from(v: u8) -> Result<Self, Self::Error> {
        match v {
            0 => Ok(Self::V0),
            1 => Ok(Self::V1),
            other => Err(other),
        }
    }
}

/// Transaction-level configuration for [`TransactionFormat::V1`].
///
/// V1 carries priority fee and compute budget in the transaction envelope
/// rather than in ComputeBudget instructions, which V1 ignores for
/// configuration. These values are not expressible as instructions, so a
/// [`TransactionTemplate`] cannot describe them without this struct — and a
/// transaction whose config we cannot see cannot be sized correctly.
///
/// Required when [`TransactionFormat::V1`] is used with a template.
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct TransactionConfigParams {
    /// Priority fee in lamports.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub priority_fee: Option<u64>,
    /// Maximum compute units.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub compute_unit_limit: Option<u32>,
    /// Maximum bytes of account data that may be loaded.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub loaded_accounts_data_size_limit: Option<u32>,
    /// Requested heap size in bytes. Must be a multiple of 1024.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub heap_size: Option<u32>,
}

/// A templated route which Titan can use when determining eligible routes.
/// If possible, Titan will insert at the specified index a swap that meets
/// Solana's sizing requirements. This is incompatible with the options,
/// `accounts_limit_total`, `accounts_limit_writable` and `size_constraint`.
/// An error will be returned if they are both specified.
#[derive(Default, PartialEq, Eq, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TransactionTemplate {
    /// A vector of instructions. It is assumed that you have included
    /// the input mint and output mint account creation/deletion when necessary.
    #[cfg_attr(feature = "serde", serde(rename = "i"))]
    pub instructions: Vec<Instruction>,
    /// Address lookup tables (ATLs) used in the instruction. Should be provided in the same order that
    /// you will use the address lookup tables when compiling the message. This is because Solana
    /// uses the ALTs in a greedy fashion and their effect is dependent on their ordering . Any ALTs used
    /// by Titan will be used to extend the vector.
    #[cfg_attr(feature = "serde", serde(rename = "a"))]
    pub alts: Vec<AddressLookupTableAccount>,
    /// Additional account metas that need to be added into consideration for sizing
    #[cfg_attr(feature = "serde", serde(rename = "m", default))]
    pub account_metas: Vec<AccountMeta>,
    /// Transaction-level configuration, required when using
    /// [`TransactionFormat::V1`].
    ///
    /// A template describes instructions, and V1's config values are not
    /// instructions — without this the transaction cannot be sized.
    #[cfg_attr(
        feature = "serde",
        serde(rename = "c", skip_serializing_if = "Option::is_none", default)
    )]
    pub transaction_config: Option<TransactionConfigParams>,
}

/// Parameters for a swap request.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct SwapParams {
    /// Address of the input mint of the swap.
    pub input_mint: Pubkey,
    /// Address of the desired output token for the swap.
    pub output_mint: Pubkey,
    /// Raw number of tokens to swap, not scaled by decimals.
    pub amount: u64,
    /// Swap mode for how the amount should be interpreted.
    ///
    /// Either ExactIn or ExactOut, defaults to ExactIn.
    /// ExactOut is for supporting use cases where you need an exact output token amount, like
    /// payments. In this case, slippage would be on the input token. May not always be supported.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub swap_mode: Option<SwapMode>,
    /// Allowed slippage in basis points.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub slippage_bps: Option<u16>,
    /// If set, constrain quotes to the given set of DEXes.
    ///
    /// Note: setting both `dexes` and `exclude_dexes` may result in excluding all dexes, resulting
    /// in no routes.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub dexes: Option<Vec<String>>,
    /// If set, exclude the following DEXes when determining routes.
    ///
    /// Note: setting both `dexes` and `exclude_dexes` may result in excluding all dexes, resulting
    /// in no routes.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub exclude_dexes: Option<Vec<String>>,
    /// If true, exclude the server-configured "vote account" venues from routing.
    /// When absent or false, those venues are included as normal.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub no_vote_accounts: Option<bool>,
    /// If set to true, only direct routes between the input and output mint will be considered.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub only_direct_routes: Option<bool>,
    /// If set to true, will request that quote providers restrict their quotes to transactions
    /// that will fit within the size constraint.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub add_size_constraint: Option<bool>,
    /// Transaction size constraint in bytes. Defaults to 1232. Only enabled if
    /// `add_size_constraint` is also set.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub size_constraint: Option<u32>,
    /// If set, limit quotes to the given set of provider IDs.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub providers: Option<Vec<String>>,
    /// If set, constrain quotes to routes that only use venues (pools) whose address is in this
    /// list.
    ///
    /// This filters by individual venue address, unlike `dexes`/`exclude_dexes` which filter by
    /// venue label. A venue present in `venue_banlist` is excluded even if it also appears here:
    /// the banlist takes precedence over the allowlist.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub venue_allowlist: Option<Vec<Pubkey>>,
    /// If set, exclude any route that uses a venue (pool) whose address is in this list.
    ///
    /// The banlist overrides `venue_allowlist`: a venue in both lists is always excluded.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub venue_banlist: Option<Vec<Pubkey>>,
    /// If set, limit total number of accounts used by routes to the specified value.
    ///
    /// If not set, any number of accounts that still allows for an executable transaction is
    /// allowed. As of writing, this is 256 accounts.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub accounts_limit_total: Option<u16>,
    /// If set, limit total number of writable accounts used by routes to the specified value.
    ///
    /// If not set, any number of accounts that still allows for an executable transaction is
    /// allowed. As of writing, this is 64 writable accounts.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub accounts_limit_writable: Option<u16>,
    /// If set, overrides the mesh size written into the swap instruction for dynamic allocation
    /// routes, replacing the route's configured default.
    ///
    /// The on-chain optimizer splits each venue group's input into `mesh_size` chunks, so a
    /// smaller value gives a coarser split that uses fewer compute units. `0` disables dynamic
    /// allocation entirely. Currently only honored by DART.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub mesh_size: Option<u8>,
    /// A templated route which Titan can use when determining eligible routes.
    /// If possible, Titan will insert at the specified index a swap that meets
    /// Solana's sizing requirements. This is incompatible with the options,
    /// `accounts_limit_total`, `accounts_limit_writable` and `size_constraint`.
    /// An error will be returned if they are both specified.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub transaction_template: Option<TransactionTemplate>,
}

/// Server default settings and constraints for [`SwapParams`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct SwapSettings {
    /// Default and bounds for [`SwapParams::slippage_bps`].
    pub slippage_bps: BoundedValueWithDefault<u16>,
    /// Default value for [`SwapParams::only_direct_routes`].
    pub only_direct_routes: bool,
    /// Default value for [`SwapParams::add_size_constraint`].
    pub add_size_constraint: bool,
    /// Default value for [`SwapParams::size_constraint`].
    pub size_constraint: u32,
}

/// Parameters for how quote updates should be handled.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct QuoteUpdateParams {
    /// How often the server should send updates for this quote request, in milliseconds.
    ///
    /// If not specified, the server default will be used.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub interval_ms: Option<u64>,
    /// Maximum number of quotes per update the server should return. If more quotes are available,
    /// the worst will be filtered out, based on amount in/out depending on swap mode.
    ///
    /// If not specified, the server default will be used.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub num_quotes: Option<u32>,
    /// Whether to include Address Lookup Table contents in responses.
    ///
    /// If not specified, only ALT addresses are returned and the user is responsible for looking up
    /// ALTs when building transactions.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub include_alt_contents: Option<bool>,
}

/// Contains information about the server's settings for quote updates.
///
/// Contains minimum, maximum, and default values as needed for the various settings, so that the
/// client can query information about these settings to ensure that its requests contain valid
/// values.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct QuoteUpdateSettings {
    /// Bounds and defaults for the `interval_ms` field of [`QuoteUpdateParams`].
    pub interval_ms: BoundedValueWithDefault<u64>,
    /// Bounds and defaults for the [`QuoteUpdateParams::num_quotes`] field.
    pub num_quotes: BoundedValueWithDefault<u32>,
}

/// Parameters for how transaction data should be generated for swaps.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct TransactionParams {
    /// Public key of the user requesting the swap, needed for transaction generation.
    pub user_public_key: Pubkey,
    /// If true, close the input token account as part of the transaction.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub close_input_token_account: Option<bool>,
    /// If true, an idempotent ATA will be added to the transactions, if supported by the
    /// providers.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub create_output_token_account: Option<bool>,
    /// The address of an associated token account that will be used to collect fees.
    ///
    /// Unless `fee_is_input_mint` is set to true, must be in terms of the output mint.
    ///
    /// The fee acount must already exist, or the user must add the ATA creation
    /// instruction themselves.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub fee_account: Option<Pubkey>,
    /// Fee amount to take, in basis points.
    ///
    /// If not specified, default fee for the requester is used.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub fee_bps: Option<u16>,
    /// Whether the fee should be taken in terms of the input mint.
    /// Default is false, in which case the fee is taken in terms of the output mint.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub fee_from_input_mint: Option<bool>,
    /// Address of the token account into which to place the output of the swap.
    /// If not specified, the funds will be deposited into an ATA associated with the user's
    /// wallet.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub output_account: Option<Pubkey>,
    /// Which version of the swap routing engine to use.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub titan_swap_version: Option<SwapVersion>,
    /// Which transaction wire format to build. Defaults to
    /// [`TransactionFormat::V0`].
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub transaction_format: Option<TransactionFormat>,
    /// The address that will receive any positive slippage fees.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub positive_slippage_fee_receiver: Option<Pubkey>,
    /// The address of the payer for the transaction.
    /// If not specified, defaults to the user's public key.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub payer: Option<Pubkey>,
    /// If true, leave the output as wSOL instead of unwrapping to native SOL when the output mint
    /// is the wrapped SOL mint. Defaults to false.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub output_wsol: Option<bool>,
}

/// Contains information about the server's defaults and paramter bounds for transactions.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct TransactionSettings {
    /// Default value for [`TransactionParams::close_input_token_account`].
    pub close_input_token_account: bool,
    /// Default value for [`TransactionParams::create_output_token_account`].
    pub create_output_token_account: bool,
}

/// Contains information about settings or limits set for the specific connection to the server.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct ConnectionSettings {
    /// Number of concurrent streams the user is allowed.
    pub concurrent_streams: u32,
}

/// Settings and paramter bounds as configured on the server.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct ServerSettings {
    /// Settings and parameter bounds for quote updates.
    pub quote_update: QuoteUpdateSettings,
    /// Settings and parameter bounds for swaps.
    pub swap: SwapSettings,
    /// Settings and parameter bounds for transaction generation.
    pub transaction: TransactionSettings,
    /// Settings and limits for the user's connection to the server.
    pub connection: ConnectionSettings,
}

/// Contains information about the servers settings.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct ServerInfo {
    /// Server protocol version information.
    pub protocol_version: VersionInfo,
    /// Server settings and parameter bounds.
    pub settings: ServerSettings,
}

/// A request from the user to provide quotes for a swap.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct SwapQuoteRequest {
    /// Parameters for the swap.
    pub swap: SwapParams,
    /// Parameters for transaction generation.
    pub transaction: TransactionParams,
    /// Parameters for quote updating.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub update: Option<QuoteUpdateParams>,
}

/// A request from the user to quote swapping an amount directly between two tokens,
/// which effectively gives the relative price of the tokens at that value.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct SwapPriceRequest {
    /// Address of the input mint of the swap.
    pub input_mint: Pubkey,
    /// Address of the desired output token for the swap.
    pub output_mint: Pubkey,
    /// Raw number of tokens to swap, not scaled by decimals.
    pub amount: u64,
    /// If set, constrain quotes to the given set of DEXes.
    ///
    /// Note: setting both `dexes` and `exclude_dexes` may result in excluding all dexes, resulting
    /// in no routes.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub dexes: Option<Vec<String>>,
    /// If set, exclude the following DEXes when determining routes.
    ///
    /// Note: setting both `dexes` and `exclude_dexes` may result in excluding all dexes, resulting
    /// in no routes.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub exclude_dexes: Option<Vec<String>>,
}

/// Information about a single step in a route plan for a swap.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct RoutePlanStep {
    /// Which AMM is being executed on at this step.
    pub amm_key: Pubkey,
    /// Label for the protocol being used.
    ///
    /// Examples: "Raydium AMM", "Phoenix", etc.
    pub label: String,
    /// Address of the input mint for this swap.
    pub input_mint: Pubkey,
    /// Address of the output mint for this swap.
    pub output_mint: Pubkey,
    /// How many input tokens are expected to go through this step.
    pub in_amount: u64,
    /// How many output tokens are expected to come out of this step.
    pub out_amount: u64,
    /// What what proportion, in parts per billion, of the order flow is allocated to flow through this pool.
    pub alloc_ppb: u32,
    /// Address of the mint in which the fee is charged.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub fee_mint: Option<Pubkey>,
    /// The amount of tokens charged as a fee for this swap.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub fee_amount: Option<u64>,
    /// Context slot for the pool data, if known.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub context_slot: Option<u64>,
}

/// Information about a fee that is claimed by a platform for use of its services as part of a
/// quote.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct PlatformFee {
    /// Amount of tokens taken as a fee.
    pub amount: u64,
    /// Fee percentage, in basis points.
    pub fee_bps: u8,
}

/// Information about a route for a swap.
#[derive(Debug, Clone, Default, PartialEq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct SwapRoute {
    /// How many input tokens are expected to go through this route.
    pub in_amount: u64,
    /// How many output tokens are expected to come out of this route.
    pub out_amount: u64,
    /// Amount of slippage encurred, in basis points.
    pub slippage_bps: u16,
    /// Platform fee information, if such a fee is charged by the provider.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub platform_fee: Option<PlatformFee>,
    /// Topologically ordered DAG containing the steps that comprise this route.
    ///
    /// May be empty if the provider does not provide information about the steps taken, or there
    /// are no steps (e.g. RFQ providers).
    pub steps: Vec<RoutePlanStep>,
    /// Instructions needed to execute the route.
    ///
    /// May be empty if the provider does not support the user building their own transactions.
    /// In this case, the transaction to sign should be present in the [`SwapRoute::transaction`]
    /// field.
    pub instructions: Vec<Instruction>,
    /// Address lookup tables necessary to load.
    ///
    /// May be empty if the provider does not support the user building their own transactions.
    /// In this case, the transaction to sign should be present in the [`SwapRoute::transaction`]
    /// field.
    pub address_lookup_tables: Vec<Pubkey>,
    /// Context slot for the route provided.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub context_slot: Option<u64>,
    /// Amount of time taken to generate the quote in seconds, if known.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub time_taken_ns: Option<u64>,
    /// If this route expires by time, the time at which it expires, as a millisecond UNIX timestamp.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub expires_at_ms: Option<u64>,
    /// If this route expires by slot, the last slot at which the route is valid.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub expires_after_slot: Option<u64>,
    /// The number of compute units this transaction is expected to consume, if known.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub compute_units: Option<u64>,
    /// The number of compute units that the server recommends setting for this route. Includes a
    /// buffer to allow for fluctuations in compute unit usage from various protocols as well as
    /// other instructions the user may wish to add, such as tips.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub compute_units_safe: Option<u64>,
    /// Raw transaction to be signed by the user. May be returned instead of instructions and ALTs.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", with = "serde_bytes", default)
    )]
    pub transaction: Option<Vec<u8>>,
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    /// Reference ID for Pyth Express Relay and HashFlow RFQ providers.
    pub reference_id: Option<String>,
}

/// Possible value for a flag in the flags map.
///
/// Only simple values like strings, booleans, integers, and floating point numbers are allowed.
///
/// Values are serialized untagged, e.g. as the inner type.
///
/// Available since: v1.3
#[derive(PartialEq, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(untagged))]
pub enum MetadataValue {
    /// Value contains a single String.
    String(String),
    /// Value contains a single boolean.
    Bool(bool),
    /// Value contains a single integer.
    Int(i64),
    /// Value contains a single floating point number.
    Float(f64),
    /// Array of Metadata values.
    /// Since: v1.7
    Array(Vec<Self>),
    /// Mapping of strings to metadata values.
    /// Since: v1.7
    Map(HashMap<String, Self>),
}

// Custom deserializer using serde-untagged to have better performance than the default untagged
// deserialization method, especially since this is a very simple struct that is very easy to tell
// which variant is needed based on the type.
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for MetadataValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        serde_untagged::UntaggedEnumVisitor::new()
            .string(|string| Ok(Self::String(String::from(string))))
            .i64(|int| Ok(Self::Int(int)))
            .f64(|value| Ok(Self::Float(value)))
            .bool(|value| Ok(Self::Bool(value)))
            .seq(|mut seq| {
                use serde::de::SeqAccess;

                let mut res = Vec::with_capacity(seq.size_hint().unwrap_or(0));
                while let Some(item) = seq.next_element()? {
                    res.push(item);
                }
                Ok(Self::Array(res))
            })
            .map(|mut map| {
                use serde::de::MapAccess;

                let mut res = HashMap::with_capacity(map.size_hint().unwrap_or(0));
                while let Some((key, value)) = map.next_entry()? {
                    res.insert(key, value);
                }

                Ok(Self::Map(res))
            })
            .deserialize(deserializer)
    }
}

impl From<String> for MetadataValue {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}

impl From<bool> for MetadataValue {
    fn from(value: bool) -> Self {
        Self::Bool(value)
    }
}

impl From<i64> for MetadataValue {
    fn from(value: i64) -> Self {
        Self::Int(value)
    }
}

impl From<u32> for MetadataValue {
    fn from(value: u32) -> Self {
        Self::Int(i64::from(value))
    }
}

impl From<i32> for MetadataValue {
    fn from(value: i32) -> Self {
        Self::Int(i64::from(value))
    }
}

impl From<u16> for MetadataValue {
    fn from(value: u16) -> Self {
        Self::Int(i64::from(value))
    }
}

impl From<i16> for MetadataValue {
    fn from(value: i16) -> Self {
        Self::Int(i64::from(value))
    }
}

impl From<u8> for MetadataValue {
    fn from(value: u8) -> Self {
        Self::Int(i64::from(value))
    }
}

impl From<i8> for MetadataValue {
    fn from(value: i8) -> Self {
        Self::Int(i64::from(value))
    }
}

impl From<f64> for MetadataValue {
    fn from(value: f64) -> Self {
        Self::Float(value)
    }
}

impl From<f32> for MetadataValue {
    fn from(value: f32) -> Self {
        Self::Float(f64::from(value))
    }
}

impl From<Vec<MetadataValue>> for MetadataValue {
    fn from(value: Vec<MetadataValue>) -> Self {
        Self::Array(value)
    }
}

impl FromIterator<MetadataValue> for MetadataValue {
    fn from_iter<T: IntoIterator<Item = MetadataValue>>(iter: T) -> Self {
        Self::Array(iter.into_iter().collect())
    }
}

impl From<HashMap<String, MetadataValue>> for MetadataValue {
    fn from(value: HashMap<String, MetadataValue>) -> Self {
        Self::Map(value)
    }
}

impl<S> FromIterator<(S, MetadataValue)> for MetadataValue
where
    S: ToString,
{
    fn from_iter<T: IntoIterator<Item = (S, MetadataValue)>>(iter: T) -> Self {
        let mut res = HashMap::default();
        for (key, value) in iter.into_iter() {
            res.insert(key.to_string(), value);
        }
        Self::Map(res)
    }
}

/// A set of quotes for a swap requested by the user.
///
/// If multiple providers are able to provide quotes, one route per provider will be returned.
#[derive(Debug, Clone, Default, PartialEq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct SwapQuotes {
    /// Identifier for this particular set of quotes.
    pub id: String,
    /// Address of the input mint for this quote.
    pub input_mint: Pubkey,
    /// Address of the output mint for this quote.
    pub output_mint: Pubkey,
    /// What swap mode was used for the quotes.
    pub swap_mode: SwapMode,
    /// Amount that was used for the quotes.
    pub amount: u64,
    /// A mapping of a provider identifier to their quoted route.
    pub quotes: HashMap<String, SwapRoute>,
    /// Optional informational flags attached to the quote.
    ///
    /// Available since: v1.3
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub metadata: Option<HashMap<String, MetadataValue>>,
    /// Contents of Address Lookup Tables used as part of routes, if requested.
    ///
    /// Available since: v1.9
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub alts: Option<Vec<AddressLookupTableAccount>>,
}

/// A pricing request from a user.
///
/// Only one price will be returned for the token pair via Argos.
#[derive(Debug, Clone, Default, PartialEq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct SwapPrice {
    /// Identifier for this particular set of prices.
    pub id: String,
    /// Address of the input mint for this price.
    pub input_mint: Pubkey,
    /// Address of the output mint for this price.
    pub output_mint: Pubkey,
    /// Amount that was used for the price.
    pub amount_in: u64,
    /// The amount out of the best simulated quote for pricing.
    pub amount_out: u64,
}

/// Response to a successful request to start a stream of quotes for a swap.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct QuoteSwapStreamResponse {
    /// The interval, in milliseconds, in which the server will provide updates to the quotes.
    pub interval_ms: u64,
    /// The maximum number of quotes that will be returned per update.
    pub num_quotes: u32,
}

/// Parameters for a `GetInfo` request.
///
/// Currently contains no options, allowing for further expansion and to allow serialization of all
/// request types to be consistent.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetInfoRequest {
    /// Dummy attribute so this will be serialized as expected.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub dummy: Option<bool>,
}

/// Paramters for a [`RequestData::StopStream`] request.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StopStreamRequest {
    /// Identifier of the stream to stop.
    pub id: u32,
}

/// Response to a successful request to stop a data stream.
///
/// Note: If a stream had data already prepared, there may still be a [`StreamData`][streamdata]
/// message sent for the stream before the [`StreamEnd`][streamend] is sent.
///
/// [streamdata]: ServerMessage::StreamData
/// [streamend]: ServerMessage::StreamEnd
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StopStreamResponse {
    /// Identifier of the stream that was stopped.
    pub id: u32,
}

/// Request to retrieve information about known venues for dex aggregator providers.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct GetVenuesRequest {
    /// Whether to include the program ID for each venue.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub include_program_ids: Option<bool>,
}

/// Information about known venues for dex aggregators.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct VenueInfo {
    /// Labels for known venues, used in the `dexes` and `exclude_dexes` swap parameters.
    pub labels: Vec<String>,
    /// Program IDs for each venue, if requested.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub program_ids: Option<Vec<Pubkey>>,
}

/// Request to retrieve information about the enabled quote providers.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct ListProvidersRequest {
    /// If true, will include icon URLs.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub include_icons: Option<bool>,
}

/// Information about a particular provider.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct ProviderInfo {
    /// ID of the provider as returned in quotes and used in the `providers` parameter for
    /// requests.
    pub id: String,
    /// Human-readable name for the provider.
    pub name: String,
    /// What kind of provider this is.
    pub kind: ProviderKind,
    /// URI for a 48x48 pixel icon for the provider, if requested.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub icon_uri_48: Option<String>,
}

/// What kind of quote provider a particular provider is.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ProviderKind {
    /// Provider is an aggregator of decentralized exchanges.
    DexAggregator,
    /// Provider is a Request-For-Quotes provider.
    RFQ,
    /// Catch-all for deserializing additional types added in the future.
    #[cfg_attr(feature = "serde", serde(untagged))]
    Other(String),
}

/// Data for a request from the user sent on the WebSocket.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[allow(clippy::large_enum_variant)]
pub enum RequestData {
    /// Request that the server respond with information on its settings and parameter bounds.
    GetInfo(GetInfoRequest),
    /// User requests a stream of quotes for a swap between two tokens.
    NewSwapQuoteStream(SwapQuoteRequest),
    /// User requests to stop a stream of data.
    StopStream(StopStreamRequest),
    /// User requets information about known venues for dex aggregator providers.
    GetVenues(GetVenuesRequest),
    /// User requests information about enabled quote providers.
    ListProviders(ListProvidersRequest),
    /// User requests the price of a swap directly between two tokens.
    GetSwapPrice(SwapPriceRequest),
    /// Other type of un-handled message type.
    #[cfg(feature = "enum-other")]
    #[cfg_attr(feature = "serde", serde(untagged))]
    Other(rmpv::Value),
}

/// Data for a successful response to a request.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug, PartialEq)]
pub enum ResponseData {
    /// Response for a [`GetInfo`][ResponseData::GetInfo] request.
    GetInfo(ServerInfo),
    /// Response for a [`NewSwapQuoteStream`][RequestData::NewSwapQuoteStream] request.
    NewSwapQuoteStream(QuoteSwapStreamResponse),
    /// Successful response to a [`StopStream`][RequestData::StopStream] request.
    StreamStopped(StopStreamResponse),
    /// Successful response to a [`GetVenues`][RequestData::GetVenues] request.
    GetVenues(VenueInfo),
    /// Successful response to a [`ListProviders`][RequestData::ListProviders] request.
    ListProviders(Vec<ProviderInfo>),
    /// Successful response to a [`GetPrice`][RequestData::GetSwapPrice] request.
    GetSwapPrice(SwapPrice),
    /// Other type of un-handled message type.
    #[cfg(feature = "enum-other")]
    #[cfg_attr(feature = "serde", serde(untagged))]
    Other(rmpv::Value),
}

/// A request sent by the client.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ClientRequest {
    /// Identifier for the request.
    ///
    /// The response(s) will contain the same ID that is specified here so that the client can
    /// correlate the response(s) with the request.
    pub id: u32,
    /// Data for the request.
    pub data: RequestData,
}

/// Notification that a new stream has been started by the server.
///
/// Returned as part of a successful response so that the client can allocate resources for the
/// stream.
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamStart {
    /// ID of the new stream.
    ///
    /// This ID will be present in [`StreamData`] and [`StreamEnd`] messages for this stream.
    pub id: u32,
    /// The type of data that will be sent in this stream.
    pub data_type: StreamDataType,
}

/// Data packet for a stream.
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
#[derive(Debug, Clone, PartialEq)]
pub struct StreamData {
    /// ID of the stream.
    pub id: u32,
    /// Sequence number of this data packet.
    pub seq: u32,
    /// Data payload.
    pub payload: StreamDataPayload,
}

/// Notification that a stream has closed and will no longer receive data.
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamEnd {
    /// ID of the stream that has ended.
    pub id: u32,
    /// If the stream ended due to an error, contains the code denoting the specific error that
    /// occurred.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub error_code: Option<u32>,
    /// If the stream ended due to an error, contains a message explaining what happened.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub error_message: Option<String>,
}

/// A response to a successful request.
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
#[derive(Debug, Clone, PartialEq)]
pub struct ResponseSuccess {
    /// Identifier of the request that triggered this response.
    pub request_id: u32,
    /// The response data.
    pub data: ResponseData,
    /// If this request starts a new stream, contains information about the stream ID and its data
    /// type.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Option::is_none", default)
    )]
    pub stream: Option<StreamStart>,
}

/// A response to a request that resulted in an error.
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResponseError {
    /// Identifier of the request that triggered this response.
    pub request_id: u32,
    /// A numeric error code representing the specific error that occurred.
    pub code: u32,
    /// A message describing the error.
    pub message: String,
}

/// Types of data that can be streamed to the client.
///
/// Included in a [`StreamStart`] message so that the client may prepare for the incoming data.
#[derive(PartialEq, Eq, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum StreamDataType {
    /// Stream contains [`SwapQuotes`](struct@SwapQuotes) as the data values.
    SwapQuotes,
    /// Other type added in a future version.
    #[cfg(feature = "enum-other")]
    #[cfg_attr(feature = "serde", serde(untagged))]
    Other(String),
}

/// Payload for a [`StreamData`] message.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum StreamDataPayload {
    /// Payload contains a set of quotes for a swap request.
    SwapQuotes(SwapQuotes),
    /// Other type of un-handled message type.
    #[cfg(feature = "enum-other")]
    #[cfg_attr(feature = "serde", serde(untagged))]
    Other(rmpv::Value),
}

/// A message sent by the server to the client.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum ServerMessage {
    /// Successful response to a request, which may optionally start a stream.
    Response(ResponseSuccess),
    /// An error response to a request.
    Error(ResponseError),
    /// Data for a stream.
    StreamData(StreamData),
    /// Notification that a stream has ended.
    StreamEnd(StreamEnd),
    /// Other type of un-handled message type.
    #[cfg(feature = "enum-other")]
    #[cfg_attr(feature = "serde", serde(untagged))]
    Other(rmpv::Value),
}

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

    use hex_literal::hex;
    use rmp_serde::{decode::Error as DecError, encode::Error as EncError};
    use rmpv::Value;

    const WSOL_ADDR: Pubkey = Pubkey::from_str_const("So11111111111111111111111111111111111111112");
    const USDC_ADDR: Pubkey =
        Pubkey::from_str_const("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
    const METEORA_DLMM_WSOL_USDC: Pubkey =
        Pubkey::from_str_const("2kSaQT7BcB92uVeDtmxsDJm9fbGxupf64KgtsF5xzLhf");

    #[test]
    fn test_encode_version_info() -> Result<(), EncError> {
        let info = VersionInfo::new(1, 2, 3);
        let expected = hex!("83a56d616a6f7201a56d696e6f7202a5706174636803");
        let encoded = rmp_serde::to_vec_named(&info)?;
        assert_eq!(encoded, expected);
        Ok(())
    }

    #[test]
    fn test_decode_version_info() -> Result<(), DecError> {
        let info = VersionInfo::new(1, 2, 3);
        let data = hex!("83a56d616a6f7201a56d696e6f7202a5706174636803");
        let decoded = rmp_serde::from_slice::<VersionInfo>(&data)?;
        assert_eq!(decoded, info);
        Ok(())
    }

    #[test]
    fn test_encode_swap_mode() -> Result<(), EncError> {
        let exact_in_data = hex!("a74578616374496e");
        let exact_out_data = hex!("a845786163744f7574");

        assert_eq!(rmp_serde::to_vec_named(&SwapMode::ExactIn)?, &exact_in_data);
        assert_eq!(
            rmp_serde::to_vec_named(&SwapMode::ExactOut)?,
            &exact_out_data
        );

        Ok(())
    }

    #[test]
    fn test_decode_swap_mode() -> Result<(), DecError> {
        let exact_in_data = hex!("a74578616374496e");
        let exact_out_data = hex!("a845786163744f7574");

        assert_eq!(
            rmp_serde::from_slice::<SwapMode>(&exact_in_data)?,
            SwapMode::ExactIn
        );
        assert_eq!(
            rmp_serde::from_slice::<SwapMode>(&exact_out_data)?,
            SwapMode::ExactOut
        );

        Ok(())
    }

    #[test]
    fn test_encode_swap_params() -> Result<(), EncError> {
        let data = hex!("83a9696e7075744d696e74c420069b8857feab8184fb687f634618c035dac439dc1aeb3b5598a0f00000000001aa6f75747075744d696e74c420c6fa7af3bedbad3a3d65f36aabc97431b1bbe4c2d2f6e0e47ca60203452f5d61a6616d6f756e74ce3b9aca00");
        let info = SwapParams {
            input_mint: WSOL_ADDR,
            output_mint: USDC_ADDR,
            amount: 1_000_000_000,
            ..Default::default()
        };
        let encoded = rmp_serde::to_vec_named(&info)?;
        assert_eq!(encoded, data);

        Ok(())
    }

    #[test]
    fn test_decode_swap_params() -> Result<(), DecError> {
        let data = hex!("83a9696e7075744d696e74c420069b8857feab8184fb687f634618c035dac439dc1aeb3b5598a0f00000000001aa6f75747075744d696e74c420c6fa7af3bedbad3a3d65f36aabc97431b1bbe4c2d2f6e0e47ca60203452f5d61a6616d6f756e74ce3b9aca00");
        let info = SwapParams {
            input_mint: WSOL_ADDR,
            output_mint: USDC_ADDR,
            amount: 1_000_000_000,
            ..Default::default()
        };
        let decoded: SwapParams = rmp_serde::from_slice(&data)?;
        assert_eq!(decoded, info);

        Ok(())
    }

    #[test]
    fn test_encode_swap_settings() -> Result<(), EncError> {
        let expected_rmp = Value::Map(vec![
            (
                Value::from("slippageBps"),
                Value::Map(vec![
                    (Value::from("min"), Value::from(0u16)),
                    (Value::from("max"), Value::from(10_000u16)),
                    (Value::from("default"), Value::from(100u16)),
                ]),
            ),
            (Value::from("onlyDirectRoutes"), Value::from(false)),
            (Value::from("addSizeConstraint"), Value::from(true)),
            (Value::from("sizeConstraint"), Value::from(1232)),
        ]);
        let data = rmp_serde::to_vec_named(&expected_rmp).expect("expected rmp should encode");
        let info = SwapSettings {
            slippage_bps: BoundedValueWithDefault {
                min: 0,
                max: 10_000,
                default: 100,
            },
            only_direct_routes: false,
            add_size_constraint: true,
            size_constraint: 1232,
        };
        let encoded = rmp_serde::to_vec_named(&info)?;
        assert_eq!(encoded, data);

        Ok(())
    }

    #[test]
    fn test_decode_swap_settings() -> Result<(), DecError> {
        let expected_rmp = Value::Map(vec![
            (
                Value::from("slippageBps"),
                Value::Map(vec![
                    (Value::from("min"), Value::from(0u16)),
                    (Value::from("max"), Value::from(10_000u16)),
                    (Value::from("default"), Value::from(100u16)),
                ]),
            ),
            (Value::from("onlyDirectRoutes"), Value::from(false)),
            (Value::from("addSizeConstraint"), Value::from(true)),
            (Value::from("sizeConstraint"), Value::from(1232)),
        ]);
        let data = rmp_serde::to_vec_named(&expected_rmp).expect("expected rmp should encode");
        let info = SwapSettings {
            slippage_bps: BoundedValueWithDefault {
                min: 0,
                max: 10_000,
                default: 100,
            },
            only_direct_routes: false,
            add_size_constraint: true,
            size_constraint: 1232,
        };
        let decoded: SwapSettings = rmp_serde::from_slice(&data)?;
        assert_eq!(decoded, info);

        Ok(())
    }

    #[test]
    fn test_encode_quote_update_params() -> Result<(), EncError> {
        let data = hex!("81aa696e74657276616c4d73cd03e8");
        let info = QuoteUpdateParams {
            interval_ms: Some(1000),
            ..Default::default()
        };
        let encoded = rmp_serde::to_vec_named(&info)?;
        assert_eq!(encoded, data);

        let empty_data = hex!("80");
        let info = QuoteUpdateParams {
            interval_ms: None,
            ..Default::default()
        };
        let encoded = rmp_serde::to_vec_named(&info)?;
        assert_eq!(encoded, empty_data);

        Ok(())
    }

    #[test]
    fn test_decode_quote_update_params() -> Result<(), DecError> {
        let data = hex!("81aa696e74657276616c4d73cd03e8");
        let info = QuoteUpdateParams {
            interval_ms: Some(1000),
            ..Default::default()
        };
        let decoded: QuoteUpdateParams = rmp_serde::from_slice(&data)?;
        assert_eq!(decoded, info);

        let empty_data = hex!("80");
        let info = QuoteUpdateParams {
            interval_ms: None,
            ..Default::default()
        };
        let decoded: QuoteUpdateParams = rmp_serde::from_slice(&empty_data)?;
        assert_eq!(decoded, info);

        Ok(())
    }

    #[test]
    fn test_encode_transaction_params() -> Result<(), EncError> {
        let data = hex!("82ad757365725075626c69634b6579c42019fc949cf6d288d076e39f923bf6f1b45da023310e606afc40cc080d5b25983ab6636c6f7365496e707574546f6b656e4163636f756e74c3");
        let info = TransactionParams {
            user_public_key: METEORA_DLMM_WSOL_USDC,
            close_input_token_account: Some(true),
            create_output_token_account: None,
            ..Default::default()
        };
        let encoded = rmp_serde::to_vec_named(&info)?;
        assert_eq!(encoded, data);

        Ok(())
    }

    #[test]
    fn test_decode_transaction_params() -> Result<(), DecError> {
        let data = hex!("82ad757365725075626c69634b6579c42019fc949cf6d288d076e39f923bf6f1b45da023310e606afc40cc080d5b25983ab6636c6f7365496e707574546f6b656e4163636f756e74c3");
        let info = TransactionParams {
            user_public_key: METEORA_DLMM_WSOL_USDC,
            close_input_token_account: Some(true),
            create_output_token_account: None,
            ..Default::default()
        };
        let decoded: TransactionParams = rmp_serde::from_slice(&data)?;
        assert_eq!(decoded, info);

        Ok(())
    }

    #[test]
    fn test_encode_transaction_settings() -> Result<(), EncError> {
        let data = hex!("82b6636c6f7365496e707574546f6b656e4163636f756e74c2b86372656174654f7574707574546f6b656e4163636f756e74c3");
        let info = TransactionSettings {
            close_input_token_account: false,
            create_output_token_account: true,
        };
        let encoded = rmp_serde::to_vec_named(&info)?;
        assert_eq!(encoded, data);

        Ok(())
    }

    #[test]
    fn test_decode_transaction_settings() -> Result<(), DecError> {
        let data = hex!("82b6636c6f7365496e707574546f6b656e4163636f756e74c2b86372656174654f7574707574546f6b656e4163636f756e74c3");
        let info = TransactionSettings {
            close_input_token_account: false,
            create_output_token_account: true,
        };
        let decoded: TransactionSettings = rmp_serde::from_slice(&data)?;
        assert_eq!(decoded, info);

        Ok(())
    }

    #[test]
    fn test_encode_route_plan_step() -> Result<(), EncError> {
        let data = hex!("88a6616d6d4b6579c42019fc949cf6d288d076e39f923bf6f1b45da023310e606afc40cc080d5b25983aa56c6162656cac4d6574656f726120444c4d4da9696e7075744d696e74c420069b8857feab8184fb687f634618c035dac439dc1aeb3b5598a0f00000000001aa6f75747075744d696e74c420c6fa7af3bedbad3a3d65f36aabc97431b1bbe4c2d2f6e0e47ca60203452f5d61a8696e416d6f756e74ce3b9aca00a96f7574416d6f756e74ce08d0ed70a8616c6c6f63507062ce3b9aca00ab636f6e74657874536c6f74ce00bc614e");
        let step = RoutePlanStep {
            amm_key: METEORA_DLMM_WSOL_USDC,
            label: "Meteora DLMM".into(),
            input_mint: WSOL_ADDR,
            output_mint: USDC_ADDR,
            in_amount: 1_000_000_000, // 1 SOL
            out_amount: 147_910_000,  // 147.91 USDC
            alloc_ppb: 1_000_000_000, // 100%
            fee_mint: None,
            fee_amount: None,
            context_slot: Some(12345678),
        };

        let encoded = rmp_serde::to_vec_named(&step)?;
        assert_eq!(encoded, data);

        Ok(())
    }

    #[test]
    fn test_decode_route_plan_step() -> Result<(), DecError> {
        let data = hex!("88a6616d6d4b6579c42019fc949cf6d288d076e39f923bf6f1b45da023310e606afc40cc080d5b25983aa56c6162656cac4d6574656f726120444c4d4da9696e7075744d696e74c420069b8857feab8184fb687f634618c035dac439dc1aeb3b5598a0f00000000001aa6f75747075744d696e74c420c6fa7af3bedbad3a3d65f36aabc97431b1bbe4c2d2f6e0e47ca60203452f5d61a8696e416d6f756e74ce3b9aca00a96f7574416d6f756e74ce08d0ed70a8616c6c6f63507062ce3b9aca00ab636f6e74657874536c6f74ce00bc614e");
        let step = RoutePlanStep {
            amm_key: METEORA_DLMM_WSOL_USDC,
            label: "Meteora DLMM".into(),
            input_mint: WSOL_ADDR,
            output_mint: USDC_ADDR,
            in_amount: 1_000_000_000, // 1 SOL
            out_amount: 147_910_000,  // 147.91 USDC
            alloc_ppb: 1_000_000_000, // 100%
            fee_mint: None,
            fee_amount: None,
            context_slot: Some(12345678),
        };

        let decoded: RoutePlanStep = rmp_serde::from_slice(&data)?;
        assert_eq!(decoded, step);

        Ok(())
    }

    #[test]
    fn test_encode_request_data() -> Result<(), EncError> {
        // GetInfo
        let data = hex!("81a7476574496e666f80");
        let req = RequestData::GetInfo(GetInfoRequest { dummy: None });

        let encoded = rmp_serde::to_vec_named(&req)?;
        assert_eq!(encoded, data);

        Ok(())
    }

    #[test]
    fn test_decode_request_data() -> Result<(), DecError> {
        let data = hex!("81a7476574496e666f80");
        let req = RequestData::GetInfo(GetInfoRequest { dummy: None });

        let decoded: RequestData = rmp_serde::from_slice(&data)?;
        assert_eq!(decoded, req);

        Ok(())
    }

    #[test]
    fn test_encode_server_message() -> Result<(), EncError> {
        let data = hex!("81a953747265616d456e6483a26964cd3039a96572726f72436f6465cd01f8ac6572726f724d657373616765bb626f622074726970706564206f7665722074686520726f75746572");
        let message = ServerMessage::StreamEnd(StreamEnd {
            id: 12345,
            error_code: Some(504),
            error_message: Some("bob tripped over the router".into()),
        });

        let encoded = rmp_serde::to_vec_named(&message)?;
        assert_eq!(encoded, data);

        Ok(())
    }

    #[test]
    fn test_decode_server_message() -> Result<(), DecError> {
        let data = hex!("81a953747265616d456e6483a26964cd3039a96572726f72436f6465cd01f8ac6572726f724d657373616765bb626f622074726970706564206f7665722074686520726f75746572");
        let message = ServerMessage::StreamEnd(StreamEnd {
            id: 12345,
            error_code: Some(504),
            error_message: Some("bob tripped over the router".into()),
        });

        let decoded: ServerMessage = rmp_serde::from_slice(&data)?;
        assert_eq!(decoded, message);
        Ok(())
    }

    #[test]
    fn test_other_server_message() -> Result<(), DecError> {
        let unhandled = Value::Map(vec![(
            Value::from("SomeOtherWeirdMessageType"),
            Value::from(1),
        )]);
        let unhandled_data = rmp_serde::to_vec_named(&unhandled).expect("should encode");
        let decoded: ServerMessage = rmp_serde::from_slice(&unhandled_data)?;
        let unhandled_sm = ServerMessage::Other(unhandled);
        assert_eq!(decoded, unhandled_sm);
        Ok(())
    }

    #[test]
    fn test_other_request_data() -> Result<(), DecError> {
        // client request
        let bad_request_data = Value::Map(vec![(
            Value::from("BadDataType"),
            Value::Map(vec![(Value::from("foo"), Value::from("bar"))]),
        )]);
        let unhandled = Value::Map(vec![
            (Value::from("id"), Value::from(1)),
            (Value::from("data"), bad_request_data.clone()),
        ]);
        let unhandled_data = rmp_serde::to_vec_named(&unhandled).expect("should encode");
        let decoded: ClientRequest = rmp_serde::from_slice(&unhandled_data)?;
        let unhandled_msg = ClientRequest {
            id: 1,
            data: RequestData::Other(bad_request_data),
        };
        assert_eq!(decoded, unhandled_msg);
        Ok(())
    }

    #[test]
    fn test_swap_params_mesh_size_roundtrip() {
        let params = SwapParams {
            input_mint: WSOL_ADDR,
            output_mint: USDC_ADDR,
            amount: 1_000_000_000,
            mesh_size: Some(4),
            ..Default::default()
        };
        let json = serde_json::to_value(&params).unwrap();
        assert_eq!(json["meshSize"], serde_json::json!(4));
        let decoded: SwapParams = serde_json::from_value(json).unwrap();
        assert_eq!(decoded.mesh_size, Some(4));

        // Absent: decodes to None, and is omitted when serializing.
        let omitted = serde_json::to_value(&SwapParams {
            input_mint: WSOL_ADDR,
            output_mint: USDC_ADDR,
            amount: 1,
            ..Default::default()
        })
        .unwrap();
        assert!(omitted.get("meshSize").is_none());
        let decoded: SwapParams = serde_json::from_value(omitted).unwrap();
        assert_eq!(decoded.mesh_size, None);
    }

    #[test]
    fn test_swap_params_no_vote_accounts_roundtrip() {
        // Present and true: serializes to the camelCase `noVoteAccounts` key.
        let params = SwapParams {
            input_mint: WSOL_ADDR,
            output_mint: USDC_ADDR,
            amount: 1_000_000_000,
            no_vote_accounts: Some(true),
            ..Default::default()
        };
        let json = serde_json::to_value(&params).unwrap();
        assert_eq!(json["noVoteAccounts"], serde_json::json!(true));
        let decoded: SwapParams = serde_json::from_value(json).unwrap();
        assert_eq!(decoded.no_vote_accounts, Some(true));

        // Absent: decodes to None (default), and is omitted when serializing.
        let decoded: SwapParams = serde_json::from_str(
            r#"{"inputMint":"So11111111111111111111111111111111111111112","outputMint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v","amount":1000000000}"#,
        )
        .unwrap();
        assert_eq!(decoded.no_vote_accounts, None);

        let omitted = serde_json::to_value(&SwapParams {
            input_mint: WSOL_ADDR,
            output_mint: USDC_ADDR,
            amount: 1,
            ..Default::default()
        })
        .unwrap();
        assert!(omitted.get("noVoteAccounts").is_none());
    }

    #[test]
    fn test_metadata_map() -> Result<(), DecError> {
        let mut metadata_map = HashMap::with_capacity(4);
        metadata_map.insert(
            String::from("StringFlag"),
            MetadataValue::String(String::from("StringValue")),
        );
        metadata_map.insert(String::from("IntFlag"), MetadataValue::Int(1234));
        metadata_map.insert(String::from("BoolFlag"), MetadataValue::Bool(true));
        metadata_map.insert(String::from("FloatFlag"), MetadataValue::Float(12.5));
        metadata_map.insert(
            String::from("ArrayFlag"),
            vec![1.into(), 2.into(), 3.into()].into(),
        );
        metadata_map.insert(
            String::from("MapFlag"),
            MetadataValue::from_iter([
                ("Key1", MetadataValue::Int(5)),
                ("Key2", MetadataValue::Bool(false)),
            ]),
        );
        let encoded = rmp_serde::to_vec_named(&metadata_map).expect("should encode");
        let decoded: HashMap<String, MetadataValue> = rmp_serde::from_slice(&encoded)?;

        assert_eq!(decoded, metadata_map);

        Ok(())
    }
}

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

    #[test]
    fn transaction_format_defaults_to_v0() {
        assert_eq!(TransactionFormat::default(), TransactionFormat::V0);
    }

    #[test]
    fn transaction_format_round_trips_through_u8() {
        assert_eq!(u8::from(TransactionFormat::V0), 0);
        assert_eq!(u8::from(TransactionFormat::V1), 1);
        assert_eq!(TransactionFormat::try_from(0u8), Ok(TransactionFormat::V0));
        assert_eq!(TransactionFormat::try_from(1u8), Ok(TransactionFormat::V1));
        assert_eq!(TransactionFormat::try_from(2u8), Err(2u8));
    }

    /// An absent field must mean V0, so existing clients are unaffected.
    #[test]
    fn absent_transaction_format_is_none() {
        let params = TransactionParams::default();
        assert!(params.transaction_format.is_none());
        assert_eq!(
            params.transaction_format.unwrap_or_default(),
            TransactionFormat::V0
        );
    }

    #[test]
    fn absent_transaction_config_is_none() {
        let template = TransactionTemplate::default();
        assert!(template.transaction_config.is_none());
    }

    #[test]
    fn transaction_config_params_default_is_all_none() {
        let c = TransactionConfigParams::default();
        assert!(c.priority_fee.is_none());
        assert!(c.compute_unit_limit.is_none());
        assert!(c.loaded_accounts_data_size_limit.is_none());
        assert!(c.heap_size.is_none());
    }

    /// `TransactionTemplate::transaction_config` crosses apollo -> CART as
    /// MessagePack under the renamed wire key `"c"`. If this key fails to
    /// round-trip, the config arrives as `None` on the other side and the
    /// transaction is sized against the wrong config-byte count -- the exact
    /// failure this feature exists to prevent.
    #[test]
    fn transaction_config_round_trips_through_messagepack_as_short_key_c() {
        let config = TransactionConfigParams {
            priority_fee: Some(12_345),
            compute_unit_limit: Some(600_000),
            loaded_accounts_data_size_limit: Some(4_194_304),
            heap_size: Some(32 * 1024),
        };
        let template = TransactionTemplate {
            instructions: Vec::new(),
            alts: Vec::new(),
            account_metas: Vec::new(),
            transaction_config: Some(config),
        };

        let encoded =
            rmp_serde::to_vec_named(&template).expect("template should encode to messagepack");

        // The config must survive the round trip intact, field for field.
        let decoded: TransactionTemplate =
            rmp_serde::from_slice(&encoded).expect("template should decode from messagepack");
        assert_eq!(decoded, template);
        assert_eq!(decoded.transaction_config, Some(config));

        // The wire key must actually be the renamed short key "c", not the
        // Rust field name -- decode generically and inspect the map.
        let generic: rmpv::Value =
            rmp_serde::from_slice(&encoded).expect("template should decode as generic msgpack");
        let top_level = generic
            .as_map()
            .expect("a TransactionTemplate must encode as a msgpack map");
        let config_value = top_level
            .iter()
            .find(|(k, _)| k.as_str() == Some("c"))
            .map(|(_, v)| v)
            .expect("transaction_config must be encoded under the short key \"c\"");
        let config_map = config_value
            .as_map()
            .expect("transaction_config must encode as a msgpack map");
        assert!(
            config_map
                .iter()
                .any(|(k, _)| k.as_str() == Some("priorityFee")),
            "TransactionConfigParams fields must keep their camelCase wire names under \"c\""
        );
    }

    /// `skip_serializing_if` on `transaction_config` must actually omit the
    /// key when the config is absent, not encode it as an explicit nil --
    /// otherwise every non-V1 request would carry a wasted "c" entry.
    #[test]
    fn absent_transaction_config_is_omitted_from_messagepack() {
        let template = TransactionTemplate {
            transaction_config: None,
            ..Default::default()
        };

        let encoded =
            rmp_serde::to_vec_named(&template).expect("template should encode to messagepack");

        let decoded: TransactionTemplate =
            rmp_serde::from_slice(&encoded).expect("template should decode from messagepack");
        assert!(decoded.transaction_config.is_none());

        let generic: rmpv::Value =
            rmp_serde::from_slice(&encoded).expect("template should decode as generic msgpack");
        let top_level = generic
            .as_map()
            .expect("a TransactionTemplate must encode as a msgpack map");
        assert!(
            !top_level.iter().any(|(k, _)| k.as_str() == Some("c")),
            "\"c\" must be omitted entirely when transaction_config is None, found: {top_level:?}"
        );
    }
}