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