Skip to main content

multiliquid_svm_sdk/
client.rs

1//! Cluster-aware convenience API over the native, read-only SDK modules.
2//!
3//! PDA and formatting helpers are synchronous. RPC operations are asynchronous,
4//! use the supplied transport's commitment, and are cancelled by dropping their
5//! futures. Builders return unsigned instructions or transactions; they never
6//! sign, submit, or require a wallet.
7
8#[cfg(feature = "http")]
9use crate::types::{CapitalProvider, CapitalProviderFetchOptions, PairRegistryFetchOptions};
10use crate::{
11    accounts,
12    constants::{
13        PROGRAM_ADDRESS_DEVNET, PROGRAM_ADDRESS_MAINNET, SPL_TOKEN_PROGRAM_ADDRESS,
14        TREASURY_PROGRAM_ADDRESS_DEVNET, TREASURY_PROGRAM_ADDRESS_MAINNET,
15    },
16    error::Result,
17    errors::{self, ParsedSimulationProgramError},
18    events, format, lp, pda, quote, registry, swap,
19    types::{
20        AssetConfigAccount, BuildAddLiquidityInstructionResult, BuildAddLiquidityTransactionParams,
21        BuildAddLiquidityTransactionResult, BuildClosePairInstructionResult,
22        BuildClosePairTransactionParams, BuildClosePairTransactionResult,
23        BuildFundLpFeeVaultInstructionResult, BuildFundLpFeeVaultTransactionParams,
24        BuildFundLpFeeVaultTransactionResult, BuildInitPairInstructionResult,
25        BuildInitPairTransactionParams, BuildInitPairTransactionResult,
26        BuildRemoveLiquidityInstructionResult, BuildRemoveLiquidityTransactionParams,
27        BuildRemoveLiquidityTransactionResult, BuildSwapInstructionResult,
28        BuildSwapTransactionParams, BuildSwapTransactionResult, BuildUpdatePairInstructionResult,
29        BuildUpdatePairTransactionParams, BuildUpdatePairTransactionResult, ClosePairParams,
30        Cluster, FundLpFeeVaultParams, GlobalConfigAccount, InitPairParams, LpLiquidityParams,
31        LpStableConfigAccount, MultiliquidRpc, PairAccount, PairFilters, PairRegistryEntry,
32        PairRegistryErrorHandler, PauseStatus, SimulationQuote, SwapExecutedEvent, SwapParams,
33        SwapQuote, SwapState, UpdatePairParams,
34    },
35    Pubkey,
36};
37
38/// Optional client defaults plus a required caller-selected RPC transport.
39///
40/// Construct with [`Self::new`], then override individual fields. The default
41/// cluster is devnet. A custom swap program does not change the cluster's
42/// registry or treasury program; treasury CPI accounts are resolved from native
43/// account state by the builders.
44#[derive(Clone)]
45pub struct MultiliquidClientConfig {
46    pub rpc: MultiliquidRpc,
47    pub program_address: Option<Pubkey>,
48    pub cluster: Option<Cluster>,
49    pub registry_api_url: Option<String>,
50    pub registry_fetch_timeout_ms: Option<u64>,
51    pub on_registry_error: Option<PairRegistryErrorHandler>,
52}
53
54impl MultiliquidClientConfig {
55    pub fn new(rpc: MultiliquidRpc) -> Self {
56        Self {
57            rpc,
58            program_address: None,
59            cluster: None,
60            registry_api_url: None,
61            registry_fetch_timeout_ms: None,
62            on_registry_error: None,
63        }
64    }
65}
66
67/// Native counterpart of the npm `MultiliquidClient`.
68///
69/// All account codecs and builders target the bundled audited production ABI.
70/// Liquidity and treasury bounds are caller-supplied, with no automatic slippage
71/// limits. Cloning the client shares its RPC and callbacks.
72///
73/// ```no_run
74/// # #[cfg(feature = "http")]
75/// # {
76/// use std::sync::Arc;
77/// use multiliquid_svm_sdk::{
78///     Cluster, CommitmentConfig, HttpRpcClient, MultiliquidClient,
79///     MultiliquidClientConfig,
80/// };
81///
82/// let rpc = Arc::new(HttpRpcClient::new(
83///     "https://api.mainnet-beta.solana.com",
84///     CommitmentConfig::confirmed(),
85/// ));
86/// let mut config = MultiliquidClientConfig::new(rpc);
87/// config.cluster = Some(Cluster::MainnetBeta);
88/// let client = MultiliquidClient::new(config);
89/// let (global_config, bump) = client.derive_global_config();
90/// # }
91/// ```
92///
93/// With `default-features = false`, supply `Arc::new(your_rpc)` implementing
94/// [`crate::Rpc`]. All methods except HTTP registry `get_pairs` remain
95/// available, including RPC discovery and the bundled offline registry.
96#[derive(Clone)]
97pub struct MultiliquidClient {
98    pub rpc: MultiliquidRpc,
99    pub program_address: Pubkey,
100    pub treasury_program_address: Pubkey,
101    pub cluster: Cluster,
102    pub registry_api_url: String,
103    pub registry_fetch_timeout_ms: Option<u64>,
104    pub on_registry_error: Option<PairRegistryErrorHandler>,
105}
106
107impl MultiliquidClient {
108    pub fn new(config: MultiliquidClientConfig) -> Self {
109        let cluster = config.cluster.unwrap_or(Cluster::Devnet);
110        let (program_address, treasury_program_address) = match cluster {
111            Cluster::Devnet => (PROGRAM_ADDRESS_DEVNET, TREASURY_PROGRAM_ADDRESS_DEVNET),
112            Cluster::MainnetBeta => (PROGRAM_ADDRESS_MAINNET, TREASURY_PROGRAM_ADDRESS_MAINNET),
113        };
114        Self {
115            rpc: config.rpc,
116            program_address: config.program_address.unwrap_or(program_address),
117            treasury_program_address,
118            cluster,
119            registry_api_url: config
120                .registry_api_url
121                .unwrap_or_else(|| registry::DEFAULT_REGISTRY_API_URL.to_owned()),
122            registry_fetch_timeout_ms: config.registry_fetch_timeout_ms,
123            on_registry_error: config.on_registry_error,
124        }
125    }
126
127    /// Fetch the API registry, falling back to filtered bundled entries on failure.
128    ///
129    /// Each `Some` per-call option overrides the corresponding client setting;
130    /// `None` inherits it. In particular, `Some(0)` disables the HTTP timeout.
131    /// An overridden RPC brings its own commitment policy. The custom swap
132    /// program does not change the cluster-based registry; use
133    /// [`Self::discover_pairs`] to discover that program's accounts instead.
134    #[cfg(feature = "http")]
135    pub async fn get_pairs(
136        &self,
137        filters: Option<&PairFilters>,
138        options: Option<&PairRegistryFetchOptions>,
139    ) -> Result<Vec<PairRegistryEntry>> {
140        let options = PairRegistryFetchOptions {
141            registry_api_url: Some(
142                options
143                    .and_then(|options| options.registry_api_url.as_ref())
144                    .unwrap_or(&self.registry_api_url)
145                    .clone(),
146            ),
147            rpc: Some(
148                options
149                    .and_then(|options| options.rpc.as_ref())
150                    .unwrap_or(&self.rpc)
151                    .clone(),
152            ),
153            timeout_ms: options
154                .and_then(|options| options.timeout_ms)
155                .or(self.registry_fetch_timeout_ms),
156            on_error: options
157                .and_then(|options| options.on_error.as_ref())
158                .or(self.on_registry_error.as_ref())
159                .cloned(),
160        };
161        registry::get_pairs(self.cluster, filters, &options).await
162    }
163
164    /// Fetch capital providers from the API for this client's cluster, with no bundled fallback.
165    ///
166    /// Each `Some` per-call option overrides the client's registry URL or timeout; `None` inherits it.
167    ///
168    /// ```no_run
169    /// # async fn example(client: &multiliquid_svm_sdk::MultiliquidClient) -> multiliquid_svm_sdk::Result<()> {
170    /// for provider in client.get_capital_providers(None).await? {
171    ///     println!("{} {} pairs={}", provider.name, provider.liquidity_provider, provider.pairs.len());
172    /// }
173    /// # Ok(())
174    /// # }
175    /// ```
176    #[cfg(feature = "http")]
177    pub async fn get_capital_providers(
178        &self,
179        options: Option<&CapitalProviderFetchOptions>,
180    ) -> Result<Vec<CapitalProvider>> {
181        let options = CapitalProviderFetchOptions {
182            registry_api_url: Some(
183                options
184                    .and_then(|options| options.registry_api_url.as_ref())
185                    .unwrap_or(&self.registry_api_url)
186                    .clone(),
187            ),
188            timeout_ms: options
189                .and_then(|options| options.timeout_ms)
190                .or(self.registry_fetch_timeout_ms),
191        };
192        registry::get_capital_providers(self.cluster, &options).await
193    }
194
195    /// List pairs from the bundled registry for this client's cluster, without network access.
196    pub fn get_offline_pairs(&self, filters: Option<&PairFilters>) -> Vec<PairRegistryEntry> {
197        registry::get_offline_pairs(self.cluster, filters)
198    }
199
200    /// Discover pairs by scanning this client's swap program over RPC.
201    pub async fn discover_pairs(
202        &self,
203        filters: Option<&PairFilters>,
204    ) -> Result<Vec<PairRegistryEntry>> {
205        registry::discover_pairs(self.rpc.as_ref(), &self.program_address, filters).await
206    }
207
208    pub async fn fetch_global_config(&self) -> Result<GlobalConfigAccount> {
209        accounts::fetch_global_config(self.rpc.as_ref(), &self.program_address, None).await
210    }
211
212    pub async fn fetch_pair(&self, account_address: &Pubkey) -> Result<PairAccount> {
213        accounts::fetch_pair(self.rpc.as_ref(), account_address).await
214    }
215
216    pub async fn fetch_asset_config(&self, account_address: &Pubkey) -> Result<AssetConfigAccount> {
217        accounts::fetch_asset_config(self.rpc.as_ref(), account_address).await
218    }
219
220    pub async fn fetch_lp_stable_config(
221        &self,
222        account_address: &Pubkey,
223    ) -> Result<LpStableConfigAccount> {
224        accounts::fetch_lp_stable_config(self.rpc.as_ref(), account_address).await
225    }
226
227    pub async fn fetch_swap_state(
228        &self,
229        input_mint: &Pubkey,
230        output_mint: &Pubkey,
231        liquidity_provider: &Pubkey,
232        pair_address: Option<&Pubkey>,
233    ) -> Result<SwapState> {
234        accounts::fetch_swap_state(
235            self.rpc.as_ref(),
236            input_mint,
237            output_mint,
238            liquidity_provider,
239            &self.program_address,
240            pair_address,
241        )
242        .await
243    }
244
245    pub async fn check_pause_status(
246        &self,
247        input_mint: &Pubkey,
248        output_mint: &Pubkey,
249        liquidity_provider: &Pubkey,
250        pair_address: Option<&Pubkey>,
251    ) -> Result<PauseStatus> {
252        accounts::check_pause_status(
253            self.rpc.as_ref(),
254            input_mint,
255            output_mint,
256            liquidity_provider,
257            &self.program_address,
258            pair_address,
259        )
260        .await
261    }
262
263    pub fn derive_global_config(&self) -> (Pubkey, u8) {
264        pda::derive_global_config(&self.program_address)
265    }
266
267    pub fn derive_asset_config(&self, mint: &Pubkey) -> (Pubkey, u8) {
268        pda::derive_asset_config(mint, &self.program_address)
269    }
270
271    /// Preserve the supplied on-chain mint order; this does not sort the pair.
272    pub fn derive_pair(
273        &self,
274        liquidity_provider: &Pubkey,
275        first_mint: &Pubkey,
276        second_mint: &Pubkey,
277    ) -> (Pubkey, u8) {
278        pda::derive_pair(
279            liquidity_provider,
280            first_mint,
281            second_mint,
282            &self.program_address,
283        )
284    }
285
286    /// Derive the LP vault ATA, defaulting to the original SPL Token program.
287    /// Unlike the free Rust helper, this follows the npm client's mint-first order.
288    pub fn derive_vault(
289        &self,
290        mint: &Pubkey,
291        liquidity_provider: &Pubkey,
292        token_program: Option<&Pubkey>,
293    ) -> (Pubkey, u8) {
294        pda::derive_vault(
295            liquidity_provider,
296            mint,
297            token_program.unwrap_or(&SPL_TOKEN_PROGRAM_ADDRESS),
298            &self.program_address,
299        )
300    }
301
302    pub fn derive_vault_authority(&self, liquidity_provider: &Pubkey) -> (Pubkey, u8) {
303        pda::derive_vault_authority(liquidity_provider, &self.program_address)
304    }
305
306    pub fn derive_program_authority(&self) -> (Pubkey, u8) {
307        pda::derive_program_authority(&self.program_address)
308    }
309
310    pub fn derive_fee_vault(
311        &self,
312        fee_mint: &Pubkey,
313        token_program: Option<&Pubkey>,
314    ) -> (Pubkey, u8) {
315        pda::derive_fee_vault(
316            fee_mint,
317            token_program.unwrap_or(&SPL_TOKEN_PROGRAM_ADDRESS),
318            &self.program_address,
319        )
320    }
321
322    pub fn derive_lp_stable_config(
323        &self,
324        stable_mint: &Pubkey,
325        liquidity_provider: &Pubkey,
326    ) -> (Pubkey, u8) {
327        pda::derive_lp_stable_config(stable_mint, liquidity_provider, &self.program_address)
328    }
329
330    pub fn derive_user_vault_info(&self, mint: &Pubkey, user: &Pubkey) -> (Pubkey, u8) {
331        pda::derive_user_vault_info(mint, user, &self.program_address)
332    }
333
334    /// Calculate a local quote from current account and oracle state. See [`SwapParams`] for the fields it reads.
335    pub async fn get_quote(&self, params: &SwapParams) -> Result<SwapQuote> {
336        quote::get_quote(self.rpc.as_ref(), params, &self.program_address).await
337    }
338
339    /// Quote by simulating the swap instruction, without slippage bounds or token account creation.
340    pub async fn get_quote_via_simulation(&self, params: &SwapParams) -> Result<SimulationQuote> {
341        quote::get_quote_via_simulation(self.rpc.as_ref(), params, &self.program_address).await
342    }
343
344    /// Build a swap instruction and any token account setup instructions from [`SwapParams`].
345    pub async fn build_swap_instruction(
346        &self,
347        params: &SwapParams,
348    ) -> Result<BuildSwapInstructionResult> {
349        swap::build_swap_instruction(self.rpc.as_ref(), params, &self.program_address).await
350    }
351
352    /// Build an unsigned v0 swap transaction with `params.user` as fee payer.
353    pub async fn build_swap_transaction(
354        &self,
355        params: &BuildSwapTransactionParams,
356    ) -> Result<BuildSwapTransactionResult> {
357        swap::build_swap_transaction(self.rpc.as_ref(), params, &self.program_address).await
358    }
359
360    pub async fn build_update_pair_instruction(
361        &self,
362        params: &UpdatePairParams,
363    ) -> Result<BuildUpdatePairInstructionResult> {
364        lp::build_update_pair_instruction(self.rpc.as_ref(), params, &self.program_address).await
365    }
366
367    pub async fn build_update_pair_transaction(
368        &self,
369        params: &BuildUpdatePairTransactionParams,
370    ) -> Result<BuildUpdatePairTransactionResult> {
371        lp::build_update_pair_transaction(self.rpc.as_ref(), params, &self.program_address).await
372    }
373
374    pub async fn build_init_pair_instruction(
375        &self,
376        params: &InitPairParams,
377    ) -> Result<BuildInitPairInstructionResult> {
378        lp::build_init_pair_instruction(self.rpc.as_ref(), params, &self.program_address).await
379    }
380
381    pub async fn build_init_pair_transaction(
382        &self,
383        params: &BuildInitPairTransactionParams,
384    ) -> Result<BuildInitPairTransactionResult> {
385        lp::build_init_pair_transaction(self.rpc.as_ref(), params, &self.program_address).await
386    }
387
388    /// Build an add-liquidity instruction and token account setup from [`LpLiquidityParams`].
389    pub async fn build_add_liquidity_instruction(
390        &self,
391        params: &LpLiquidityParams,
392    ) -> Result<BuildAddLiquidityInstructionResult> {
393        lp::build_add_liquidity_instruction(self.rpc.as_ref(), params, &self.program_address).await
394    }
395
396    /// Build an unsigned v0 add-liquidity transaction with the liquidity provider as fee payer.
397    pub async fn build_add_liquidity_transaction(
398        &self,
399        params: &BuildAddLiquidityTransactionParams,
400    ) -> Result<BuildAddLiquidityTransactionResult> {
401        lp::build_add_liquidity_transaction(self.rpc.as_ref(), params, &self.program_address).await
402    }
403
404    /// Build a remove-liquidity instruction and recipient token account setup from [`LpLiquidityParams`].
405    pub async fn build_remove_liquidity_instruction(
406        &self,
407        params: &LpLiquidityParams,
408    ) -> Result<BuildRemoveLiquidityInstructionResult> {
409        lp::build_remove_liquidity_instruction(self.rpc.as_ref(), params, &self.program_address)
410            .await
411    }
412
413    /// Build an unsigned v0 remove-liquidity transaction with the liquidity provider as fee payer.
414    pub async fn build_remove_liquidity_transaction(
415        &self,
416        params: &BuildRemoveLiquidityTransactionParams,
417    ) -> Result<BuildRemoveLiquidityTransactionResult> {
418        lp::build_remove_liquidity_transaction(self.rpc.as_ref(), params, &self.program_address)
419            .await
420    }
421
422    pub async fn build_close_pair_instruction(
423        &self,
424        params: &ClosePairParams,
425    ) -> Result<BuildClosePairInstructionResult> {
426        lp::build_close_pair_instruction(self.rpc.as_ref(), params, &self.program_address).await
427    }
428
429    pub async fn build_close_pair_transaction(
430        &self,
431        params: &BuildClosePairTransactionParams,
432    ) -> Result<BuildClosePairTransactionResult> {
433        lp::build_close_pair_transaction(self.rpc.as_ref(), params, &self.program_address).await
434    }
435
436    pub async fn build_fund_lp_fee_vault_instruction(
437        &self,
438        params: &FundLpFeeVaultParams,
439    ) -> Result<BuildFundLpFeeVaultInstructionResult> {
440        lp::build_fund_lp_fee_vault_instruction(self.rpc.as_ref(), params, &self.program_address)
441            .await
442    }
443
444    pub async fn build_fund_lp_fee_vault_transaction(
445        &self,
446        params: &BuildFundLpFeeVaultTransactionParams,
447    ) -> Result<BuildFundLpFeeVaultTransactionResult> {
448        lp::build_fund_lp_fee_vault_transaction(self.rpc.as_ref(), params, &self.program_address)
449            .await
450    }
451
452    /// Decode events emitted by this swap program, excluding nested CPIs.
453    /// Data-only logs without runtime records are assumed to be already scoped.
454    pub fn parse_swap_events_from_logs(&self, logs: &[String]) -> Vec<SwapExecutedEvent> {
455        events::parse_swap_events_from_logs(logs, &self.program_address)
456    }
457
458    pub async fn parse_swap_events_from_transaction(
459        &self,
460        signature: &str,
461    ) -> Result<Vec<SwapExecutedEvent>> {
462        events::parse_swap_events_from_transaction(
463            self.rpc.as_ref(),
464            signature,
465            &self.program_address,
466        )
467        .await
468    }
469
470    /// Parse JSON-RPC/Anchor errors, preserving the emitting program namespace.
471    /// Unrelated runtime errors cannot fall back to a colliding swap error code.
472    pub fn parse_swap_error(
473        &self,
474        error: &serde_json::Value,
475    ) -> Option<ParsedSimulationProgramError> {
476        errors::parse_simulation_program_error(
477            error,
478            &self.program_address,
479            Some(&self.treasury_program_address),
480        )
481        .or_else(|| {
482            errors::parse_swap_error(error, Some(&self.program_address))
483                .map(ParsedSimulationProgramError::Swap)
484        })
485    }
486
487    pub fn to_human_readable(amount: u128, decimals: u8) -> String {
488        format::to_human_readable(amount, decimals)
489    }
490
491    pub fn to_native_amount(human: &str, decimals: u8) -> Result<u128> {
492        format::to_native_amount(human, decimals)
493    }
494}