multiliquid-svm-sdk 0.1.2

Unsigned transaction builders, account codecs, and quoting for Multiliquid on Solana
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! Native counterparts of the npm SDK's public types.
//!
//! Account aliases deliberately preserve the checked-in IDL's field names and
//! fixed-size arrays. NAV descriptions use the variants of [`NavData`] instead
//! of JavaScript's single-key wrapper objects.

use std::{fmt, str::FromStr, sync::Arc};

use serde::{Deserialize, Serialize};
use solana_sdk::{
    instruction::{AccountMeta, Instruction},
    pubkey::Pubkey,
    transaction::VersionedTransaction,
};

use crate::{error::SdkError, rpc::Rpc};

pub use crate::errors::{ParsedSwapError, SwapErrorCategory};
pub use crate::generated::swap::{
    AssetConfig as AssetConfigAccount, AssetType, ExactMode, GlobalConfig as GlobalConfigAccount,
    LpProtocolFeeConfig as LpProtocolFeeConfigAccount, LpStableConfig as LpStableConfigAccount,
    NavData, Pair as PairAccount, SwapDirection, SwapExecuted as SwapExecutedEvent, SwapType,
};
pub use crate::rpc::Rpc as MultiliquidRpcApi;

pub type MultiliquidInstruction = Instruction;
pub type MultiliquidRpc = Arc<dyn Rpc>;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub enum Cluster {
    #[default]
    #[serde(rename = "devnet")]
    Devnet,
    #[serde(rename = "mainnet-beta")]
    MainnetBeta,
}

impl Cluster {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Devnet => "devnet",
            Self::MainnetBeta => "mainnet-beta",
        }
    }
}

impl fmt::Display for Cluster {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for Cluster {
    type Err = SdkError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "devnet" => Ok(Self::Devnet),
            "mainnet-beta" => Ok(Self::MainnetBeta),
            _ => Err(SdkError::InvalidInput(format!(
                "unsupported cluster: {value}"
            ))),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum NavDataKind {
    U64FixedAddress = 0,
    Hardcoded = 1,
    PythPush = 2,
    RedstonePush = 3,
}

impl From<&NavData> for NavDataKind {
    fn from(value: &NavData) -> Self {
        match value {
            NavData::U64FixedAddress { .. } => Self::U64FixedAddress,
            NavData::Hardcoded { .. } => Self::Hardcoded,
            NavData::PythPush { .. } => Self::PythPush,
            NavData::RedstonePush { .. } => Self::RedstonePush,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedSwapPair {
    pub pair_address: Pubkey,
    pub pair: PairAccount,
    pub input_mint: Pubkey,
    pub output_mint: Pubkey,
    pub quote_mint: Pubkey,
    pub base_mint: Pubkey,
    pub swap_direction: SwapDirection,
}

#[derive(Debug, Clone)]
pub struct SwapParams {
    pub user: Pubkey,
    pub liquidity_provider: Pubkey,
    pub input_mint: Pubkey,
    pub output_mint: Pubkey,
    /// Selects a deployed pair when both LP/mint orderings exist.
    pub pair_address: Option<Pubkey>,
    pub amount: u64,
    pub swap_type: SwapType,
    pub min_amount_out: Option<u64>,
    pub max_amount_in: Option<u64>,
    pub user_input_token_account: Option<Pubkey>,
    pub user_output_token_account: Option<Pubkey>,
    /// Builders treat `None` as `true`.
    pub auto_create_ata: Option<bool>,
    pub remaining_accounts: Option<Vec<AccountMeta>>,
}

pub type BuildSwapTransactionParams = SwapParams;

#[derive(Debug, Clone)]
pub struct UpdatePairParams {
    pub liquidity_provider: Pubkey,
    pub mint_a: Pubkey,
    pub mint_b: Pubkey,
    pub pair_address: Option<Pubkey>,
    pub redemption_fee_bps: u16,
    pub discount_rate_bps: u16,
    pub paused: bool,
}

pub type BuildUpdatePairTransactionParams = UpdatePairParams;

#[derive(Debug, Clone)]
pub struct InitPairParams {
    pub liquidity_provider: Pubkey,
    pub mint_a: Pubkey,
    pub mint_b: Pubkey,
    pub redemption_fee_bps: u16,
    pub discount_rate_bps: u16,
}

pub type BuildInitPairTransactionParams = InitPairParams;

#[derive(Debug, Clone)]
pub struct ClosePairParams {
    pub liquidity_provider: Pubkey,
    pub mint_a: Pubkey,
    pub mint_b: Pubkey,
    pub pair_address: Option<Pubkey>,
    /// Optional cached global-config admin; this account does not sign.
    pub admin: Option<Pubkey>,
    pub lp_mint_a_token_account: Option<Pubkey>,
    pub lp_mint_b_token_account: Option<Pubkey>,
    /// Defaults to true. Transfer-hook recipients may need to exist already.
    pub auto_create_ata: Option<bool>,
    pub remaining_accounts: Option<Vec<AccountMeta>>,
}

pub type BuildClosePairTransactionParams = ClosePairParams;

#[derive(Debug, Clone)]
pub struct LpLiquidityParams {
    pub liquidity_provider: Pubkey,
    pub mint: Pubkey,
    pub amount: u64,
    /// Execution-time treasury bound, with no SDK-computed default.
    /// Add liquidity is always ExactIn: minimum treasury tokens minted.
    /// Remove ExactIn: minimum asset output; ExactOut: maximum treasury tokens burned.
    /// Ignored by the program when no treasury deposit or redemption occurs.
    pub amount_threshold: Option<u64>,
    pub exact_mode: Option<ExactMode>,
    pub lp_token_account: Option<Pubkey>,
    /// Defaults to true; add liquidity also creates the vault ATA if needed.
    pub auto_create_ata: Option<bool>,
    pub remaining_accounts: Option<Vec<AccountMeta>>,
}

pub type BuildAddLiquidityTransactionParams = LpLiquidityParams;
pub type BuildRemoveLiquidityTransactionParams = LpLiquidityParams;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SwapQuote {
    pub amount_in: u64,
    pub amount_out: u64,
    pub protocol_fees: u64,
    pub issuer_protocol_fees: u64,
    pub spread_protocol_fees: u64,
    pub discount_amount: u64,
    pub amount_in_for_vault: u64,
    pub input_nav: u64,
    pub output_nav: u64,
    pub fee_token_mint: Pubkey,
    pub fee_token_nav: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SimulationQuote {
    pub amount_in: u64,
    pub amount_out: u64,
    pub protocol_fee: u64,
    pub discount_bps: u16,
    pub pair: Pubkey,
    pub input_mint: Pubkey,
    pub output_mint: Pubkey,
    pub swap_type: SwapType,
    pub compute_units_consumed: u64,
}

#[derive(Debug, Clone)]
pub struct BuildSwapInstructionResult {
    pub instruction: Instruction,
    pub setup_instructions: Vec<Instruction>,
    pub accounts: SwapAccountKeys,
    pub onchain_direction: SwapDirection,
    /// Present when the compiled treasury CPI path is enabled for this LP.
    pub treasury_program_address: Option<Pubkey>,
    pub has_protocol_fee_transfer: bool,
}

#[derive(Debug, Clone)]
pub struct BuildSwapTransactionResult {
    pub transaction: VersionedTransaction,
    pub accounts: SwapAccountKeys,
    pub onchain_direction: SwapDirection,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpdatePairAccountKeys {
    pub liquidity_provider: Pubkey,
    pub pair: Pubkey,
    pub quote_token_mint_address: Pubkey,
    pub base_token_mint_address: Pubkey,
    pub global_config: Pubkey,
}

#[derive(Debug, Clone)]
pub struct BuildUpdatePairInstructionResult {
    pub instruction: Instruction,
    pub accounts: UpdatePairAccountKeys,
}

#[derive(Debug, Clone)]
pub struct BuildUpdatePairTransactionResult {
    pub transaction: VersionedTransaction,
    pub accounts: UpdatePairAccountKeys,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InitPairAccountKeys {
    pub liquidity_provider: Pubkey,
    pub pair: Pubkey,
    pub quote_token_mint_address: Pubkey,
    pub base_token_mint_address: Pubkey,
    pub lp_vault_authority: Pubkey,
    pub lp_fee_vault_authority: Pubkey,
    pub quote_token_vault_token_account: Pubkey,
    pub base_token_vault_token_account: Pubkey,
    pub lp_vault_quote_pda: Pubkey,
    pub lp_vault_base_pda: Pubkey,
    pub global_config: Pubkey,
    pub fee_token_mint_address: Pubkey,
    pub lp_fee_token_account: Pubkey,
    pub lp_stable_config_quote: Pubkey,
    pub lp_stable_config_base: Pubkey,
    pub quote_asset_config: Pubkey,
    pub base_asset_config: Pubkey,
    pub token_program_quote: Pubkey,
    pub token_program_base: Pubkey,
    pub token_program_fee: Pubkey,
    pub associated_token_program: Pubkey,
    pub system_program: Pubkey,
}

#[derive(Debug, Clone)]
pub struct BuildInitPairInstructionResult {
    pub instruction: Instruction,
    pub accounts: InitPairAccountKeys,
}

#[derive(Debug, Clone)]
pub struct BuildInitPairTransactionResult {
    pub transaction: VersionedTransaction,
    pub accounts: InitPairAccountKeys,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClosePairAccountKeys {
    pub admin: Pubkey,
    pub liquidity_provider: Pubkey,
    pub pair: Pubkey,
    pub quote_token_mint_address: Pubkey,
    pub base_token_mint_address: Pubkey,
    pub lp_vault_authority: Pubkey,
    pub quote_token_vault_token_account: Pubkey,
    pub base_token_vault_token_account: Pubkey,
    pub lp_quote_token_account: Pubkey,
    pub lp_base_token_account: Pubkey,
    pub lp_vault_quote_pda: Pubkey,
    pub lp_vault_base_pda: Pubkey,
    pub quote_asset_config: Pubkey,
    pub base_asset_config: Pubkey,
    pub global_config: Pubkey,
    pub lp_protocol_fee_config: Pubkey,
    pub treasury_user_position: Pubkey,
    pub token_program_quote: Pubkey,
    pub token_program_base: Pubkey,
    pub remaining_accounts: Vec<AccountMeta>,
}

#[derive(Debug, Clone)]
pub struct BuildClosePairInstructionResult {
    pub instruction: Instruction,
    pub setup_instructions: Vec<Instruction>,
    pub accounts: ClosePairAccountKeys,
}

#[derive(Debug, Clone)]
pub struct BuildClosePairTransactionResult {
    pub transaction: VersionedTransaction,
    pub accounts: ClosePairAccountKeys,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiquidityAccountKeys {
    pub liquidity_provider: Pubkey,
    pub mint_address: Pubkey,
    pub lp_token_account: Pubkey,
    pub vault_token_account: Pubkey,
    pub lp_vault_authority: Pubkey,
    pub global_config: Pubkey,
    pub lp_protocol_fee_config: Pubkey,
    pub asset_config: Pubkey,
    pub lp_stable_config: Pubkey,
    pub token_program: Pubkey,
    pub remaining_accounts: Vec<Pubkey>,
}

#[derive(Debug, Clone)]
pub struct BuildAddLiquidityInstructionResult {
    pub instruction: Instruction,
    pub setup_instructions: Vec<Instruction>,
    pub accounts: LiquidityAccountKeys,
}

#[derive(Debug, Clone)]
pub struct BuildAddLiquidityTransactionResult {
    pub transaction: VersionedTransaction,
    pub accounts: LiquidityAccountKeys,
}

#[derive(Debug, Clone)]
pub struct BuildRemoveLiquidityInstructionResult {
    pub instruction: Instruction,
    pub setup_instructions: Vec<Instruction>,
    pub accounts: LiquidityAccountKeys,
}

#[derive(Debug, Clone)]
pub struct BuildRemoveLiquidityTransactionResult {
    pub transaction: VersionedTransaction,
    pub accounts: LiquidityAccountKeys,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SwapAccountKeys {
    pub user: Pubkey,
    pub pair: Pubkey,
    pub program_authority: Pubkey,
    pub liquidity_provider: Pubkey,
    pub lp_vault_authority: Pubkey,
    pub lp_fee_vault_authority: Pubkey,
    pub input_token_mint_address: Pubkey,
    pub output_token_mint_address: Pubkey,
    pub input_token_user_token_account: Pubkey,
    pub output_token_user_token_account: Pubkey,
    pub input_token_vault_token_account: Pubkey,
    pub output_token_vault_token_account: Pubkey,
    pub global_config: Pubkey,
    pub fee_token_mint_address: Pubkey,
    pub lp_fee_token_account: Pubkey,
    pub fee_token_account: Pubkey,
    pub input_config: Pubkey,
    pub output_config: Pubkey,
    pub fee_config: Pubkey,
    pub input_lp_stable_config: Pubkey,
    pub output_lp_stable_config: Pubkey,
    pub lp_protocol_fee_config: Pubkey,
    pub token_program_input: Pubkey,
    pub token_program_output: Pubkey,
    pub token_program_fee: Pubkey,
    pub remaining_accounts: Vec<Pubkey>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PairRegistryEntry {
    #[serde(with = "pubkey_string")]
    pub pair: Pubkey,
    #[serde(with = "pubkey_string")]
    pub liquidity_provider: Pubkey,
    #[serde(
        default,
        with = "optional_pubkey_string",
        skip_serializing_if = "Option::is_none"
    )]
    pub vault_authority: Option<Pubkey>,
    #[serde(with = "pubkey_string")]
    pub quote_mint: Pubkey,
    #[serde(with = "pubkey_string")]
    pub base_mint: Pubkey,
    pub quote_decimals: u8,
    pub base_decimals: u8,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransferHookRegistryEntry {
    #[serde(with = "pubkey_string")]
    pub mint: Pubkey,
    #[serde(with = "pubkey_string")]
    pub hook_program: Pubkey,
    #[serde(with = "pubkey_string")]
    pub extra_account_meta_list: Pubkey,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct PairRegistry {
    pub devnet: Vec<PairRegistryEntry>,
    #[serde(rename = "mainnet-beta")]
    pub mainnet_beta: Vec<PairRegistryEntry>,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PairFilters {
    pub quote_mint: Option<Pubkey>,
    pub base_mint: Option<Pubkey>,
    pub liquidity_provider: Option<Pubkey>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PairRegistryErrorContext {
    pub cluster: Cluster,
    pub registry_api_url: String,
}

pub type PairRegistryErrorHandler = Arc<dyn Fn(&SdkError, &PairRegistryErrorContext) + Send + Sync>;

/// Registry fetch configuration. The supplied RPC owns its commitment policy.
/// Cancel a fetch by dropping its future; there is no JavaScript `AbortSignal`.
#[derive(Clone, Default)]
pub struct PairRegistryFetchOptions {
    pub registry_api_url: Option<String>,
    pub rpc: Option<MultiliquidRpc>,
    pub timeout_ms: Option<u64>,
    pub on_error: Option<PairRegistryErrorHandler>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PauseStatus {
    pub global_paused: bool,
    pub pair_paused: bool,
    pub input_paused: bool,
    pub output_paused: bool,
    pub fee_paused: bool,
    pub input_lp_paused: bool,
    pub output_lp_paused: bool,
    pub any_paused: bool,
    pub pause_reasons: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SwapMathResult {
    pub protocol_fees: u64,
    pub protocol_fee_basis: u64,
    pub discount_amount: u64,
    pub amount_in_for_vault: u64,
    pub amount_out: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SwapState {
    pub global_config: GlobalConfigAccount,
    pub pair_address: Pubkey,
    pub pair: PairAccount,
    pub onchain_direction: SwapDirection,
    pub input_config: AssetConfigAccount,
    pub output_config: AssetConfigAccount,
    pub input_lp_stable_config: Option<LpStableConfigAccount>,
    pub output_lp_stable_config: Option<LpStableConfigAccount>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OracleResolutionResult {
    pub remaining_accounts: Vec<AccountMeta>,
}

mod pubkey_string {
    use super::*;
    use serde::{de::Error, Deserializer, Serializer};

    pub fn serialize<S: Serializer>(key: &Pubkey, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(key)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Pubkey, D::Error> {
        String::deserialize(deserializer)?
            .parse()
            .map_err(D::Error::custom)
    }
}

mod optional_pubkey_string {
    use super::*;
    use serde::{de::Error, Deserializer, Serializer};

    struct PubkeyString<'a>(&'a Pubkey);

    impl Serialize for PubkeyString<'_> {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            serializer.collect_str(self.0)
        }
    }

    pub fn serialize<S: Serializer>(
        key: &Option<Pubkey>,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        match key {
            Some(key) => serializer.serialize_some(&PubkeyString(key)),
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Option<Pubkey>, D::Error> {
        Option::<String>::deserialize(deserializer)?
            .map(|key| key.parse().map_err(D::Error::custom))
            .transpose()
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn registry_json_uses_base58_addresses_and_original_api_field_names() {
        let pair = Pubkey::new_unique();
        let lp = Pubkey::new_unique();
        let quote = Pubkey::new_unique();
        let base = Pubkey::new_unique();
        let vault = Pubkey::new_unique();
        let payload = json!({
            "devnet": [{
                "pair": pair.to_string(),
                "liquidityProvider": lp.to_string(),
                "vaultAuthority": vault.to_string(),
                "quoteMint": quote.to_string(),
                "baseMint": base.to_string(),
                "quoteDecimals": 6,
                "baseDecimals": 9,
            }],
            "mainnet-beta": [],
        });
        let registry: PairRegistry = serde_json::from_value(payload.clone()).unwrap();
        assert_eq!(
            registry.devnet[0],
            PairRegistryEntry {
                pair,
                liquidity_provider: lp,
                vault_authority: Some(vault),
                quote_mint: quote,
                base_mint: base,
                quote_decimals: 6,
                base_decimals: 9,
                label: None,
            }
        );
        assert_eq!(serde_json::to_value(registry).unwrap(), payload);

        let mut invalid = payload;
        invalid["devnet"][0]["pair"] = json!("not-a-solana-address");
        assert!(serde_json::from_value::<PairRegistry>(invalid).is_err());
    }
}