jup-ag-sdk 0.1.6

A Rust SDK for Jupiter exchange APIs.
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
use serde::{Deserialize, Serialize, Serializer};

use super::{DexEnum, dex_vec_to_comma_string};

/// A request struct for fetching a quote from Jupiter's `/quote` endpoint.
///
/// Use `QuoteRequest::new()` and the fluent setters to configure parameters.
///
/// [Official API docs](https://docs.jup.ag/apis/quote)
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QuoteRequest {
    /// The mint address of the input token.
    ///
    /// Example: `"So11111111111111111111111111111111111111112"` (SOL)
    pub input_mint: String,

    /// The mint address of the output token.
    ///
    /// Example: `"JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN"`
    pub output_mint: String,

    /// The amount to swap (raw, before decimals).
    ///
    /// Meaning depends on `swap_mode` ExactIn default :
    /// - `ExactIn`: amount of input token
    /// - `ExactOut`: amount of output token
    pub amount: u64,

    /// Slippage tolerance in basis points (bps).
    ///
    /// Example: `100` for 1% slippage.
    /// Optional; used only if `dyanmic_slippage` is `false`.
    pub slippage_bps: Option<u16>,

    /// Determines whether the amount is `ExactIn` or `ExactOut`.
    ///
    /// - `ExactIn`: guarantees input amount, computes output.
    /// - `ExactOut`: guarantees output amount, computes input.
    ///
    /// Default: `ExactIn`
    pub swap_mode: Option<QuoteGetSwapModeEnum>,

    /// A list of DEXes to exclusively include in routing.
    ///
    /// Example: `["Orca", "Meteora+DLMM"]`
    #[serde(serialize_with = "dex_vec_to_comma_string")]
    pub dexes: Option<Vec<DexEnum>>,

    /// A list of DEXes to exclude from routing.
    ///
    /// Example: `["Raydium", "Lifinity"]`
    #[serde(serialize_with = "dex_vec_to_comma_string")]
    pub exclude_dexes: Option<Vec<DexEnum>>,

    /// If true, restricts intermediate tokens to a stable set.
    ///
    /// Reduces slippage risk. Default: `true`.
    pub restrict_intermediate_tokens: Option<bool>,

    /// If true, only direct (single-hop) routes are allowed.
    ///
    /// May return suboptimal pricing. Default: `false`.
    pub only_direct_routes: Option<bool>,

    /// If true, the quote is prepared for legacy (v0) transactions.
    ///
    /// Use this if you're building a legacy transaction manually.
    pub as_legacy_transaction: Option<bool>,

    /// Platform fee in basis points (bps).
    ///
    /// Used with `feeAccount` in `/swap` to apply affiliate/platform fees.
    pub platform_fee_bps: Option<u64>,

    /// Upper bound on the number of accounts used in the quote.
    ///
    /// Helps with resource budgeting. Default: `64`
    pub max_accounts: Option<u8>,

    /// Enables Jupiter's dynamic slippage estimation.
    ///
    /// If true, overrides `slippage_bps`.
    pub dynamic_slippage: Option<bool>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum QuoteGetSwapModeEnum {
    ExactIn,
    ExactOut,
}

impl QuoteRequest {
    /// Creates a new `QuoteRequest` with the specified input mint, output mint, and amount.
    ///
    /// # Arguments
    /// * `input_mint` - The mint address of the input token (e.g., SOL mint).
    /// * `output_mint` - The mint address of the output token (e.g., JUP mint).
    /// * `amount` - The amount to swap (raw, before decimals). Meaning depends on `swap_mode`.
    ///
    /// # Returns
    /// A new `QuoteRequest` instance with None value for optional fields.
    ///
    /// # Example
    /// ```
    ///
    /// let request = QuoteRequest::new(
    ///     "So11111111111111111111111111111111111111112", // SOL
    ///     "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN", // JUP
    ///     1_000_000_000 // 1 SOL (9 decimals)
    /// );
    /// assert_eq!(request.input_mint, "So11111111111111111111111111111111111111112");
    /// assert_eq!(request.output_mint, "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN");
    /// assert_eq!(request.amount, 1_000_000_000);
    /// ```
    pub fn new(input_mint: &str, output_mint: &str, amount: u64) -> Self {
        Self {
            input_mint: input_mint.to_string(),
            output_mint: output_mint.to_string(),
            amount,
            slippage_bps: None,
            swap_mode: None,
            dexes: None,
            exclude_dexes: None,
            restrict_intermediate_tokens: None,
            only_direct_routes: None,
            as_legacy_transaction: None,
            platform_fee_bps: None,
            max_accounts: None,
            dynamic_slippage: None,
        }
    }

    /// Sets the slippage tolerance in basis points (bps).
    ///
    /// Only used if `dynamic_slippage` is `false`. 100 bps = 1% slippage.
    ///
    /// # Arguments
    /// * `slippage_bps` - Slippage tolerance in basis points (e.g., 50 for 0.5%).
    ///
    /// # Returns
    /// The modified `QuoteRequest` for chaining.
    ///
    /// # Example
    /// ```
    ///
    /// let request = QuoteRequest::new(
    ///     "So11111111111111111111111111111111111111112",
    ///     "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN",
    ///     1_000_000_000
    /// )
    /// .slippage_bps(100); // 1% slippage
    /// assert_eq!(request.slippage_bps, Some(100));
    /// ```
    pub fn slippage_bps(mut self, slippage_bps: u16) -> Self {
        self.slippage_bps = Some(slippage_bps);
        self
    }

    /// Sets the swap mode (`ExactIn` or `ExactOut`).
    ///
    /// - `ExactIn`: Specifies input amount, computes output.
    /// - `ExactOut`: Specifies output amount, computes input.
    ///
    /// # Arguments
    /// * `swap_mode` - The swap mode (`QuoteGetSwapModeEnum::ExactIn` or `ExactOut`).
    ///
    /// # Returns
    /// The modified `QuoteRequest` for chaining.
    ///
    /// # Example
    /// ```
    ///
    /// let request = QuoteRequest::new(
    ///     "So11111111111111111111111111111111111111112",
    ///     "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN",
    ///     1_000_000
    /// )
    /// .swap_mode(QuoteGetSwapModeEnum::ExactOut); // Want exactly 1 JUP output
    /// assert_eq!(request.swap_mode, Some(QuoteGetSwapModeEnum::ExactOut));
    /// ```
    pub fn swap_mode(mut self, swap_mode: QuoteGetSwapModeEnum) -> Self {
        self.swap_mode = Some(swap_mode);
        self
    }

    /// Sets the list of DEXes to exclusively include in routing.
    ///
    /// Only routes through these DEXes will be considered.
    ///
    /// # Arguments
    /// * `dexes` - A vector of DEX names (e.g., `["DexEnum::Orca", "DexEnum::MeteoraDlmm"]`).
    ///
    /// # Returns
    /// The modified `QuoteRequest` for chaining.
    ///
    /// # Example
    /// ```
    ///
    /// let request = QuoteRequest::new(
    ///     "So11111111111111111111111111111111111111112",
    ///     "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN",
    ///     1_000_000_000
    /// ).dexes(vec![DexEnum::MeteoraDlmm, DexEnum::Meteora]);
    /// ```
    /// [list of dexes](https://lite-api.jup.ag/swap/v1/program-id-to-label)
    pub fn dexes(mut self, dexes: Vec<DexEnum>) -> Self {
        self.dexes = Some(dexes);
        self
    }

    /// Sets the list of DEXes to exclude from routing. You can only specify one of `dexes` or `exclude_dexes` not both at the same time.
    ///
    /// Routes will avoid these DEXes.
    ///
    /// # Arguments
    /// * `exclude_dexes` - A vector of DEX names to exclude (e.g., `[DexEnum::Raydium, DexEnum::OrcaV2]`).
    ///
    /// # Returns
    /// The modified `QuoteRequest` for chaining.
    ///
    /// # Example
    /// ```
    /// use quote_request::{QuoteRequest, QuoteRequestBuilder};
    ///
    /// let request = QuoteRequest::new(
    ///     "So11111111111111111111111111111111111111112",
    ///     "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN",
    ///     1_000_000_000
    /// ).exclude_dexes(vec![DexEnum::Raydium, DexEnum::OrcaV2]);
    /// ```
    /// [list of dexes](https://lite-api.jup.ag/swap/v1/program-id-to-label)
    pub fn exclude_dexes(mut self, exclude_dexes: Vec<DexEnum>) -> Self {
        self.exclude_dexes = Some(exclude_dexes);
        self
    }

    /// Sets whether to restrict intermediate tokens to a stable set.
    ///
    /// Reduces slippage risk by limiting intermediate tokens. Default: `true`.
    ///
    /// # Arguments
    /// * `restrict_intermediate_tokens` - Whether to restrict intermediate tokens.
    ///
    /// # Returns
    /// The modified `QuoteRequest` for chaining.
    ///
    /// # Example
    /// ```
    /// use quote_request::{QuoteRequest, QuoteRequestBuilder};
    ///
    /// let request = QuoteRequest::new(
    ///     "So11111111111111111111111111111111111111112",
    ///     "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN",
    ///     1_000_000_000
    /// )
    /// .restrict_intermediate_tokens(true);
    /// assert_eq!(request.restrict_intermediate_tokens, Some(true));
    /// ```
    pub fn restrict_intermediate_tokens(mut self, restrict_intermediate_tokens: bool) -> Self {
        self.restrict_intermediate_tokens = Some(restrict_intermediate_tokens);
        self
    }

    /// Sets whether to allow only direct (single-hop) routes.
    ///
    /// May result in suboptimal pricing. Default: `false`.
    ///
    /// # Arguments
    /// * `only_direct_routes` - Whether to allow only direct routes.
    ///
    /// # Returns
    /// The modified `QuoteRequest` for chaining.
    ///
    /// # Example
    /// ```
    ///
    /// let request = QuoteRequest::new(
    ///     "So11111111111111111111111111111111111111112",
    ///     "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN",
    ///     1_000_000_000
    /// )
    /// .only_direct_routes(true);
    /// assert_eq!(request.only_direct_routes, Some(true));
    /// ```
    pub fn only_direct_routes(mut self, only_direct_routes: bool) -> Self {
        self.only_direct_routes = Some(only_direct_routes);
        self
    }

    /// Sets whether the quote is prepared for legacy (v0) transactions.
    ///
    /// Use for manually building legacy transactions.
    ///
    /// # Arguments
    /// * `as_legacy_transaction` - Whether to prepare for legacy transactions.
    ///
    /// # Returns
    /// The modified `QuoteRequest` for chaining.
    ///
    /// # Example
    /// ```
    ///
    /// let request = QuoteRequest::new(
    ///     "So11111111111111111111111111111111111111112",
    ///     "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN",
    ///     1_000_000_000
    /// )
    /// .as_legacy_transaction(true);
    /// assert_eq!(request.as_legacy_transaction, Some(true));
    /// ```
    pub fn as_legacy_transaction(mut self, as_legacy_transaction: bool) -> Self {
        self.as_legacy_transaction = Some(as_legacy_transaction);
        self
    }

    /// Sets the platform fee in basis points (bps).
    ///
    /// Used with `feeAccount` in `/swap` for affiliate/platform fees.
    ///
    /// # Arguments
    /// * `platform_fee_bps` - The platform fee in basis points.
    ///
    /// # Returns
    /// The modified `QuoteRequest` for chaining.
    ///
    /// # Example
    /// ```
    ///
    /// let request = QuoteRequest::new(
    ///     "So11111111111111111111111111111111111111112",
    ///     "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN",
    ///     1_000_000_000
    /// )
    /// .platform_fee_bps(20); // 0.2% fee
    /// assert_eq!(request.platform_fee_bps, Some(20));
    /// ```
    pub fn platform_fee_bps(mut self, platform_fee_bps: u64) -> Self {
        self.platform_fee_bps = Some(platform_fee_bps);
        self
    }

    /// Sets the upper bound on the number of accounts used in the quote.
    ///
    /// This helps budget resources for the transaction, as some routes may require more accounts.
    /// The default value is typically 64, but you can specify a lower or higher value depending on your needs.
    ///
    /// # Arguments
    /// * `self` - The `QuoteRequest` instance (mutable, consumed by the method).
    /// * `max_accounts` - The maximum number of accounts to use in the quote (e.g., 32 for resource-constrained transactions).
    ///
    /// # Returns
    /// The modified `QuoteRequest` instance for method chaining.
    ///
    /// # Example
    /// ```
    ///
    /// let request = QuoteRequest::new(
    ///     "So11111111111111111111111111111111111111112", // SOL
    ///     "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN", // JUP
    ///     1_000_000_000 // 1 SOL
    /// )
    /// .max_accounts(32);
    /// assert_eq!(request.max_accounts, Some(32));
    /// ```
    pub fn max_accounts(mut self, max_accounts: u8) -> Self {
        self.max_accounts = Some(max_accounts);
        self
    }

    /// Sets whether to enable Jupiter's dynamic slippage estimation.
    ///
    /// When enabled, this overrides the `slippage_bps` setting, allowing Jupiter to dynamically adjust
    /// slippage based on market conditions. This can reduce the risk of failed transactions due to price volatility.
    ///
    /// # Arguments
    /// * `self` - The `QuoteRequest` instance (mutable, consumed by the method).
    /// * `dynamic_slippage` - Whether to enable dynamic slippage estimation (true to enable, false to use `slippage_bps`).
    ///
    /// # Returns
    /// The modified `QuoteRequest` instance for method chaining.
    ///
    /// # Example
    /// ```
    ///
    /// let request = QuoteRequest::new(
    ///     "So11111111111111111111111111111111111111112", // SOL
    ///     "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN", // JUP
    ///     1_000_000_000 // 1 SOL
    /// )
    /// .dynamic_slippage(true);
    /// assert_eq!(request.dynamic_slippage, Some(true));
    /// ```
    pub fn dynamic_slippage(mut self, dynamic_slippage: bool) -> Self {
        self.dynamic_slippage = Some(dynamic_slippage);
        self
    }
}

pub fn vec_to_comma_string<S>(vec: &Option<Vec<String>>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    match vec {
        Some(v) => serializer.serialize_str(&v.join(",")),
        None => serializer.serialize_none(),
    }
}