Skip to main content

titan_api_types/ws/
v1.rs

1//! Types and constants for version 1 of the Titan WebSocket API.
2//!
3//! Messages sent across the WebSocket connection are expected to be encoded using [MessagePack],
4//! along with optional compression. Whether compression is enabled and which algorithm is used is
5//! negotiated via the [`Sec-WebSocket-Protocol`][sec-ws-proto] header during the WebSocket handshake using the
6//! various subprotocol constants defined in this module.
7//!
8//! Structs are encoded with field names converted to `camelCase` except where otherwise specified.
9//! Specifically, many commonly-used types such as [`crate::common::AccountMeta`] have encodings with
10//! shorter field names to save space.
11//!
12//! For optional fields in structs, if the value is not set, it should be skipped while serializing
13//! to save space.
14//!
15//! Enumerations are encoded depending on the type of enumeration.
16//! Simple enumerations are encoded as their underlying values. The enumeration definition will
17//! specify exactly what this is.
18//!
19//! Complex enumerations (e.g. those whose values have parameters) are encoded as single-entry maps,
20//! where the key is a string with the name of the enumeration kind and the value is the encoded
21//! parameter(s). If the enumeration has a single parameter, the value will be that parameter's
22//! encoding. If the enumeration has multiple parameters, the value will be an array containing the
23//! encoded parameters.
24//!
25//! [MessagePack]: https://msgpack.org/index.html
26//! [sec-ws-proto]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-WebSocket-Protocol
27
28use std::collections::HashMap;
29
30use crate::common::{
31    instruction::AddressLookupTableAccount, AccountMeta, BoundedValueWithDefault, Instruction,
32    Pubkey,
33};
34
35/// Major version number of this API.
36pub const VERSION_MAJOR: u16 = 1;
37/// Minor version number of this API.
38///
39/// Incremented when non-breaking changes are made to the type definitions, such as adding new
40/// optional fields to request types or new fields to response types that are not crucial for the
41/// client to understand.
42pub const VERSION_MINOR: u16 = 10;
43
44/// Base subprotocol identifier for this version of the WebSocket API.
45///
46/// For this version of the protocol, all messages are encoded via [MessagePack] with no
47/// compression. Compression may be separately provided via WebSocket protocol extensions if
48/// supported by both the client and server.
49///
50/// To be used with the [`Sec-WebSocket-Protocol`] header for sub-protocol negotiation.
51///
52/// [MessagePack]: https://msgpack.org/index.html
53/// ['Sec-WebSocket-Protocol`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-WebSocket-Protocol
54pub const WEBSOCKET_SUBPROTO_BASE: &str = "v1.api.titan.ag";
55
56/// Subprotocol identifier for this version of the WebSocket API with [zstd] compression.
57///
58/// If this protocol is selected, after encoding messages using [MessagePack], messages must be
59/// compressed via [zstd] with compression level 3.
60///
61/// [MessagePack]: https://msgpack.org/index.html
62/// [zstd]: https://github.com/facebook/zstd
63pub const WEBSOCKET_SUBPROTO_ZSTD: &str = "v1.api.titan.ag+zstd";
64
65/// Subprotocol identifier for this version of the WebSocket API with [brotli] compression.
66///
67/// If this protocol is selected, after encoding messages using [MessagePack], messages must be
68/// compressed via [brotli] with quality level 11.
69///
70/// [MessagePack]: https://msgpack.org/index.html
71/// [brotli]: https://github.com/google/brotli
72pub const WEBSOCKET_SUBPROTO_BROTLI: &str = "v1.api.titan.ag+br";
73
74/// Subprotocol identifier for this version of the WebSocket API with [gzip] compression.
75///
76/// If this protocol is selected, after encoding messages using [MessagePack], messages must be
77/// compressed via [gzip].
78///
79/// [MessagePack]: https://msgpack.org/index.html
80/// [gzip]: https://www.gzip.org/
81pub const WEBSOCKET_SUBPROTO_GZIP: &str = "v1.api.titan.ag+gzip";
82
83/// Array containing all the valid WeBSocket subprotocol identifiers for this version of the API.
84///
85/// Protocols are ordered roughly in descending order of preference in terms of compression ratio
86/// and speed.
87pub const WEBSOCKET_SUBPROTOCOLS: [&str; 4] = [
88    WEBSOCKET_SUBPROTO_ZSTD,
89    WEBSOCKET_SUBPROTO_BROTLI,
90    WEBSOCKET_SUBPROTO_GZIP,
91    WEBSOCKET_SUBPROTO_BASE,
92];
93
94/// Information about the version of the protocol being spoken by the server.
95///
96/// Only changes to the major and minor versions affect the format of data sent across the network.
97/// Patch version increases note that internal logic changes in the server have occurred that do
98/// not otherwise impact the API (e.g. bug fixes).
99#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
100#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
101pub struct VersionInfo {
102    /// Major version number.
103    ///
104    /// Incremented when the data format changes in backwards-incompatible ways.
105    pub major: u16,
106    /// Minor version number.
107    ///
108    /// Incremented when the data format changes in backwards-compatible ways.
109    pub minor: u16,
110    /// Patch version number.
111    ///
112    /// Incremented when changes to the protocol that do not affect the data format have occurred.
113    /// Primarily informational.
114    pub patch: u16,
115}
116
117impl VersionInfo {
118    /// Constructs a new `VersionInfo` from its parts.
119    pub const fn new(major: u16, minor: u16, patch: u16) -> Self {
120        Self {
121            major,
122            minor,
123            patch,
124        }
125    }
126
127    /// Computes a serial number representation of this version.
128    ///
129    /// This is constructed in such a way that comparisons of serial numbers respect the priority
130    /// of major, minor, and patch versions.
131    pub const fn serial(&self) -> u64 {
132        ((self.major as u64) << 32) + ((self.minor as u64) << 16) + (self.minor as u64)
133    }
134}
135
136/// Type of swap to perform.
137///
138/// Affects how the swap `amount` is handled.
139///
140/// Values are encoded as strings exactly matching the names.
141#[derive(Default, PartialEq, Eq, Clone, Copy, Debug)]
142#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
143pub enum SwapMode {
144    /// Swap amount is the number of input tokens that should be swapped.
145    #[default]
146    ExactIn,
147    /// Swap amount is the number of output tokens that should be received.
148    ExactOut,
149}
150
151/// Which version of the swap routing engine to use.
152///
153/// Currently defaults to [`V2`](SwapVersion::V2). V2 will be deprecated in a future release, at
154/// which point the default will switch to [`V3`](SwapVersion::V3). After the deprecation date,
155/// V2 will no longer receive technical support and clients should migrate to V3.
156///
157/// Values are encoded as their `u8` discriminant: `2` for V2, `3` for V3.
158#[derive(Default, PartialEq, Eq, Clone, Copy, Debug)]
159#[cfg_attr(
160    feature = "serde",
161    derive(serde::Serialize, serde::Deserialize),
162    serde(into = "u8", try_from = "u8")
163)]
164#[repr(u8)]
165pub enum SwapVersion {
166    /// Version 2 of the swap routing engine (current default, will be deprecated).
167    #[default]
168    V2 = 2,
169    /// Version 3 of the swap routing engine.
170    V3 = 3,
171}
172
173impl From<SwapVersion> for u8 {
174    fn from(v: SwapVersion) -> u8 {
175        v as u8
176    }
177}
178
179impl TryFrom<u8> for SwapVersion {
180    type Error = u8;
181
182    fn try_from(v: u8) -> Result<Self, Self::Error> {
183        match v {
184            2 => Ok(Self::V2),
185            3 => Ok(Self::V3),
186            other => Err(other),
187        }
188    }
189}
190
191/// Which transaction wire format the client intends to build.
192///
193/// Orthogonal to [`SwapVersion`]: this selects the transaction encoding, that
194/// selects the Titan swap instruction set. Defaults to [`V0`](TransactionFormat::V0),
195/// so clients that do not set it are unaffected.
196///
197/// [`V1`](TransactionFormat::V1) is the Agave 4.2 / SIMD-0385 format: 4096
198/// bytes, no address lookup tables. It is not supported with
199/// [`SwapVersion::V2`].
200///
201/// Values are encoded as their `u8` discriminant: `0` for V0, `1` for V1.
202#[derive(Default, PartialEq, Eq, Clone, Copy, Debug)]
203#[cfg_attr(
204    feature = "serde",
205    derive(serde::Serialize, serde::Deserialize),
206    serde(into = "u8", try_from = "u8")
207)]
208#[repr(u8)]
209pub enum TransactionFormat {
210    /// Versioned (v0) transaction. Address lookup tables permitted.
211    #[default]
212    V0 = 0,
213    /// SIMD-0385 transaction. 4096 bytes, no address lookup tables.
214    V1 = 1,
215}
216
217impl From<TransactionFormat> for u8 {
218    fn from(v: TransactionFormat) -> u8 {
219        v as u8
220    }
221}
222
223impl TryFrom<u8> for TransactionFormat {
224    type Error = u8;
225
226    fn try_from(v: u8) -> Result<Self, Self::Error> {
227        match v {
228            0 => Ok(Self::V0),
229            1 => Ok(Self::V1),
230            other => Err(other),
231        }
232    }
233}
234
235/// Transaction-level configuration for [`TransactionFormat::V1`].
236///
237/// V1 carries priority fee and compute budget in the transaction envelope
238/// rather than in ComputeBudget instructions, which V1 ignores for
239/// configuration. These values are not expressible as instructions, so a
240/// [`TransactionTemplate`] cannot describe them without this struct — and a
241/// transaction whose config we cannot see cannot be sized correctly.
242///
243/// Required when [`TransactionFormat::V1`] is used with a template.
244#[derive(Default, PartialEq, Eq, Clone, Copy, Debug)]
245#[cfg_attr(
246    feature = "serde",
247    derive(serde::Serialize, serde::Deserialize),
248    serde(rename_all = "camelCase")
249)]
250pub struct TransactionConfigParams {
251    /// Priority fee in lamports.
252    #[cfg_attr(
253        feature = "serde",
254        serde(skip_serializing_if = "Option::is_none", default)
255    )]
256    pub priority_fee: Option<u64>,
257    /// Maximum compute units.
258    #[cfg_attr(
259        feature = "serde",
260        serde(skip_serializing_if = "Option::is_none", default)
261    )]
262    pub compute_unit_limit: Option<u32>,
263    /// Maximum bytes of account data that may be loaded.
264    #[cfg_attr(
265        feature = "serde",
266        serde(skip_serializing_if = "Option::is_none", default)
267    )]
268    pub loaded_accounts_data_size_limit: Option<u32>,
269    /// Requested heap size in bytes. Must be a multiple of 1024.
270    #[cfg_attr(
271        feature = "serde",
272        serde(skip_serializing_if = "Option::is_none", default)
273    )]
274    pub heap_size: Option<u32>,
275}
276
277/// A templated route which Titan can use when determining eligible routes.
278/// If possible, Titan will insert at the specified index a swap that meets
279/// Solana's sizing requirements. This is incompatible with the options,
280/// `accounts_limit_total`, `accounts_limit_writable` and `size_constraint`.
281/// An error will be returned if they are both specified.
282#[derive(Default, PartialEq, Eq, Clone, Debug)]
283#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
284pub struct TransactionTemplate {
285    /// A vector of instructions. It is assumed that you have included
286    /// the input mint and output mint account creation/deletion when necessary.
287    #[cfg_attr(feature = "serde", serde(rename = "i"))]
288    pub instructions: Vec<Instruction>,
289    /// Address lookup tables (ATLs) used in the instruction. Should be provided in the same order that
290    /// you will use the address lookup tables when compiling the message. This is because Solana
291    /// uses the ALTs in a greedy fashion and their effect is dependent on their ordering . Any ALTs used
292    /// by Titan will be used to extend the vector.
293    #[cfg_attr(feature = "serde", serde(rename = "a"))]
294    pub alts: Vec<AddressLookupTableAccount>,
295    /// Additional account metas that need to be added into consideration for sizing
296    #[cfg_attr(feature = "serde", serde(rename = "m", default))]
297    pub account_metas: Vec<AccountMeta>,
298    /// Transaction-level configuration, required when using
299    /// [`TransactionFormat::V1`].
300    ///
301    /// A template describes instructions, and V1's config values are not
302    /// instructions — without this the transaction cannot be sized.
303    #[cfg_attr(
304        feature = "serde",
305        serde(rename = "c", skip_serializing_if = "Option::is_none", default)
306    )]
307    pub transaction_config: Option<TransactionConfigParams>,
308}
309
310/// Parameters for a swap request.
311#[derive(Clone, Debug, Default, PartialEq, Eq)]
312#[cfg_attr(
313    feature = "serde",
314    derive(serde::Serialize, serde::Deserialize),
315    serde(rename_all = "camelCase")
316)]
317pub struct SwapParams {
318    /// Address of the input mint of the swap.
319    pub input_mint: Pubkey,
320    /// Address of the desired output token for the swap.
321    pub output_mint: Pubkey,
322    /// Raw number of tokens to swap, not scaled by decimals.
323    pub amount: u64,
324    /// Swap mode for how the amount should be interpreted.
325    ///
326    /// Either ExactIn or ExactOut, defaults to ExactIn.
327    /// ExactOut is for supporting use cases where you need an exact output token amount, like
328    /// payments. In this case, slippage would be on the input token. May not always be supported.
329    #[cfg_attr(
330        feature = "serde",
331        serde(skip_serializing_if = "Option::is_none", default)
332    )]
333    pub swap_mode: Option<SwapMode>,
334    /// Allowed slippage in basis points.
335    #[cfg_attr(
336        feature = "serde",
337        serde(skip_serializing_if = "Option::is_none", default)
338    )]
339    pub slippage_bps: Option<u16>,
340    /// If set, constrain quotes to the given set of DEXes.
341    ///
342    /// Note: setting both `dexes` and `exclude_dexes` may result in excluding all dexes, resulting
343    /// in no routes.
344    #[cfg_attr(
345        feature = "serde",
346        serde(skip_serializing_if = "Option::is_none", default)
347    )]
348    pub dexes: Option<Vec<String>>,
349    /// If set, exclude the following DEXes when determining routes.
350    ///
351    /// Note: setting both `dexes` and `exclude_dexes` may result in excluding all dexes, resulting
352    /// in no routes.
353    #[cfg_attr(
354        feature = "serde",
355        serde(skip_serializing_if = "Option::is_none", default)
356    )]
357    pub exclude_dexes: Option<Vec<String>>,
358    /// If true, exclude the server-configured "vote account" venues from routing.
359    /// When absent or false, those venues are included as normal.
360    #[cfg_attr(
361        feature = "serde",
362        serde(skip_serializing_if = "Option::is_none", default)
363    )]
364    pub no_vote_accounts: Option<bool>,
365    /// If set to true, only direct routes between the input and output mint will be considered.
366    #[cfg_attr(
367        feature = "serde",
368        serde(skip_serializing_if = "Option::is_none", default)
369    )]
370    pub only_direct_routes: Option<bool>,
371    /// If set to true, will request that quote providers restrict their quotes to transactions
372    /// that will fit within the size constraint.
373    #[cfg_attr(
374        feature = "serde",
375        serde(skip_serializing_if = "Option::is_none", default)
376    )]
377    pub add_size_constraint: Option<bool>,
378    /// Transaction size constraint in bytes. Defaults to 1232. Only enabled if
379    /// `add_size_constraint` is also set.
380    #[cfg_attr(
381        feature = "serde",
382        serde(skip_serializing_if = "Option::is_none", default)
383    )]
384    pub size_constraint: Option<u32>,
385    /// If set, limit quotes to the given set of provider IDs.
386    #[cfg_attr(
387        feature = "serde",
388        serde(skip_serializing_if = "Option::is_none", default)
389    )]
390    pub providers: Option<Vec<String>>,
391    /// If set, constrain quotes to routes that only use venues (pools) whose address is in this
392    /// list.
393    ///
394    /// This filters by individual venue address, unlike `dexes`/`exclude_dexes` which filter by
395    /// venue label. A venue present in `venue_banlist` is excluded even if it also appears here:
396    /// the banlist takes precedence over the allowlist.
397    #[cfg_attr(
398        feature = "serde",
399        serde(skip_serializing_if = "Option::is_none", default)
400    )]
401    pub venue_allowlist: Option<Vec<Pubkey>>,
402    /// If set, exclude any route that uses a venue (pool) whose address is in this list.
403    ///
404    /// The banlist overrides `venue_allowlist`: a venue in both lists is always excluded.
405    #[cfg_attr(
406        feature = "serde",
407        serde(skip_serializing_if = "Option::is_none", default)
408    )]
409    pub venue_banlist: Option<Vec<Pubkey>>,
410    /// If set, limit total number of accounts used by routes to the specified value.
411    ///
412    /// If not set, any number of accounts that still allows for an executable transaction is
413    /// allowed. As of writing, this is 256 accounts.
414    #[cfg_attr(
415        feature = "serde",
416        serde(skip_serializing_if = "Option::is_none", default)
417    )]
418    pub accounts_limit_total: Option<u16>,
419    /// If set, limit total number of writable accounts used by routes to the specified value.
420    ///
421    /// If not set, any number of accounts that still allows for an executable transaction is
422    /// allowed. As of writing, this is 64 writable accounts.
423    #[cfg_attr(
424        feature = "serde",
425        serde(skip_serializing_if = "Option::is_none", default)
426    )]
427    pub accounts_limit_writable: Option<u16>,
428    /// If set, overrides the mesh size written into the swap instruction for dynamic allocation
429    /// routes, replacing the route's configured default.
430    ///
431    /// The on-chain optimizer splits each venue group's input into `mesh_size` chunks, so a
432    /// smaller value gives a coarser split that uses fewer compute units. `0` disables dynamic
433    /// allocation entirely. Currently only honored by DART.
434    #[cfg_attr(
435        feature = "serde",
436        serde(skip_serializing_if = "Option::is_none", default)
437    )]
438    pub mesh_size: Option<u8>,
439    /// A templated route which Titan can use when determining eligible routes.
440    /// If possible, Titan will insert at the specified index a swap that meets
441    /// Solana's sizing requirements. This is incompatible with the options,
442    /// `accounts_limit_total`, `accounts_limit_writable` and `size_constraint`.
443    /// An error will be returned if they are both specified.
444    #[cfg_attr(
445        feature = "serde",
446        serde(skip_serializing_if = "Option::is_none", default)
447    )]
448    pub transaction_template: Option<TransactionTemplate>,
449}
450
451/// Server default settings and constraints for [`SwapParams`].
452#[derive(Clone, Debug, Default, PartialEq, Eq)]
453#[cfg_attr(
454    feature = "serde",
455    derive(serde::Serialize, serde::Deserialize),
456    serde(rename_all = "camelCase")
457)]
458pub struct SwapSettings {
459    /// Default and bounds for [`SwapParams::slippage_bps`].
460    pub slippage_bps: BoundedValueWithDefault<u16>,
461    /// Default value for [`SwapParams::only_direct_routes`].
462    pub only_direct_routes: bool,
463    /// Default value for [`SwapParams::add_size_constraint`].
464    pub add_size_constraint: bool,
465    /// Default value for [`SwapParams::size_constraint`].
466    pub size_constraint: u32,
467}
468
469/// Parameters for how quote updates should be handled.
470#[derive(Clone, Debug, Default, PartialEq, Eq)]
471#[cfg_attr(
472    feature = "serde",
473    derive(serde::Serialize, serde::Deserialize),
474    serde(rename_all = "camelCase")
475)]
476pub struct QuoteUpdateParams {
477    /// How often the server should send updates for this quote request, in milliseconds.
478    ///
479    /// If not specified, the server default will be used.
480    #[cfg_attr(
481        feature = "serde",
482        serde(skip_serializing_if = "Option::is_none", default)
483    )]
484    pub interval_ms: Option<u64>,
485    /// Maximum number of quotes per update the server should return. If more quotes are available,
486    /// the worst will be filtered out, based on amount in/out depending on swap mode.
487    ///
488    /// If not specified, the server default will be used.
489    #[cfg_attr(
490        feature = "serde",
491        serde(skip_serializing_if = "Option::is_none", default)
492    )]
493    pub num_quotes: Option<u32>,
494    /// Whether to include Address Lookup Table contents in responses.
495    ///
496    /// If not specified, only ALT addresses are returned and the user is responsible for looking up
497    /// ALTs when building transactions.
498    #[cfg_attr(
499        feature = "serde",
500        serde(skip_serializing_if = "Option::is_none", default)
501    )]
502    pub include_alt_contents: Option<bool>,
503}
504
505/// Contains information about the server's settings for quote updates.
506///
507/// Contains minimum, maximum, and default values as needed for the various settings, so that the
508/// client can query information about these settings to ensure that its requests contain valid
509/// values.
510#[derive(Clone, Debug, Default, PartialEq, Eq)]
511#[cfg_attr(
512    feature = "serde",
513    derive(serde::Serialize, serde::Deserialize),
514    serde(rename_all = "camelCase")
515)]
516pub struct QuoteUpdateSettings {
517    /// Bounds and defaults for the `interval_ms` field of [`QuoteUpdateParams`].
518    pub interval_ms: BoundedValueWithDefault<u64>,
519    /// Bounds and defaults for the [`QuoteUpdateParams::num_quotes`] field.
520    pub num_quotes: BoundedValueWithDefault<u32>,
521}
522
523/// Parameters for how transaction data should be generated for swaps.
524#[derive(Clone, Debug, Default, PartialEq, Eq)]
525#[cfg_attr(
526    feature = "serde",
527    derive(serde::Serialize, serde::Deserialize),
528    serde(rename_all = "camelCase")
529)]
530pub struct TransactionParams {
531    /// Public key of the user requesting the swap, needed for transaction generation.
532    pub user_public_key: Pubkey,
533    /// If true, close the input token account as part of the transaction.
534    #[cfg_attr(
535        feature = "serde",
536        serde(skip_serializing_if = "Option::is_none", default)
537    )]
538    pub close_input_token_account: Option<bool>,
539    /// If true, an idempotent ATA will be added to the transactions, if supported by the
540    /// providers.
541    #[cfg_attr(
542        feature = "serde",
543        serde(skip_serializing_if = "Option::is_none", default)
544    )]
545    pub create_output_token_account: Option<bool>,
546    /// The address of an associated token account that will be used to collect fees.
547    ///
548    /// Unless `fee_is_input_mint` is set to true, must be in terms of the output mint.
549    ///
550    /// The fee acount must already exist, or the user must add the ATA creation
551    /// instruction themselves.
552    #[cfg_attr(
553        feature = "serde",
554        serde(skip_serializing_if = "Option::is_none", default)
555    )]
556    pub fee_account: Option<Pubkey>,
557    /// Fee amount to take, in basis points.
558    ///
559    /// If not specified, default fee for the requester is used.
560    #[cfg_attr(
561        feature = "serde",
562        serde(skip_serializing_if = "Option::is_none", default)
563    )]
564    pub fee_bps: Option<u16>,
565    /// Whether the fee should be taken in terms of the input mint.
566    /// Default is false, in which case the fee is taken in terms of the output mint.
567    #[cfg_attr(
568        feature = "serde",
569        serde(skip_serializing_if = "Option::is_none", default)
570    )]
571    pub fee_from_input_mint: Option<bool>,
572    /// Address of the token account into which to place the output of the swap.
573    /// If not specified, the funds will be deposited into an ATA associated with the user's
574    /// wallet.
575    #[cfg_attr(
576        feature = "serde",
577        serde(skip_serializing_if = "Option::is_none", default)
578    )]
579    pub output_account: Option<Pubkey>,
580    /// Which version of the swap routing engine to use.
581    #[cfg_attr(
582        feature = "serde",
583        serde(skip_serializing_if = "Option::is_none", default)
584    )]
585    pub titan_swap_version: Option<SwapVersion>,
586    /// Which transaction wire format to build. Defaults to
587    /// [`TransactionFormat::V0`].
588    #[cfg_attr(
589        feature = "serde",
590        serde(skip_serializing_if = "Option::is_none", default)
591    )]
592    pub transaction_format: Option<TransactionFormat>,
593    /// The address that will receive any positive slippage fees.
594    #[cfg_attr(
595        feature = "serde",
596        serde(skip_serializing_if = "Option::is_none", default)
597    )]
598    pub positive_slippage_fee_receiver: Option<Pubkey>,
599    /// The address of the payer for the transaction.
600    /// If not specified, defaults to the user's public key.
601    #[cfg_attr(
602        feature = "serde",
603        serde(skip_serializing_if = "Option::is_none", default)
604    )]
605    pub payer: Option<Pubkey>,
606    /// If true, leave the output as wSOL instead of unwrapping to native SOL when the output mint
607    /// is the wrapped SOL mint. Defaults to false.
608    #[cfg_attr(
609        feature = "serde",
610        serde(skip_serializing_if = "Option::is_none", default)
611    )]
612    pub output_wsol: Option<bool>,
613}
614
615/// Contains information about the server's defaults and paramter bounds for transactions.
616#[derive(Clone, Debug, Default, PartialEq, Eq)]
617#[cfg_attr(
618    feature = "serde",
619    derive(serde::Serialize, serde::Deserialize),
620    serde(rename_all = "camelCase")
621)]
622pub struct TransactionSettings {
623    /// Default value for [`TransactionParams::close_input_token_account`].
624    pub close_input_token_account: bool,
625    /// Default value for [`TransactionParams::create_output_token_account`].
626    pub create_output_token_account: bool,
627}
628
629/// Contains information about settings or limits set for the specific connection to the server.
630#[derive(Clone, Debug, Default, PartialEq, Eq)]
631#[cfg_attr(
632    feature = "serde",
633    derive(serde::Serialize, serde::Deserialize),
634    serde(rename_all = "camelCase")
635)]
636pub struct ConnectionSettings {
637    /// Number of concurrent streams the user is allowed.
638    pub concurrent_streams: u32,
639}
640
641/// Settings and paramter bounds as configured on the server.
642#[derive(Clone, Debug, Default, PartialEq, Eq)]
643#[cfg_attr(
644    feature = "serde",
645    derive(serde::Serialize, serde::Deserialize),
646    serde(rename_all = "camelCase")
647)]
648pub struct ServerSettings {
649    /// Settings and parameter bounds for quote updates.
650    pub quote_update: QuoteUpdateSettings,
651    /// Settings and parameter bounds for swaps.
652    pub swap: SwapSettings,
653    /// Settings and parameter bounds for transaction generation.
654    pub transaction: TransactionSettings,
655    /// Settings and limits for the user's connection to the server.
656    pub connection: ConnectionSettings,
657}
658
659/// Contains information about the servers settings.
660#[derive(Clone, Debug, Default, PartialEq, Eq)]
661#[cfg_attr(
662    feature = "serde",
663    derive(serde::Serialize, serde::Deserialize),
664    serde(rename_all = "camelCase")
665)]
666pub struct ServerInfo {
667    /// Server protocol version information.
668    pub protocol_version: VersionInfo,
669    /// Server settings and parameter bounds.
670    pub settings: ServerSettings,
671}
672
673/// A request from the user to provide quotes for a swap.
674#[derive(Debug, Clone, Default, PartialEq, Eq)]
675#[cfg_attr(
676    feature = "serde",
677    derive(serde::Serialize, serde::Deserialize),
678    serde(rename_all = "camelCase")
679)]
680pub struct SwapQuoteRequest {
681    /// Parameters for the swap.
682    pub swap: SwapParams,
683    /// Parameters for transaction generation.
684    pub transaction: TransactionParams,
685    /// Parameters for quote updating.
686    #[cfg_attr(
687        feature = "serde",
688        serde(skip_serializing_if = "Option::is_none", default)
689    )]
690    pub update: Option<QuoteUpdateParams>,
691}
692
693/// A request from the user to quote swapping an amount directly between two tokens,
694/// which effectively gives the relative price of the tokens at that value.
695#[derive(Debug, Clone, Default, PartialEq, Eq)]
696#[cfg_attr(
697    feature = "serde",
698    derive(serde::Serialize, serde::Deserialize),
699    serde(rename_all = "camelCase")
700)]
701pub struct SwapPriceRequest {
702    /// Address of the input mint of the swap.
703    pub input_mint: Pubkey,
704    /// Address of the desired output token for the swap.
705    pub output_mint: Pubkey,
706    /// Raw number of tokens to swap, not scaled by decimals.
707    pub amount: u64,
708    /// If set, constrain quotes to the given set of DEXes.
709    ///
710    /// Note: setting both `dexes` and `exclude_dexes` may result in excluding all dexes, resulting
711    /// in no routes.
712    #[cfg_attr(
713        feature = "serde",
714        serde(skip_serializing_if = "Option::is_none", default)
715    )]
716    pub dexes: Option<Vec<String>>,
717    /// If set, exclude the following DEXes when determining routes.
718    ///
719    /// Note: setting both `dexes` and `exclude_dexes` may result in excluding all dexes, resulting
720    /// in no routes.
721    #[cfg_attr(
722        feature = "serde",
723        serde(skip_serializing_if = "Option::is_none", default)
724    )]
725    pub exclude_dexes: Option<Vec<String>>,
726}
727
728/// Information about a single step in a route plan for a swap.
729#[derive(Debug, Clone, Default, PartialEq, Eq)]
730#[cfg_attr(
731    feature = "serde",
732    derive(serde::Serialize, serde::Deserialize),
733    serde(rename_all = "camelCase")
734)]
735pub struct RoutePlanStep {
736    /// Which AMM is being executed on at this step.
737    pub amm_key: Pubkey,
738    /// Label for the protocol being used.
739    ///
740    /// Examples: "Raydium AMM", "Phoenix", etc.
741    pub label: String,
742    /// Address of the input mint for this swap.
743    pub input_mint: Pubkey,
744    /// Address of the output mint for this swap.
745    pub output_mint: Pubkey,
746    /// How many input tokens are expected to go through this step.
747    pub in_amount: u64,
748    /// How many output tokens are expected to come out of this step.
749    pub out_amount: u64,
750    /// What what proportion, in parts per billion, of the order flow is allocated to flow through this pool.
751    pub alloc_ppb: u32,
752    /// Address of the mint in which the fee is charged.
753    #[cfg_attr(
754        feature = "serde",
755        serde(skip_serializing_if = "Option::is_none", default)
756    )]
757    pub fee_mint: Option<Pubkey>,
758    /// The amount of tokens charged as a fee for this swap.
759    #[cfg_attr(
760        feature = "serde",
761        serde(skip_serializing_if = "Option::is_none", default)
762    )]
763    pub fee_amount: Option<u64>,
764    /// Context slot for the pool data, if known.
765    #[cfg_attr(
766        feature = "serde",
767        serde(skip_serializing_if = "Option::is_none", default)
768    )]
769    pub context_slot: Option<u64>,
770}
771
772/// Information about a fee that is claimed by a platform for use of its services as part of a
773/// quote.
774#[derive(Debug, Clone, Default, PartialEq, Eq)]
775#[cfg_attr(
776    feature = "serde",
777    derive(serde::Serialize, serde::Deserialize),
778    serde(rename_all = "camelCase")
779)]
780pub struct PlatformFee {
781    /// Amount of tokens taken as a fee.
782    pub amount: u64,
783    /// Fee percentage, in basis points.
784    pub fee_bps: u8,
785}
786
787/// Information about a route for a swap.
788#[derive(Debug, Clone, Default, PartialEq)]
789#[cfg_attr(
790    feature = "serde",
791    derive(serde::Serialize, serde::Deserialize),
792    serde(rename_all = "camelCase")
793)]
794pub struct SwapRoute {
795    /// How many input tokens are expected to go through this route.
796    pub in_amount: u64,
797    /// How many output tokens are expected to come out of this route.
798    pub out_amount: u64,
799    /// Amount of slippage encurred, in basis points.
800    pub slippage_bps: u16,
801    /// Platform fee information, if such a fee is charged by the provider.
802    #[cfg_attr(
803        feature = "serde",
804        serde(skip_serializing_if = "Option::is_none", default)
805    )]
806    pub platform_fee: Option<PlatformFee>,
807    /// Topologically ordered DAG containing the steps that comprise this route.
808    ///
809    /// May be empty if the provider does not provide information about the steps taken, or there
810    /// are no steps (e.g. RFQ providers).
811    pub steps: Vec<RoutePlanStep>,
812    /// Instructions needed to execute the route.
813    ///
814    /// May be empty if the provider does not support the user building their own transactions.
815    /// In this case, the transaction to sign should be present in the [`SwapRoute::transaction`]
816    /// field.
817    pub instructions: Vec<Instruction>,
818    /// Address lookup tables necessary to load.
819    ///
820    /// May be empty if the provider does not support the user building their own transactions.
821    /// In this case, the transaction to sign should be present in the [`SwapRoute::transaction`]
822    /// field.
823    pub address_lookup_tables: Vec<Pubkey>,
824    /// Context slot for the route provided.
825    #[cfg_attr(
826        feature = "serde",
827        serde(skip_serializing_if = "Option::is_none", default)
828    )]
829    pub context_slot: Option<u64>,
830    /// Amount of time taken to generate the quote in seconds, if known.
831    #[cfg_attr(
832        feature = "serde",
833        serde(skip_serializing_if = "Option::is_none", default)
834    )]
835    pub time_taken_ns: Option<u64>,
836    /// If this route expires by time, the time at which it expires, as a millisecond UNIX timestamp.
837    #[cfg_attr(
838        feature = "serde",
839        serde(skip_serializing_if = "Option::is_none", default)
840    )]
841    pub expires_at_ms: Option<u64>,
842    /// If this route expires by slot, the last slot at which the route is valid.
843    #[cfg_attr(
844        feature = "serde",
845        serde(skip_serializing_if = "Option::is_none", default)
846    )]
847    pub expires_after_slot: Option<u64>,
848    /// The number of compute units this transaction is expected to consume, if known.
849    #[cfg_attr(
850        feature = "serde",
851        serde(skip_serializing_if = "Option::is_none", default)
852    )]
853    pub compute_units: Option<u64>,
854    /// The number of compute units that the server recommends setting for this route. Includes a
855    /// buffer to allow for fluctuations in compute unit usage from various protocols as well as
856    /// other instructions the user may wish to add, such as tips.
857    #[cfg_attr(
858        feature = "serde",
859        serde(skip_serializing_if = "Option::is_none", default)
860    )]
861    pub compute_units_safe: Option<u64>,
862    /// Raw transaction to be signed by the user. May be returned instead of instructions and ALTs.
863    #[cfg_attr(
864        feature = "serde",
865        serde(skip_serializing_if = "Option::is_none", with = "serde_bytes", default)
866    )]
867    pub transaction: Option<Vec<u8>>,
868    #[cfg_attr(
869        feature = "serde",
870        serde(skip_serializing_if = "Option::is_none", default)
871    )]
872    /// Reference ID for Pyth Express Relay and HashFlow RFQ providers.
873    pub reference_id: Option<String>,
874}
875
876/// Possible value for a flag in the flags map.
877///
878/// Only simple values like strings, booleans, integers, and floating point numbers are allowed.
879///
880/// Values are serialized untagged, e.g. as the inner type.
881///
882/// Available since: v1.3
883#[derive(PartialEq, Clone, Debug)]
884#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(untagged))]
885pub enum MetadataValue {
886    /// Value contains a single String.
887    String(String),
888    /// Value contains a single boolean.
889    Bool(bool),
890    /// Value contains a single integer.
891    Int(i64),
892    /// Value contains a single floating point number.
893    Float(f64),
894    /// Array of Metadata values.
895    /// Since: v1.7
896    Array(Vec<Self>),
897    /// Mapping of strings to metadata values.
898    /// Since: v1.7
899    Map(HashMap<String, Self>),
900}
901
902// Custom deserializer using serde-untagged to have better performance than the default untagged
903// deserialization method, especially since this is a very simple struct that is very easy to tell
904// which variant is needed based on the type.
905#[cfg(feature = "serde")]
906impl<'de> serde::Deserialize<'de> for MetadataValue {
907    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
908    where
909        D: serde::Deserializer<'de>,
910    {
911        serde_untagged::UntaggedEnumVisitor::new()
912            .string(|string| Ok(Self::String(String::from(string))))
913            .i64(|int| Ok(Self::Int(int)))
914            .f64(|value| Ok(Self::Float(value)))
915            .bool(|value| Ok(Self::Bool(value)))
916            .seq(|mut seq| {
917                use serde::de::SeqAccess;
918
919                let mut res = Vec::with_capacity(seq.size_hint().unwrap_or(0));
920                while let Some(item) = seq.next_element()? {
921                    res.push(item);
922                }
923                Ok(Self::Array(res))
924            })
925            .map(|mut map| {
926                use serde::de::MapAccess;
927
928                let mut res = HashMap::with_capacity(map.size_hint().unwrap_or(0));
929                while let Some((key, value)) = map.next_entry()? {
930                    res.insert(key, value);
931                }
932
933                Ok(Self::Map(res))
934            })
935            .deserialize(deserializer)
936    }
937}
938
939impl From<String> for MetadataValue {
940    fn from(value: String) -> Self {
941        Self::String(value)
942    }
943}
944
945impl From<bool> for MetadataValue {
946    fn from(value: bool) -> Self {
947        Self::Bool(value)
948    }
949}
950
951impl From<i64> for MetadataValue {
952    fn from(value: i64) -> Self {
953        Self::Int(value)
954    }
955}
956
957impl From<u32> for MetadataValue {
958    fn from(value: u32) -> Self {
959        Self::Int(i64::from(value))
960    }
961}
962
963impl From<i32> for MetadataValue {
964    fn from(value: i32) -> Self {
965        Self::Int(i64::from(value))
966    }
967}
968
969impl From<u16> for MetadataValue {
970    fn from(value: u16) -> Self {
971        Self::Int(i64::from(value))
972    }
973}
974
975impl From<i16> for MetadataValue {
976    fn from(value: i16) -> Self {
977        Self::Int(i64::from(value))
978    }
979}
980
981impl From<u8> for MetadataValue {
982    fn from(value: u8) -> Self {
983        Self::Int(i64::from(value))
984    }
985}
986
987impl From<i8> for MetadataValue {
988    fn from(value: i8) -> Self {
989        Self::Int(i64::from(value))
990    }
991}
992
993impl From<f64> for MetadataValue {
994    fn from(value: f64) -> Self {
995        Self::Float(value)
996    }
997}
998
999impl From<f32> for MetadataValue {
1000    fn from(value: f32) -> Self {
1001        Self::Float(f64::from(value))
1002    }
1003}
1004
1005impl From<Vec<MetadataValue>> for MetadataValue {
1006    fn from(value: Vec<MetadataValue>) -> Self {
1007        Self::Array(value)
1008    }
1009}
1010
1011impl FromIterator<MetadataValue> for MetadataValue {
1012    fn from_iter<T: IntoIterator<Item = MetadataValue>>(iter: T) -> Self {
1013        Self::Array(iter.into_iter().collect())
1014    }
1015}
1016
1017impl From<HashMap<String, MetadataValue>> for MetadataValue {
1018    fn from(value: HashMap<String, MetadataValue>) -> Self {
1019        Self::Map(value)
1020    }
1021}
1022
1023impl<S> FromIterator<(S, MetadataValue)> for MetadataValue
1024where
1025    S: ToString,
1026{
1027    fn from_iter<T: IntoIterator<Item = (S, MetadataValue)>>(iter: T) -> Self {
1028        let mut res = HashMap::default();
1029        for (key, value) in iter.into_iter() {
1030            res.insert(key.to_string(), value);
1031        }
1032        Self::Map(res)
1033    }
1034}
1035
1036/// A set of quotes for a swap requested by the user.
1037///
1038/// If multiple providers are able to provide quotes, one route per provider will be returned.
1039#[derive(Debug, Clone, Default, PartialEq)]
1040#[cfg_attr(
1041    feature = "serde",
1042    derive(serde::Serialize, serde::Deserialize),
1043    serde(rename_all = "camelCase")
1044)]
1045pub struct SwapQuotes {
1046    /// Identifier for this particular set of quotes.
1047    pub id: String,
1048    /// Address of the input mint for this quote.
1049    pub input_mint: Pubkey,
1050    /// Address of the output mint for this quote.
1051    pub output_mint: Pubkey,
1052    /// What swap mode was used for the quotes.
1053    pub swap_mode: SwapMode,
1054    /// Amount that was used for the quotes.
1055    pub amount: u64,
1056    /// A mapping of a provider identifier to their quoted route.
1057    pub quotes: HashMap<String, SwapRoute>,
1058    /// Optional informational flags attached to the quote.
1059    ///
1060    /// Available since: v1.3
1061    #[cfg_attr(
1062        feature = "serde",
1063        serde(skip_serializing_if = "Option::is_none", default)
1064    )]
1065    pub metadata: Option<HashMap<String, MetadataValue>>,
1066    /// Contents of Address Lookup Tables used as part of routes, if requested.
1067    ///
1068    /// Available since: v1.9
1069    #[cfg_attr(
1070        feature = "serde",
1071        serde(skip_serializing_if = "Option::is_none", default)
1072    )]
1073    pub alts: Option<Vec<AddressLookupTableAccount>>,
1074}
1075
1076/// A pricing request from a user.
1077///
1078/// Only one price will be returned for the token pair via Argos.
1079#[derive(Debug, Clone, Default, PartialEq)]
1080#[cfg_attr(
1081    feature = "serde",
1082    derive(serde::Serialize, serde::Deserialize),
1083    serde(rename_all = "camelCase")
1084)]
1085pub struct SwapPrice {
1086    /// Identifier for this particular set of prices.
1087    pub id: String,
1088    /// Address of the input mint for this price.
1089    pub input_mint: Pubkey,
1090    /// Address of the output mint for this price.
1091    pub output_mint: Pubkey,
1092    /// Amount that was used for the price.
1093    pub amount_in: u64,
1094    /// The amount out of the best simulated quote for pricing.
1095    pub amount_out: u64,
1096}
1097
1098/// Response to a successful request to start a stream of quotes for a swap.
1099#[derive(Debug, Clone, Default, PartialEq, Eq)]
1100#[cfg_attr(
1101    feature = "serde",
1102    derive(serde::Serialize, serde::Deserialize),
1103    serde(rename_all = "camelCase")
1104)]
1105pub struct QuoteSwapStreamResponse {
1106    /// The interval, in milliseconds, in which the server will provide updates to the quotes.
1107    pub interval_ms: u64,
1108    /// The maximum number of quotes that will be returned per update.
1109    pub num_quotes: u32,
1110}
1111
1112/// Parameters for a `GetInfo` request.
1113///
1114/// Currently contains no options, allowing for further expansion and to allow serialization of all
1115/// request types to be consistent.
1116#[derive(Clone, Debug, Default, PartialEq, Eq)]
1117#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1118pub struct GetInfoRequest {
1119    /// Dummy attribute so this will be serialized as expected.
1120    #[cfg_attr(
1121        feature = "serde",
1122        serde(skip_serializing_if = "Option::is_none", default)
1123    )]
1124    pub dummy: Option<bool>,
1125}
1126
1127/// Paramters for a [`RequestData::StopStream`] request.
1128#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
1129#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1130pub struct StopStreamRequest {
1131    /// Identifier of the stream to stop.
1132    pub id: u32,
1133}
1134
1135/// Response to a successful request to stop a data stream.
1136///
1137/// Note: If a stream had data already prepared, there may still be a [`StreamData`][streamdata]
1138/// message sent for the stream before the [`StreamEnd`][streamend] is sent.
1139///
1140/// [streamdata]: ServerMessage::StreamData
1141/// [streamend]: ServerMessage::StreamEnd
1142#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
1143#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1144pub struct StopStreamResponse {
1145    /// Identifier of the stream that was stopped.
1146    pub id: u32,
1147}
1148
1149/// Request to retrieve information about known venues for dex aggregator providers.
1150#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
1151#[cfg_attr(
1152    feature = "serde",
1153    derive(serde::Serialize, serde::Deserialize),
1154    serde(rename_all = "camelCase")
1155)]
1156pub struct GetVenuesRequest {
1157    /// Whether to include the program ID for each venue.
1158    #[cfg_attr(
1159        feature = "serde",
1160        serde(default, skip_serializing_if = "Option::is_none")
1161    )]
1162    pub include_program_ids: Option<bool>,
1163}
1164
1165/// Information about known venues for dex aggregators.
1166#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
1167#[cfg_attr(
1168    feature = "serde",
1169    derive(serde::Serialize, serde::Deserialize),
1170    serde(rename_all = "camelCase")
1171)]
1172pub struct VenueInfo {
1173    /// Labels for known venues, used in the `dexes` and `exclude_dexes` swap parameters.
1174    pub labels: Vec<String>,
1175    /// Program IDs for each venue, if requested.
1176    #[cfg_attr(
1177        feature = "serde",
1178        serde(default, skip_serializing_if = "Option::is_none")
1179    )]
1180    pub program_ids: Option<Vec<Pubkey>>,
1181}
1182
1183/// Request to retrieve information about the enabled quote providers.
1184#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
1185#[cfg_attr(
1186    feature = "serde",
1187    derive(serde::Serialize, serde::Deserialize),
1188    serde(rename_all = "camelCase")
1189)]
1190pub struct ListProvidersRequest {
1191    /// If true, will include icon URLs.
1192    #[cfg_attr(
1193        feature = "serde",
1194        serde(default, skip_serializing_if = "Option::is_none")
1195    )]
1196    pub include_icons: Option<bool>,
1197}
1198
1199/// Information about a particular provider.
1200#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
1201#[cfg_attr(
1202    feature = "serde",
1203    derive(serde::Serialize, serde::Deserialize),
1204    serde(rename_all = "camelCase")
1205)]
1206pub struct ProviderInfo {
1207    /// ID of the provider as returned in quotes and used in the `providers` parameter for
1208    /// requests.
1209    pub id: String,
1210    /// Human-readable name for the provider.
1211    pub name: String,
1212    /// What kind of provider this is.
1213    pub kind: ProviderKind,
1214    /// URI for a 48x48 pixel icon for the provider, if requested.
1215    #[cfg_attr(
1216        feature = "serde",
1217        serde(default, skip_serializing_if = "Option::is_none")
1218    )]
1219    pub icon_uri_48: Option<String>,
1220}
1221
1222/// What kind of quote provider a particular provider is.
1223#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
1224#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1225pub enum ProviderKind {
1226    /// Provider is an aggregator of decentralized exchanges.
1227    DexAggregator,
1228    /// Provider is a Request-For-Quotes provider.
1229    RFQ,
1230    /// Catch-all for deserializing additional types added in the future.
1231    #[cfg_attr(feature = "serde", serde(untagged))]
1232    Other(String),
1233}
1234
1235/// Data for a request from the user sent on the WebSocket.
1236#[derive(Clone, Debug, PartialEq)]
1237#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1238#[allow(clippy::large_enum_variant)]
1239pub enum RequestData {
1240    /// Request that the server respond with information on its settings and parameter bounds.
1241    GetInfo(GetInfoRequest),
1242    /// User requests a stream of quotes for a swap between two tokens.
1243    NewSwapQuoteStream(SwapQuoteRequest),
1244    /// User requests to stop a stream of data.
1245    StopStream(StopStreamRequest),
1246    /// User requets information about known venues for dex aggregator providers.
1247    GetVenues(GetVenuesRequest),
1248    /// User requests information about enabled quote providers.
1249    ListProviders(ListProvidersRequest),
1250    /// User requests the price of a swap directly between two tokens.
1251    GetSwapPrice(SwapPriceRequest),
1252    /// Other type of un-handled message type.
1253    #[cfg(feature = "enum-other")]
1254    #[cfg_attr(feature = "serde", serde(untagged))]
1255    Other(rmpv::Value),
1256}
1257
1258/// Data for a successful response to a request.
1259#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1260#[derive(Clone, Debug, PartialEq)]
1261pub enum ResponseData {
1262    /// Response for a [`GetInfo`][ResponseData::GetInfo] request.
1263    GetInfo(ServerInfo),
1264    /// Response for a [`NewSwapQuoteStream`][RequestData::NewSwapQuoteStream] request.
1265    NewSwapQuoteStream(QuoteSwapStreamResponse),
1266    /// Successful response to a [`StopStream`][RequestData::StopStream] request.
1267    StreamStopped(StopStreamResponse),
1268    /// Successful response to a [`GetVenues`][RequestData::GetVenues] request.
1269    GetVenues(VenueInfo),
1270    /// Successful response to a [`ListProviders`][RequestData::ListProviders] request.
1271    ListProviders(Vec<ProviderInfo>),
1272    /// Successful response to a [`GetPrice`][RequestData::GetSwapPrice] request.
1273    GetSwapPrice(SwapPrice),
1274    /// Other type of un-handled message type.
1275    #[cfg(feature = "enum-other")]
1276    #[cfg_attr(feature = "serde", serde(untagged))]
1277    Other(rmpv::Value),
1278}
1279
1280/// A request sent by the client.
1281#[derive(Clone, Debug, PartialEq)]
1282#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1283pub struct ClientRequest {
1284    /// Identifier for the request.
1285    ///
1286    /// The response(s) will contain the same ID that is specified here so that the client can
1287    /// correlate the response(s) with the request.
1288    pub id: u32,
1289    /// Data for the request.
1290    pub data: RequestData,
1291}
1292
1293/// Notification that a new stream has been started by the server.
1294///
1295/// Returned as part of a successful response so that the client can allocate resources for the
1296/// stream.
1297#[cfg_attr(
1298    feature = "serde",
1299    derive(serde::Serialize, serde::Deserialize),
1300    serde(rename_all = "camelCase")
1301)]
1302#[derive(Debug, Clone, PartialEq, Eq)]
1303pub struct StreamStart {
1304    /// ID of the new stream.
1305    ///
1306    /// This ID will be present in [`StreamData`] and [`StreamEnd`] messages for this stream.
1307    pub id: u32,
1308    /// The type of data that will be sent in this stream.
1309    pub data_type: StreamDataType,
1310}
1311
1312/// Data packet for a stream.
1313#[cfg_attr(
1314    feature = "serde",
1315    derive(serde::Serialize, serde::Deserialize),
1316    serde(rename_all = "camelCase")
1317)]
1318#[derive(Debug, Clone, PartialEq)]
1319pub struct StreamData {
1320    /// ID of the stream.
1321    pub id: u32,
1322    /// Sequence number of this data packet.
1323    pub seq: u32,
1324    /// Data payload.
1325    pub payload: StreamDataPayload,
1326}
1327
1328/// Notification that a stream has closed and will no longer receive data.
1329#[cfg_attr(
1330    feature = "serde",
1331    derive(serde::Serialize, serde::Deserialize),
1332    serde(rename_all = "camelCase")
1333)]
1334#[derive(Debug, Clone, PartialEq, Eq)]
1335pub struct StreamEnd {
1336    /// ID of the stream that has ended.
1337    pub id: u32,
1338    /// If the stream ended due to an error, contains the code denoting the specific error that
1339    /// occurred.
1340    #[cfg_attr(
1341        feature = "serde",
1342        serde(skip_serializing_if = "Option::is_none", default)
1343    )]
1344    pub error_code: Option<u32>,
1345    /// If the stream ended due to an error, contains a message explaining what happened.
1346    #[cfg_attr(
1347        feature = "serde",
1348        serde(skip_serializing_if = "Option::is_none", default)
1349    )]
1350    pub error_message: Option<String>,
1351}
1352
1353/// A response to a successful request.
1354#[cfg_attr(
1355    feature = "serde",
1356    derive(serde::Serialize, serde::Deserialize),
1357    serde(rename_all = "camelCase")
1358)]
1359#[derive(Debug, Clone, PartialEq)]
1360pub struct ResponseSuccess {
1361    /// Identifier of the request that triggered this response.
1362    pub request_id: u32,
1363    /// The response data.
1364    pub data: ResponseData,
1365    /// If this request starts a new stream, contains information about the stream ID and its data
1366    /// type.
1367    #[cfg_attr(
1368        feature = "serde",
1369        serde(skip_serializing_if = "Option::is_none", default)
1370    )]
1371    pub stream: Option<StreamStart>,
1372}
1373
1374/// A response to a request that resulted in an error.
1375#[cfg_attr(
1376    feature = "serde",
1377    derive(serde::Serialize, serde::Deserialize),
1378    serde(rename_all = "camelCase")
1379)]
1380#[derive(Debug, Clone, PartialEq, Eq)]
1381pub struct ResponseError {
1382    /// Identifier of the request that triggered this response.
1383    pub request_id: u32,
1384    /// A numeric error code representing the specific error that occurred.
1385    pub code: u32,
1386    /// A message describing the error.
1387    pub message: String,
1388}
1389
1390/// Types of data that can be streamed to the client.
1391///
1392/// Included in a [`StreamStart`] message so that the client may prepare for the incoming data.
1393#[derive(PartialEq, Eq, Clone, Debug)]
1394#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1395pub enum StreamDataType {
1396    /// Stream contains [`SwapQuotes`](struct@SwapQuotes) as the data values.
1397    SwapQuotes,
1398    /// Other type added in a future version.
1399    #[cfg(feature = "enum-other")]
1400    #[cfg_attr(feature = "serde", serde(untagged))]
1401    Other(String),
1402}
1403
1404/// Payload for a [`StreamData`] message.
1405#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1406#[derive(Debug, Clone, PartialEq)]
1407pub enum StreamDataPayload {
1408    /// Payload contains a set of quotes for a swap request.
1409    SwapQuotes(SwapQuotes),
1410    /// Other type of un-handled message type.
1411    #[cfg(feature = "enum-other")]
1412    #[cfg_attr(feature = "serde", serde(untagged))]
1413    Other(rmpv::Value),
1414}
1415
1416/// A message sent by the server to the client.
1417#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1418#[derive(Debug, Clone, PartialEq)]
1419pub enum ServerMessage {
1420    /// Successful response to a request, which may optionally start a stream.
1421    Response(ResponseSuccess),
1422    /// An error response to a request.
1423    Error(ResponseError),
1424    /// Data for a stream.
1425    StreamData(StreamData),
1426    /// Notification that a stream has ended.
1427    StreamEnd(StreamEnd),
1428    /// Other type of un-handled message type.
1429    #[cfg(feature = "enum-other")]
1430    #[cfg_attr(feature = "serde", serde(untagged))]
1431    Other(rmpv::Value),
1432}
1433
1434#[cfg(test)]
1435mod test {
1436    use super::*;
1437
1438    use hex_literal::hex;
1439    use rmp_serde::{decode::Error as DecError, encode::Error as EncError};
1440    use rmpv::Value;
1441
1442    const WSOL_ADDR: Pubkey = Pubkey::from_str_const("So11111111111111111111111111111111111111112");
1443    const USDC_ADDR: Pubkey =
1444        Pubkey::from_str_const("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
1445    const METEORA_DLMM_WSOL_USDC: Pubkey =
1446        Pubkey::from_str_const("2kSaQT7BcB92uVeDtmxsDJm9fbGxupf64KgtsF5xzLhf");
1447
1448    #[test]
1449    fn test_encode_version_info() -> Result<(), EncError> {
1450        let info = VersionInfo::new(1, 2, 3);
1451        let expected = hex!("83a56d616a6f7201a56d696e6f7202a5706174636803");
1452        let encoded = rmp_serde::to_vec_named(&info)?;
1453        assert_eq!(encoded, expected);
1454        Ok(())
1455    }
1456
1457    #[test]
1458    fn test_decode_version_info() -> Result<(), DecError> {
1459        let info = VersionInfo::new(1, 2, 3);
1460        let data = hex!("83a56d616a6f7201a56d696e6f7202a5706174636803");
1461        let decoded = rmp_serde::from_slice::<VersionInfo>(&data)?;
1462        assert_eq!(decoded, info);
1463        Ok(())
1464    }
1465
1466    #[test]
1467    fn test_encode_swap_mode() -> Result<(), EncError> {
1468        let exact_in_data = hex!("a74578616374496e");
1469        let exact_out_data = hex!("a845786163744f7574");
1470
1471        assert_eq!(rmp_serde::to_vec_named(&SwapMode::ExactIn)?, &exact_in_data);
1472        assert_eq!(
1473            rmp_serde::to_vec_named(&SwapMode::ExactOut)?,
1474            &exact_out_data
1475        );
1476
1477        Ok(())
1478    }
1479
1480    #[test]
1481    fn test_decode_swap_mode() -> Result<(), DecError> {
1482        let exact_in_data = hex!("a74578616374496e");
1483        let exact_out_data = hex!("a845786163744f7574");
1484
1485        assert_eq!(
1486            rmp_serde::from_slice::<SwapMode>(&exact_in_data)?,
1487            SwapMode::ExactIn
1488        );
1489        assert_eq!(
1490            rmp_serde::from_slice::<SwapMode>(&exact_out_data)?,
1491            SwapMode::ExactOut
1492        );
1493
1494        Ok(())
1495    }
1496
1497    #[test]
1498    fn test_encode_swap_params() -> Result<(), EncError> {
1499        let data = hex!("83a9696e7075744d696e74c420069b8857feab8184fb687f634618c035dac439dc1aeb3b5598a0f00000000001aa6f75747075744d696e74c420c6fa7af3bedbad3a3d65f36aabc97431b1bbe4c2d2f6e0e47ca60203452f5d61a6616d6f756e74ce3b9aca00");
1500        let info = SwapParams {
1501            input_mint: WSOL_ADDR,
1502            output_mint: USDC_ADDR,
1503            amount: 1_000_000_000,
1504            ..Default::default()
1505        };
1506        let encoded = rmp_serde::to_vec_named(&info)?;
1507        assert_eq!(encoded, data);
1508
1509        Ok(())
1510    }
1511
1512    #[test]
1513    fn test_decode_swap_params() -> Result<(), DecError> {
1514        let data = hex!("83a9696e7075744d696e74c420069b8857feab8184fb687f634618c035dac439dc1aeb3b5598a0f00000000001aa6f75747075744d696e74c420c6fa7af3bedbad3a3d65f36aabc97431b1bbe4c2d2f6e0e47ca60203452f5d61a6616d6f756e74ce3b9aca00");
1515        let info = SwapParams {
1516            input_mint: WSOL_ADDR,
1517            output_mint: USDC_ADDR,
1518            amount: 1_000_000_000,
1519            ..Default::default()
1520        };
1521        let decoded: SwapParams = rmp_serde::from_slice(&data)?;
1522        assert_eq!(decoded, info);
1523
1524        Ok(())
1525    }
1526
1527    #[test]
1528    fn test_encode_swap_settings() -> Result<(), EncError> {
1529        let expected_rmp = Value::Map(vec![
1530            (
1531                Value::from("slippageBps"),
1532                Value::Map(vec![
1533                    (Value::from("min"), Value::from(0u16)),
1534                    (Value::from("max"), Value::from(10_000u16)),
1535                    (Value::from("default"), Value::from(100u16)),
1536                ]),
1537            ),
1538            (Value::from("onlyDirectRoutes"), Value::from(false)),
1539            (Value::from("addSizeConstraint"), Value::from(true)),
1540            (Value::from("sizeConstraint"), Value::from(1232)),
1541        ]);
1542        let data = rmp_serde::to_vec_named(&expected_rmp).expect("expected rmp should encode");
1543        let info = SwapSettings {
1544            slippage_bps: BoundedValueWithDefault {
1545                min: 0,
1546                max: 10_000,
1547                default: 100,
1548            },
1549            only_direct_routes: false,
1550            add_size_constraint: true,
1551            size_constraint: 1232,
1552        };
1553        let encoded = rmp_serde::to_vec_named(&info)?;
1554        assert_eq!(encoded, data);
1555
1556        Ok(())
1557    }
1558
1559    #[test]
1560    fn test_decode_swap_settings() -> Result<(), DecError> {
1561        let expected_rmp = Value::Map(vec![
1562            (
1563                Value::from("slippageBps"),
1564                Value::Map(vec![
1565                    (Value::from("min"), Value::from(0u16)),
1566                    (Value::from("max"), Value::from(10_000u16)),
1567                    (Value::from("default"), Value::from(100u16)),
1568                ]),
1569            ),
1570            (Value::from("onlyDirectRoutes"), Value::from(false)),
1571            (Value::from("addSizeConstraint"), Value::from(true)),
1572            (Value::from("sizeConstraint"), Value::from(1232)),
1573        ]);
1574        let data = rmp_serde::to_vec_named(&expected_rmp).expect("expected rmp should encode");
1575        let info = SwapSettings {
1576            slippage_bps: BoundedValueWithDefault {
1577                min: 0,
1578                max: 10_000,
1579                default: 100,
1580            },
1581            only_direct_routes: false,
1582            add_size_constraint: true,
1583            size_constraint: 1232,
1584        };
1585        let decoded: SwapSettings = rmp_serde::from_slice(&data)?;
1586        assert_eq!(decoded, info);
1587
1588        Ok(())
1589    }
1590
1591    #[test]
1592    fn test_encode_quote_update_params() -> Result<(), EncError> {
1593        let data = hex!("81aa696e74657276616c4d73cd03e8");
1594        let info = QuoteUpdateParams {
1595            interval_ms: Some(1000),
1596            ..Default::default()
1597        };
1598        let encoded = rmp_serde::to_vec_named(&info)?;
1599        assert_eq!(encoded, data);
1600
1601        let empty_data = hex!("80");
1602        let info = QuoteUpdateParams {
1603            interval_ms: None,
1604            ..Default::default()
1605        };
1606        let encoded = rmp_serde::to_vec_named(&info)?;
1607        assert_eq!(encoded, empty_data);
1608
1609        Ok(())
1610    }
1611
1612    #[test]
1613    fn test_decode_quote_update_params() -> Result<(), DecError> {
1614        let data = hex!("81aa696e74657276616c4d73cd03e8");
1615        let info = QuoteUpdateParams {
1616            interval_ms: Some(1000),
1617            ..Default::default()
1618        };
1619        let decoded: QuoteUpdateParams = rmp_serde::from_slice(&data)?;
1620        assert_eq!(decoded, info);
1621
1622        let empty_data = hex!("80");
1623        let info = QuoteUpdateParams {
1624            interval_ms: None,
1625            ..Default::default()
1626        };
1627        let decoded: QuoteUpdateParams = rmp_serde::from_slice(&empty_data)?;
1628        assert_eq!(decoded, info);
1629
1630        Ok(())
1631    }
1632
1633    #[test]
1634    fn test_encode_transaction_params() -> Result<(), EncError> {
1635        let data = hex!("82ad757365725075626c69634b6579c42019fc949cf6d288d076e39f923bf6f1b45da023310e606afc40cc080d5b25983ab6636c6f7365496e707574546f6b656e4163636f756e74c3");
1636        let info = TransactionParams {
1637            user_public_key: METEORA_DLMM_WSOL_USDC,
1638            close_input_token_account: Some(true),
1639            create_output_token_account: None,
1640            ..Default::default()
1641        };
1642        let encoded = rmp_serde::to_vec_named(&info)?;
1643        assert_eq!(encoded, data);
1644
1645        Ok(())
1646    }
1647
1648    #[test]
1649    fn test_decode_transaction_params() -> Result<(), DecError> {
1650        let data = hex!("82ad757365725075626c69634b6579c42019fc949cf6d288d076e39f923bf6f1b45da023310e606afc40cc080d5b25983ab6636c6f7365496e707574546f6b656e4163636f756e74c3");
1651        let info = TransactionParams {
1652            user_public_key: METEORA_DLMM_WSOL_USDC,
1653            close_input_token_account: Some(true),
1654            create_output_token_account: None,
1655            ..Default::default()
1656        };
1657        let decoded: TransactionParams = rmp_serde::from_slice(&data)?;
1658        assert_eq!(decoded, info);
1659
1660        Ok(())
1661    }
1662
1663    #[test]
1664    fn test_encode_transaction_settings() -> Result<(), EncError> {
1665        let data = hex!("82b6636c6f7365496e707574546f6b656e4163636f756e74c2b86372656174654f7574707574546f6b656e4163636f756e74c3");
1666        let info = TransactionSettings {
1667            close_input_token_account: false,
1668            create_output_token_account: true,
1669        };
1670        let encoded = rmp_serde::to_vec_named(&info)?;
1671        assert_eq!(encoded, data);
1672
1673        Ok(())
1674    }
1675
1676    #[test]
1677    fn test_decode_transaction_settings() -> Result<(), DecError> {
1678        let data = hex!("82b6636c6f7365496e707574546f6b656e4163636f756e74c2b86372656174654f7574707574546f6b656e4163636f756e74c3");
1679        let info = TransactionSettings {
1680            close_input_token_account: false,
1681            create_output_token_account: true,
1682        };
1683        let decoded: TransactionSettings = rmp_serde::from_slice(&data)?;
1684        assert_eq!(decoded, info);
1685
1686        Ok(())
1687    }
1688
1689    #[test]
1690    fn test_encode_route_plan_step() -> Result<(), EncError> {
1691        let data = hex!("88a6616d6d4b6579c42019fc949cf6d288d076e39f923bf6f1b45da023310e606afc40cc080d5b25983aa56c6162656cac4d6574656f726120444c4d4da9696e7075744d696e74c420069b8857feab8184fb687f634618c035dac439dc1aeb3b5598a0f00000000001aa6f75747075744d696e74c420c6fa7af3bedbad3a3d65f36aabc97431b1bbe4c2d2f6e0e47ca60203452f5d61a8696e416d6f756e74ce3b9aca00a96f7574416d6f756e74ce08d0ed70a8616c6c6f63507062ce3b9aca00ab636f6e74657874536c6f74ce00bc614e");
1692        let step = RoutePlanStep {
1693            amm_key: METEORA_DLMM_WSOL_USDC,
1694            label: "Meteora DLMM".into(),
1695            input_mint: WSOL_ADDR,
1696            output_mint: USDC_ADDR,
1697            in_amount: 1_000_000_000, // 1 SOL
1698            out_amount: 147_910_000,  // 147.91 USDC
1699            alloc_ppb: 1_000_000_000, // 100%
1700            fee_mint: None,
1701            fee_amount: None,
1702            context_slot: Some(12345678),
1703        };
1704
1705        let encoded = rmp_serde::to_vec_named(&step)?;
1706        assert_eq!(encoded, data);
1707
1708        Ok(())
1709    }
1710
1711    #[test]
1712    fn test_decode_route_plan_step() -> Result<(), DecError> {
1713        let data = hex!("88a6616d6d4b6579c42019fc949cf6d288d076e39f923bf6f1b45da023310e606afc40cc080d5b25983aa56c6162656cac4d6574656f726120444c4d4da9696e7075744d696e74c420069b8857feab8184fb687f634618c035dac439dc1aeb3b5598a0f00000000001aa6f75747075744d696e74c420c6fa7af3bedbad3a3d65f36aabc97431b1bbe4c2d2f6e0e47ca60203452f5d61a8696e416d6f756e74ce3b9aca00a96f7574416d6f756e74ce08d0ed70a8616c6c6f63507062ce3b9aca00ab636f6e74657874536c6f74ce00bc614e");
1714        let step = RoutePlanStep {
1715            amm_key: METEORA_DLMM_WSOL_USDC,
1716            label: "Meteora DLMM".into(),
1717            input_mint: WSOL_ADDR,
1718            output_mint: USDC_ADDR,
1719            in_amount: 1_000_000_000, // 1 SOL
1720            out_amount: 147_910_000,  // 147.91 USDC
1721            alloc_ppb: 1_000_000_000, // 100%
1722            fee_mint: None,
1723            fee_amount: None,
1724            context_slot: Some(12345678),
1725        };
1726
1727        let decoded: RoutePlanStep = rmp_serde::from_slice(&data)?;
1728        assert_eq!(decoded, step);
1729
1730        Ok(())
1731    }
1732
1733    #[test]
1734    fn test_encode_request_data() -> Result<(), EncError> {
1735        // GetInfo
1736        let data = hex!("81a7476574496e666f80");
1737        let req = RequestData::GetInfo(GetInfoRequest { dummy: None });
1738
1739        let encoded = rmp_serde::to_vec_named(&req)?;
1740        assert_eq!(encoded, data);
1741
1742        Ok(())
1743    }
1744
1745    #[test]
1746    fn test_decode_request_data() -> Result<(), DecError> {
1747        let data = hex!("81a7476574496e666f80");
1748        let req = RequestData::GetInfo(GetInfoRequest { dummy: None });
1749
1750        let decoded: RequestData = rmp_serde::from_slice(&data)?;
1751        assert_eq!(decoded, req);
1752
1753        Ok(())
1754    }
1755
1756    #[test]
1757    fn test_encode_server_message() -> Result<(), EncError> {
1758        let data = hex!("81a953747265616d456e6483a26964cd3039a96572726f72436f6465cd01f8ac6572726f724d657373616765bb626f622074726970706564206f7665722074686520726f75746572");
1759        let message = ServerMessage::StreamEnd(StreamEnd {
1760            id: 12345,
1761            error_code: Some(504),
1762            error_message: Some("bob tripped over the router".into()),
1763        });
1764
1765        let encoded = rmp_serde::to_vec_named(&message)?;
1766        assert_eq!(encoded, data);
1767
1768        Ok(())
1769    }
1770
1771    #[test]
1772    fn test_decode_server_message() -> Result<(), DecError> {
1773        let data = hex!("81a953747265616d456e6483a26964cd3039a96572726f72436f6465cd01f8ac6572726f724d657373616765bb626f622074726970706564206f7665722074686520726f75746572");
1774        let message = ServerMessage::StreamEnd(StreamEnd {
1775            id: 12345,
1776            error_code: Some(504),
1777            error_message: Some("bob tripped over the router".into()),
1778        });
1779
1780        let decoded: ServerMessage = rmp_serde::from_slice(&data)?;
1781        assert_eq!(decoded, message);
1782        Ok(())
1783    }
1784
1785    #[test]
1786    fn test_other_server_message() -> Result<(), DecError> {
1787        let unhandled = Value::Map(vec![(
1788            Value::from("SomeOtherWeirdMessageType"),
1789            Value::from(1),
1790        )]);
1791        let unhandled_data = rmp_serde::to_vec_named(&unhandled).expect("should encode");
1792        let decoded: ServerMessage = rmp_serde::from_slice(&unhandled_data)?;
1793        let unhandled_sm = ServerMessage::Other(unhandled);
1794        assert_eq!(decoded, unhandled_sm);
1795        Ok(())
1796    }
1797
1798    #[test]
1799    fn test_other_request_data() -> Result<(), DecError> {
1800        // client request
1801        let bad_request_data = Value::Map(vec![(
1802            Value::from("BadDataType"),
1803            Value::Map(vec![(Value::from("foo"), Value::from("bar"))]),
1804        )]);
1805        let unhandled = Value::Map(vec![
1806            (Value::from("id"), Value::from(1)),
1807            (Value::from("data"), bad_request_data.clone()),
1808        ]);
1809        let unhandled_data = rmp_serde::to_vec_named(&unhandled).expect("should encode");
1810        let decoded: ClientRequest = rmp_serde::from_slice(&unhandled_data)?;
1811        let unhandled_msg = ClientRequest {
1812            id: 1,
1813            data: RequestData::Other(bad_request_data),
1814        };
1815        assert_eq!(decoded, unhandled_msg);
1816        Ok(())
1817    }
1818
1819    #[test]
1820    fn test_swap_params_mesh_size_roundtrip() {
1821        let params = SwapParams {
1822            input_mint: WSOL_ADDR,
1823            output_mint: USDC_ADDR,
1824            amount: 1_000_000_000,
1825            mesh_size: Some(4),
1826            ..Default::default()
1827        };
1828        let json = serde_json::to_value(&params).unwrap();
1829        assert_eq!(json["meshSize"], serde_json::json!(4));
1830        let decoded: SwapParams = serde_json::from_value(json).unwrap();
1831        assert_eq!(decoded.mesh_size, Some(4));
1832
1833        // Absent: decodes to None, and is omitted when serializing.
1834        let omitted = serde_json::to_value(&SwapParams {
1835            input_mint: WSOL_ADDR,
1836            output_mint: USDC_ADDR,
1837            amount: 1,
1838            ..Default::default()
1839        })
1840        .unwrap();
1841        assert!(omitted.get("meshSize").is_none());
1842        let decoded: SwapParams = serde_json::from_value(omitted).unwrap();
1843        assert_eq!(decoded.mesh_size, None);
1844    }
1845
1846    #[test]
1847    fn test_swap_params_no_vote_accounts_roundtrip() {
1848        // Present and true: serializes to the camelCase `noVoteAccounts` key.
1849        let params = SwapParams {
1850            input_mint: WSOL_ADDR,
1851            output_mint: USDC_ADDR,
1852            amount: 1_000_000_000,
1853            no_vote_accounts: Some(true),
1854            ..Default::default()
1855        };
1856        let json = serde_json::to_value(&params).unwrap();
1857        assert_eq!(json["noVoteAccounts"], serde_json::json!(true));
1858        let decoded: SwapParams = serde_json::from_value(json).unwrap();
1859        assert_eq!(decoded.no_vote_accounts, Some(true));
1860
1861        // Absent: decodes to None (default), and is omitted when serializing.
1862        let decoded: SwapParams = serde_json::from_str(
1863            r#"{"inputMint":"So11111111111111111111111111111111111111112","outputMint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v","amount":1000000000}"#,
1864        )
1865        .unwrap();
1866        assert_eq!(decoded.no_vote_accounts, None);
1867
1868        let omitted = serde_json::to_value(&SwapParams {
1869            input_mint: WSOL_ADDR,
1870            output_mint: USDC_ADDR,
1871            amount: 1,
1872            ..Default::default()
1873        })
1874        .unwrap();
1875        assert!(omitted.get("noVoteAccounts").is_none());
1876    }
1877
1878    #[test]
1879    fn test_metadata_map() -> Result<(), DecError> {
1880        let mut metadata_map = HashMap::with_capacity(4);
1881        metadata_map.insert(
1882            String::from("StringFlag"),
1883            MetadataValue::String(String::from("StringValue")),
1884        );
1885        metadata_map.insert(String::from("IntFlag"), MetadataValue::Int(1234));
1886        metadata_map.insert(String::from("BoolFlag"), MetadataValue::Bool(true));
1887        metadata_map.insert(String::from("FloatFlag"), MetadataValue::Float(12.5));
1888        metadata_map.insert(
1889            String::from("ArrayFlag"),
1890            vec![1.into(), 2.into(), 3.into()].into(),
1891        );
1892        metadata_map.insert(
1893            String::from("MapFlag"),
1894            MetadataValue::from_iter([
1895                ("Key1", MetadataValue::Int(5)),
1896                ("Key2", MetadataValue::Bool(false)),
1897            ]),
1898        );
1899        let encoded = rmp_serde::to_vec_named(&metadata_map).expect("should encode");
1900        let decoded: HashMap<String, MetadataValue> = rmp_serde::from_slice(&encoded)?;
1901
1902        assert_eq!(decoded, metadata_map);
1903
1904        Ok(())
1905    }
1906}
1907
1908#[cfg(test)]
1909mod transaction_format_tests {
1910    use super::*;
1911
1912    #[test]
1913    fn transaction_format_defaults_to_v0() {
1914        assert_eq!(TransactionFormat::default(), TransactionFormat::V0);
1915    }
1916
1917    #[test]
1918    fn transaction_format_round_trips_through_u8() {
1919        assert_eq!(u8::from(TransactionFormat::V0), 0);
1920        assert_eq!(u8::from(TransactionFormat::V1), 1);
1921        assert_eq!(TransactionFormat::try_from(0u8), Ok(TransactionFormat::V0));
1922        assert_eq!(TransactionFormat::try_from(1u8), Ok(TransactionFormat::V1));
1923        assert_eq!(TransactionFormat::try_from(2u8), Err(2u8));
1924    }
1925
1926    /// An absent field must mean V0, so existing clients are unaffected.
1927    #[test]
1928    fn absent_transaction_format_is_none() {
1929        let params = TransactionParams::default();
1930        assert!(params.transaction_format.is_none());
1931        assert_eq!(
1932            params.transaction_format.unwrap_or_default(),
1933            TransactionFormat::V0
1934        );
1935    }
1936
1937    #[test]
1938    fn absent_transaction_config_is_none() {
1939        let template = TransactionTemplate::default();
1940        assert!(template.transaction_config.is_none());
1941    }
1942
1943    #[test]
1944    fn transaction_config_params_default_is_all_none() {
1945        let c = TransactionConfigParams::default();
1946        assert!(c.priority_fee.is_none());
1947        assert!(c.compute_unit_limit.is_none());
1948        assert!(c.loaded_accounts_data_size_limit.is_none());
1949        assert!(c.heap_size.is_none());
1950    }
1951
1952    /// `TransactionTemplate::transaction_config` crosses apollo -> CART as
1953    /// MessagePack under the renamed wire key `"c"`. If this key fails to
1954    /// round-trip, the config arrives as `None` on the other side and the
1955    /// transaction is sized against the wrong config-byte count -- the exact
1956    /// failure this feature exists to prevent.
1957    #[test]
1958    fn transaction_config_round_trips_through_messagepack_as_short_key_c() {
1959        let config = TransactionConfigParams {
1960            priority_fee: Some(12_345),
1961            compute_unit_limit: Some(600_000),
1962            loaded_accounts_data_size_limit: Some(4_194_304),
1963            heap_size: Some(32 * 1024),
1964        };
1965        let template = TransactionTemplate {
1966            instructions: Vec::new(),
1967            alts: Vec::new(),
1968            account_metas: Vec::new(),
1969            transaction_config: Some(config),
1970        };
1971
1972        let encoded =
1973            rmp_serde::to_vec_named(&template).expect("template should encode to messagepack");
1974
1975        // The config must survive the round trip intact, field for field.
1976        let decoded: TransactionTemplate =
1977            rmp_serde::from_slice(&encoded).expect("template should decode from messagepack");
1978        assert_eq!(decoded, template);
1979        assert_eq!(decoded.transaction_config, Some(config));
1980
1981        // The wire key must actually be the renamed short key "c", not the
1982        // Rust field name -- decode generically and inspect the map.
1983        let generic: rmpv::Value =
1984            rmp_serde::from_slice(&encoded).expect("template should decode as generic msgpack");
1985        let top_level = generic
1986            .as_map()
1987            .expect("a TransactionTemplate must encode as a msgpack map");
1988        let config_value = top_level
1989            .iter()
1990            .find(|(k, _)| k.as_str() == Some("c"))
1991            .map(|(_, v)| v)
1992            .expect("transaction_config must be encoded under the short key \"c\"");
1993        let config_map = config_value
1994            .as_map()
1995            .expect("transaction_config must encode as a msgpack map");
1996        assert!(
1997            config_map
1998                .iter()
1999                .any(|(k, _)| k.as_str() == Some("priorityFee")),
2000            "TransactionConfigParams fields must keep their camelCase wire names under \"c\""
2001        );
2002    }
2003
2004    /// `skip_serializing_if` on `transaction_config` must actually omit the
2005    /// key when the config is absent, not encode it as an explicit nil --
2006    /// otherwise every non-V1 request would carry a wasted "c" entry.
2007    #[test]
2008    fn absent_transaction_config_is_omitted_from_messagepack() {
2009        let template = TransactionTemplate {
2010            transaction_config: None,
2011            ..Default::default()
2012        };
2013
2014        let encoded =
2015            rmp_serde::to_vec_named(&template).expect("template should encode to messagepack");
2016
2017        let decoded: TransactionTemplate =
2018            rmp_serde::from_slice(&encoded).expect("template should decode from messagepack");
2019        assert!(decoded.transaction_config.is_none());
2020
2021        let generic: rmpv::Value =
2022            rmp_serde::from_slice(&encoded).expect("template should decode as generic msgpack");
2023        let top_level = generic
2024            .as_map()
2025            .expect("a TransactionTemplate must encode as a msgpack map");
2026        assert!(
2027            !top_level.iter().any(|(k, _)| k.as_str() == Some("c")),
2028            "\"c\" must be omitted entirely when transaction_config is None, found: {top_level:?}"
2029        );
2030    }
2031}