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
//! Cluster-aware convenience API over the native, read-only SDK modules.
//!
//! PDA and formatting helpers are synchronous. RPC operations are asynchronous,
//! use the supplied transport's commitment, and are cancelled by dropping their
//! futures. Builders return unsigned instructions or transactions; they never
//! sign, submit, or require a wallet.

use solana_sdk::pubkey::Pubkey;

#[cfg(feature = "http")]
use crate::types::PairRegistryFetchOptions;
use crate::{
    accounts,
    constants::{
        PROGRAM_ADDRESS_DEVNET, PROGRAM_ADDRESS_MAINNET, SPL_TOKEN_PROGRAM_ADDRESS,
        TREASURY_PROGRAM_ADDRESS_DEVNET, TREASURY_PROGRAM_ADDRESS_MAINNET,
    },
    error::Result,
    errors::{self, ParsedSimulationProgramError},
    events, format, lp, pda, quote, registry, swap,
    types::{
        AssetConfigAccount, BuildAddLiquidityInstructionResult, BuildAddLiquidityTransactionParams,
        BuildAddLiquidityTransactionResult, BuildClosePairInstructionResult,
        BuildClosePairTransactionParams, BuildClosePairTransactionResult,
        BuildInitPairInstructionResult, BuildInitPairTransactionParams,
        BuildInitPairTransactionResult, BuildRemoveLiquidityInstructionResult,
        BuildRemoveLiquidityTransactionParams, BuildRemoveLiquidityTransactionResult,
        BuildSwapInstructionResult, BuildSwapTransactionParams, BuildSwapTransactionResult,
        BuildUpdatePairInstructionResult, BuildUpdatePairTransactionParams,
        BuildUpdatePairTransactionResult, ClosePairParams, Cluster, GlobalConfigAccount,
        InitPairParams, LpLiquidityParams, LpStableConfigAccount, MultiliquidRpc, PairAccount,
        PairFilters, PairRegistryEntry, PairRegistryErrorHandler, PauseStatus, SimulationQuote,
        SwapExecutedEvent, SwapParams, SwapQuote, SwapState, UpdatePairParams,
    },
};

/// Optional client defaults plus a required caller-selected RPC transport.
///
/// Construct with [`Self::new`], then override individual fields. The default
/// cluster is devnet. A custom swap program does not change the cluster's
/// registry or treasury program; treasury CPI accounts are resolved from native
/// account state by the builders.
#[derive(Clone)]
pub struct MultiliquidClientConfig {
    pub rpc: MultiliquidRpc,
    pub program_address: Option<Pubkey>,
    pub cluster: Option<Cluster>,
    pub registry_api_url: Option<String>,
    pub registry_fetch_timeout_ms: Option<u64>,
    pub on_registry_error: Option<PairRegistryErrorHandler>,
}

impl MultiliquidClientConfig {
    pub fn new(rpc: MultiliquidRpc) -> Self {
        Self {
            rpc,
            program_address: None,
            cluster: None,
            registry_api_url: None,
            registry_fetch_timeout_ms: None,
            on_registry_error: None,
        }
    }
}

/// Native counterpart of the npm `MultiliquidClient`.
///
/// All account codecs and builders target the bundled audited production ABI.
/// Liquidity and treasury bounds are caller-supplied, with no automatic slippage
/// limits. Cloning the client shares its RPC and callbacks.
///
/// ```no_run
/// # #[cfg(feature = "http")]
/// # {
/// use std::sync::Arc;
/// use multiliquid_svm_sdk::{
///     Cluster, CommitmentConfig, HttpRpcClient, MultiliquidClient,
///     MultiliquidClientConfig,
/// };
///
/// let rpc = Arc::new(HttpRpcClient::new(
///     "https://api.mainnet-beta.solana.com",
///     CommitmentConfig::confirmed(),
/// ));
/// let mut config = MultiliquidClientConfig::new(rpc);
/// config.cluster = Some(Cluster::MainnetBeta);
/// let client = MultiliquidClient::new(config);
/// let (global_config, bump) = client.derive_global_config();
/// # }
/// ```
///
/// With `default-features = false`, supply `Arc::new(your_rpc)` implementing
/// [`crate::Rpc`]. All methods except HTTP registry `get_pairs` remain
/// available, including RPC discovery and the bundled offline registry.
#[derive(Clone)]
pub struct MultiliquidClient {
    pub rpc: MultiliquidRpc,
    pub program_address: Pubkey,
    pub treasury_program_address: Pubkey,
    pub cluster: Cluster,
    pub registry_api_url: String,
    pub registry_fetch_timeout_ms: Option<u64>,
    pub on_registry_error: Option<PairRegistryErrorHandler>,
}

impl MultiliquidClient {
    pub fn new(config: MultiliquidClientConfig) -> Self {
        let cluster = config.cluster.unwrap_or(Cluster::Devnet);
        let (program_address, treasury_program_address) = match cluster {
            Cluster::Devnet => (PROGRAM_ADDRESS_DEVNET, TREASURY_PROGRAM_ADDRESS_DEVNET),
            Cluster::MainnetBeta => (PROGRAM_ADDRESS_MAINNET, TREASURY_PROGRAM_ADDRESS_MAINNET),
        };
        Self {
            rpc: config.rpc,
            program_address: config.program_address.unwrap_or(program_address),
            treasury_program_address,
            cluster,
            registry_api_url: config
                .registry_api_url
                .unwrap_or_else(|| registry::DEFAULT_REGISTRY_API_URL.to_owned()),
            registry_fetch_timeout_ms: config.registry_fetch_timeout_ms,
            on_registry_error: config.on_registry_error,
        }
    }

    /// Fetch the API registry, falling back to filtered bundled entries on failure.
    ///
    /// Each `Some` per-call option overrides the corresponding client setting;
    /// `None` inherits it. In particular, `Some(0)` disables the HTTP timeout.
    /// An overridden RPC brings its own commitment policy. The custom swap
    /// program does not change the cluster-based registry; use
    /// [`Self::discover_pairs`] to discover that program's accounts instead.
    #[cfg(feature = "http")]
    pub async fn get_pairs(
        &self,
        filters: Option<&PairFilters>,
        options: Option<&PairRegistryFetchOptions>,
    ) -> Result<Vec<PairRegistryEntry>> {
        let options = PairRegistryFetchOptions {
            registry_api_url: Some(
                options
                    .and_then(|options| options.registry_api_url.as_ref())
                    .unwrap_or(&self.registry_api_url)
                    .clone(),
            ),
            rpc: Some(
                options
                    .and_then(|options| options.rpc.as_ref())
                    .unwrap_or(&self.rpc)
                    .clone(),
            ),
            timeout_ms: options
                .and_then(|options| options.timeout_ms)
                .or(self.registry_fetch_timeout_ms),
            on_error: options
                .and_then(|options| options.on_error.as_ref())
                .or(self.on_registry_error.as_ref())
                .cloned(),
        };
        registry::get_pairs(self.cluster, filters, &options).await
    }

    pub fn get_offline_pairs(&self, filters: Option<&PairFilters>) -> Vec<PairRegistryEntry> {
        registry::get_offline_pairs(self.cluster, filters)
    }

    pub async fn discover_pairs(
        &self,
        filters: Option<&PairFilters>,
    ) -> Result<Vec<PairRegistryEntry>> {
        registry::discover_pairs(self.rpc.as_ref(), &self.program_address, filters).await
    }

    pub async fn fetch_global_config(&self) -> Result<GlobalConfigAccount> {
        accounts::fetch_global_config(self.rpc.as_ref(), &self.program_address, None).await
    }

    pub async fn fetch_pair(&self, account_address: &Pubkey) -> Result<PairAccount> {
        accounts::fetch_pair(self.rpc.as_ref(), account_address).await
    }

    pub async fn fetch_asset_config(&self, account_address: &Pubkey) -> Result<AssetConfigAccount> {
        accounts::fetch_asset_config(self.rpc.as_ref(), account_address).await
    }

    pub async fn fetch_lp_stable_config(
        &self,
        account_address: &Pubkey,
    ) -> Result<LpStableConfigAccount> {
        accounts::fetch_lp_stable_config(self.rpc.as_ref(), account_address).await
    }

    pub async fn fetch_swap_state(
        &self,
        input_mint: &Pubkey,
        output_mint: &Pubkey,
        liquidity_provider: &Pubkey,
        pair_address: Option<&Pubkey>,
    ) -> Result<SwapState> {
        accounts::fetch_swap_state(
            self.rpc.as_ref(),
            input_mint,
            output_mint,
            liquidity_provider,
            &self.program_address,
            pair_address,
        )
        .await
    }

    pub async fn check_pause_status(
        &self,
        input_mint: &Pubkey,
        output_mint: &Pubkey,
        liquidity_provider: &Pubkey,
        pair_address: Option<&Pubkey>,
    ) -> Result<PauseStatus> {
        accounts::check_pause_status(
            self.rpc.as_ref(),
            input_mint,
            output_mint,
            liquidity_provider,
            &self.program_address,
            pair_address,
        )
        .await
    }

    pub fn derive_global_config(&self) -> (Pubkey, u8) {
        pda::derive_global_config(&self.program_address)
    }

    pub fn derive_asset_config(&self, mint: &Pubkey) -> (Pubkey, u8) {
        pda::derive_asset_config(mint, &self.program_address)
    }

    /// Preserve the supplied on-chain mint order; this does not sort the pair.
    pub fn derive_pair(
        &self,
        liquidity_provider: &Pubkey,
        first_mint: &Pubkey,
        second_mint: &Pubkey,
    ) -> (Pubkey, u8) {
        pda::derive_pair(
            liquidity_provider,
            first_mint,
            second_mint,
            &self.program_address,
        )
    }

    /// Derive the LP vault ATA, defaulting to the original SPL Token program.
    /// Unlike the free Rust helper, this follows the npm client's mint-first order.
    pub fn derive_vault(
        &self,
        mint: &Pubkey,
        liquidity_provider: &Pubkey,
        token_program: Option<&Pubkey>,
    ) -> (Pubkey, u8) {
        pda::derive_vault(
            liquidity_provider,
            mint,
            token_program.unwrap_or(&SPL_TOKEN_PROGRAM_ADDRESS),
            &self.program_address,
        )
    }

    pub fn derive_vault_authority(&self, liquidity_provider: &Pubkey) -> (Pubkey, u8) {
        pda::derive_vault_authority(liquidity_provider, &self.program_address)
    }

    pub fn derive_program_authority(&self) -> (Pubkey, u8) {
        pda::derive_program_authority(&self.program_address)
    }

    pub fn derive_fee_vault(
        &self,
        fee_mint: &Pubkey,
        token_program: Option<&Pubkey>,
    ) -> (Pubkey, u8) {
        pda::derive_fee_vault(
            fee_mint,
            token_program.unwrap_or(&SPL_TOKEN_PROGRAM_ADDRESS),
            &self.program_address,
        )
    }

    pub fn derive_lp_stable_config(
        &self,
        stable_mint: &Pubkey,
        liquidity_provider: &Pubkey,
    ) -> (Pubkey, u8) {
        pda::derive_lp_stable_config(stable_mint, liquidity_provider, &self.program_address)
    }

    pub fn derive_user_vault_info(&self, mint: &Pubkey, user: &Pubkey) -> (Pubkey, u8) {
        pda::derive_user_vault_info(mint, user, &self.program_address)
    }

    pub async fn get_quote(&self, params: &SwapParams) -> Result<SwapQuote> {
        quote::get_quote(self.rpc.as_ref(), params, &self.program_address).await
    }

    pub async fn get_quote_via_simulation(&self, params: &SwapParams) -> Result<SimulationQuote> {
        quote::get_quote_via_simulation(self.rpc.as_ref(), params, &self.program_address).await
    }

    pub async fn build_swap_instruction(
        &self,
        params: &SwapParams,
    ) -> Result<BuildSwapInstructionResult> {
        swap::build_swap_instruction(self.rpc.as_ref(), params, &self.program_address).await
    }

    pub async fn build_swap_transaction(
        &self,
        params: &BuildSwapTransactionParams,
    ) -> Result<BuildSwapTransactionResult> {
        swap::build_swap_transaction(self.rpc.as_ref(), params, &self.program_address).await
    }

    pub async fn build_update_pair_instruction(
        &self,
        params: &UpdatePairParams,
    ) -> Result<BuildUpdatePairInstructionResult> {
        lp::build_update_pair_instruction(self.rpc.as_ref(), params, &self.program_address).await
    }

    pub async fn build_update_pair_transaction(
        &self,
        params: &BuildUpdatePairTransactionParams,
    ) -> Result<BuildUpdatePairTransactionResult> {
        lp::build_update_pair_transaction(self.rpc.as_ref(), params, &self.program_address).await
    }

    pub async fn build_init_pair_instruction(
        &self,
        params: &InitPairParams,
    ) -> Result<BuildInitPairInstructionResult> {
        lp::build_init_pair_instruction(self.rpc.as_ref(), params, &self.program_address).await
    }

    pub async fn build_init_pair_transaction(
        &self,
        params: &BuildInitPairTransactionParams,
    ) -> Result<BuildInitPairTransactionResult> {
        lp::build_init_pair_transaction(self.rpc.as_ref(), params, &self.program_address).await
    }

    pub async fn build_add_liquidity_instruction(
        &self,
        params: &LpLiquidityParams,
    ) -> Result<BuildAddLiquidityInstructionResult> {
        lp::build_add_liquidity_instruction(self.rpc.as_ref(), params, &self.program_address).await
    }

    pub async fn build_add_liquidity_transaction(
        &self,
        params: &BuildAddLiquidityTransactionParams,
    ) -> Result<BuildAddLiquidityTransactionResult> {
        lp::build_add_liquidity_transaction(self.rpc.as_ref(), params, &self.program_address).await
    }

    pub async fn build_remove_liquidity_instruction(
        &self,
        params: &LpLiquidityParams,
    ) -> Result<BuildRemoveLiquidityInstructionResult> {
        lp::build_remove_liquidity_instruction(self.rpc.as_ref(), params, &self.program_address)
            .await
    }

    pub async fn build_remove_liquidity_transaction(
        &self,
        params: &BuildRemoveLiquidityTransactionParams,
    ) -> Result<BuildRemoveLiquidityTransactionResult> {
        lp::build_remove_liquidity_transaction(self.rpc.as_ref(), params, &self.program_address)
            .await
    }

    pub async fn build_close_pair_instruction(
        &self,
        params: &ClosePairParams,
    ) -> Result<BuildClosePairInstructionResult> {
        lp::build_close_pair_instruction(self.rpc.as_ref(), params, &self.program_address).await
    }

    pub async fn build_close_pair_transaction(
        &self,
        params: &BuildClosePairTransactionParams,
    ) -> Result<BuildClosePairTransactionResult> {
        lp::build_close_pair_transaction(self.rpc.as_ref(), params, &self.program_address).await
    }

    /// Decode events emitted by this swap program, excluding nested CPIs.
    /// Data-only logs without runtime records are assumed to be already scoped.
    pub fn parse_swap_events_from_logs(&self, logs: &[String]) -> Vec<SwapExecutedEvent> {
        events::parse_swap_events_from_logs(logs, &self.program_address)
    }

    pub async fn parse_swap_events_from_transaction(
        &self,
        signature: &str,
    ) -> Result<Vec<SwapExecutedEvent>> {
        events::parse_swap_events_from_transaction(
            self.rpc.as_ref(),
            signature,
            &self.program_address,
        )
        .await
    }

    /// Parse JSON-RPC/Anchor errors, preserving the emitting program namespace.
    /// Unrelated runtime errors cannot fall back to a colliding swap error code.
    pub fn parse_swap_error(
        &self,
        error: &serde_json::Value,
    ) -> Option<ParsedSimulationProgramError> {
        errors::parse_simulation_program_error(
            error,
            &self.program_address,
            Some(&self.treasury_program_address),
        )
        .or_else(|| {
            errors::parse_swap_error(error, Some(&self.program_address))
                .map(ParsedSimulationProgramError::Swap)
        })
    }

    pub fn to_human_readable(amount: u128, decimals: u8) -> String {
        format::to_human_readable(amount, decimals)
    }

    pub fn to_native_amount(human: &str, decimals: u8) -> Result<u128> {
        format::to_native_amount(human, decimals)
    }
}