Skip to main content

orca_sdk/
pool.rs

1use solana_account_decoder::UiAccountEncoding;
2use solana_client::rpc_config::{RpcAccountInfoConfig, RpcProgramAccountsConfig};
3use solana_client::rpc_filter::RpcFilterType;
4use solana_commitment_config::CommitmentConfig;
5
6use super::*;
7use crate::global::*;
8use crate::types::OrcaResult;
9
10#[derive(Debug, Clone)]
11pub struct PoolInfo {
12    pub address: String,
13    pub token_mint_a: String,
14    pub token_mint_b: String,
15    pub token_vault_a: String,
16    pub token_vault_b: String,
17    pub lp_token_mint: String,
18    pub fee_account: String,
19    pub trade_fee_numerator: u64,
20    pub trade_fee_denominator: u64,
21    pub tick_spacing: u16,
22    pub liquidity: u128,
23    pub sqrt_price: u128,
24    pub fee_growth_global_a: u128,
25    pub fee_growth_global_b: u128,
26}
27
28#[derive(Debug, Clone)]
29pub struct QuoteResult {
30    pub input_amount: u64,
31    pub output_amount: u64,
32    pub min_output_amount: u64,
33    pub price_impact: f64,
34    pub fee_amount: u64,
35}
36
37impl OrcaClient {
38    /// Fetches pool state from on-chain data
39    ///
40    /// # Example
41    /// ```
42    /// let pool_info = client.get_pool_state_onchain("address").await?;
43    /// println!("Pool liquidity: {}", pool_info.liquidity);
44    /// ```
45    pub async fn get_pool_state_onchain(&self, pool_address: &str) -> OrcaResult<PoolInfo> {
46        let client = self
47            .solana
48            .client
49            .as_ref()
50            .ok_or(OrcaError::Error("RPC client not available".to_string()))?;
51        let pool_pubkey = Pubkey::from_str(pool_address)
52            .map_err(|e| OrcaError::Error(format!("Invalid pool address: {}", e)))?;
53        let account_data = client
54            .get_account_data(&pool_pubkey)
55            .await
56            .map_err(|e| OrcaError::Error(format!("Failed to get account data: {}", e)))?;
57        self.parse_whirlpool_account_data(&account_data, pool_address)
58    }
59
60    /// Parses Whirlpool account data into PoolInfo struct
61    fn parse_whirlpool_account_data(
62        &self,
63        data: &[u8],
64        pool_address: &str,
65    ) -> OrcaResult<PoolInfo> {
66        if data.len() < 300 {
67            return Err(OrcaError::Error(
68                "Invalid whirlpool account data length".to_string(),
69            ));
70        }
71        let token_mint_a = Pubkey::new_from_array(
72            data[WHIRLPOOL_TOKEN_MINT_A_OFFSET..WHIRLPOOL_TOKEN_MINT_A_OFFSET + 32]
73                .try_into()
74                .map_err(|_| OrcaError::Error("Failed to parse token mint A".to_string()))?,
75        )
76        .to_string();
77        let token_mint_b = Pubkey::new_from_array(
78            data[WHIRLPOOL_TOKEN_MINT_B_OFFSET..WHIRLPOOL_TOKEN_MINT_B_OFFSET + 32]
79                .try_into()
80                .map_err(|_| OrcaError::Error("Failed to parse token mint B".to_string()))?,
81        )
82        .to_string();
83        let tick_spacing = u16::from_le_bytes(
84            data[WHIRLPOOL_TICK_SPACING_OFFSET..WHIRLPOOL_TICK_SPACING_OFFSET + 2]
85                .try_into()
86                .map_err(|_| OrcaError::Error("Failed to parse tick spacing".to_string()))?,
87        );
88        let fee_rate = u16::from_le_bytes(
89            data[WHIRLPOOL_FEE_RATE_OFFSET..WHIRLPOOL_FEE_RATE_OFFSET + 2]
90                .try_into()
91                .map_err(|_| OrcaError::Error("Failed to parse fee rate".to_string()))?,
92        );
93        let liquidity = u128::from_le_bytes(
94            data[WHIRLPOOL_LIQUIDITY_OFFSET..WHIRLPOOL_LIQUIDITY_OFFSET + 16]
95                .try_into()
96                .map_err(|_| OrcaError::Error("Failed to parse liquidity".to_string()))?,
97        );
98        let sqrt_price = u128::from_le_bytes(
99            data[WHIRLPOOL_SQRT_PRICE_OFFSET..WHIRLPOOL_SQRT_PRICE_OFFSET + 16]
100                .try_into()
101                .map_err(|_| OrcaError::Error("Failed to parse sqrt price".to_string()))?,
102        );
103        let token_vault_a = self.derive_token_vault_address(&token_mint_a, pool_address)?;
104        let token_vault_b = self.derive_token_vault_address(&token_mint_b, pool_address)?;
105        let lp_token_mint = self.derive_lp_token_mint(pool_address)?;
106        let fee_account = self.derive_fee_account(pool_address)?;
107        let fee_growth_global_a = if data.len() >= 248 {
108            u128::from_le_bytes(data[232..248].try_into().unwrap_or([0; 16]))
109        } else {
110            0
111        };
112        let fee_growth_global_b = if data.len() >= 264 {
113            u128::from_le_bytes(data[248..264].try_into().unwrap_or([0; 16]))
114        } else {
115            0
116        };
117        Ok(PoolInfo {
118            address: pool_address.to_string(),
119            token_mint_a,
120            token_mint_b,
121            token_vault_a,
122            token_vault_b,
123            lp_token_mint,
124            fee_account,
125            trade_fee_numerator: fee_rate as u64,
126            trade_fee_denominator: 1_000_000,
127            tick_spacing,
128            liquidity,
129            sqrt_price,
130            fee_growth_global_a,
131            fee_growth_global_b,
132        })
133    }
134
135    /// Derives token vault address using PDA
136    fn derive_token_vault_address(
137        &self,
138        token_mint: &str,
139        pool_address: &str,
140    ) -> OrcaResult<String> {
141        let token_mint_pubkey = Pubkey::from_str(token_mint)
142            .map_err(|e| OrcaError::Error(format!("Invalid token mint: {}", e)))?;
143        let pool_pubkey = Pubkey::from_str(pool_address)
144            .map_err(|e| OrcaError::Error(format!("Invalid pool address: {}", e)))?;
145        let (vault_address, _) = Pubkey::find_program_address(
146            &[
147                b"token_vault",
148                pool_pubkey.as_ref(),
149                token_mint_pubkey.as_ref(),
150            ],
151            &self.whirlpool_program_id,
152        );
153        Ok(vault_address.to_string())
154    }
155
156    /// Derives LP token mint address using PDA
157    fn derive_lp_token_mint(&self, pool_address: &str) -> OrcaResult<String> {
158        let pool_pubkey = Pubkey::from_str(pool_address)
159            .map_err(|e| OrcaError::Error(format!("Invalid pool address: {}", e)))?;
160        let (lp_mint, _) = Pubkey::find_program_address(
161            &[b"lp_mint", pool_pubkey.as_ref()],
162            &self.whirlpool_program_id,
163        );
164        Ok(lp_mint.to_string())
165    }
166
167    /// Derives fee account address using PDA
168    fn derive_fee_account(&self, pool_address: &str) -> OrcaResult<String> {
169        let pool_pubkey = Pubkey::from_str(pool_address)
170            .map_err(|e| OrcaError::Error(format!("Invalid pool address: {}", e)))?;
171        let (fee_account, _) = Pubkey::find_program_address(
172            &[b"fee_account", pool_pubkey.as_ref()],
173            &self.whirlpool_program_id,
174        );
175        Ok(fee_account.to_string())
176    }
177
178    /// Optimized method to find pools containing a specific token
179    ///
180    /// # Example
181    /// ```
182    /// let pools = client.find_pools_by_token_onchain_optimized("So11111111111111111111111111111111111111112").await?;
183    /// println!("Found {} pools", pools.len());
184    /// ```
185    pub async fn find_pools_by_token_onchain_optimized(
186        &self,
187        token_mint: &str,
188    ) -> OrcaResult<Vec<String>> {
189        if let Some(cached_pools) = self.get_cached_pools_for_token(token_mint).await? {
190            return Ok(cached_pools);
191        }
192        let client = self
193            .solana
194            .client
195            .as_ref()
196            .ok_or(OrcaError::Error("RPC client not available".to_string()))?;
197        let token_pubkey = Pubkey::from_str(token_mint)
198            .map_err(|e| OrcaError::Error(format!("Invalid token mint: {}", e)))?;
199        let filters = vec![RpcFilterType::DataSize(300)];
200        let accounts = client
201            .get_program_accounts_with_config(
202                &self.whirlpool_program_id,
203                RpcProgramAccountsConfig {
204                    filters: Some(filters),
205                    account_config: RpcAccountInfoConfig {
206                        encoding: Some(UiAccountEncoding::Base64),
207                        data_slice: None,
208                        commitment: Some(CommitmentConfig::confirmed()),
209                        min_context_slot: None,
210                    },
211                    with_context: None,
212                    sort_results: None,
213                },
214            )
215            .await
216            .map_err(|e| OrcaError::Error(format!("Failed to get program accounts: {}", e)))?;
217        let mut pool_addresses = Vec::new();
218        for (pubkey, account) in accounts {
219            if account.data.len() < WHIRLPOOL_TOKEN_MINT_B_OFFSET + 32 {
220                continue;
221            }
222            let mint_a_bytes: [u8; 32] = account.data
223                [WHIRLPOOL_TOKEN_MINT_A_OFFSET..WHIRLPOOL_TOKEN_MINT_A_OFFSET + 32]
224                .try_into()
225                .map_err(|_| OrcaError::Error("Failed to convert mint A bytes".to_string()))?;
226            let mint_b_bytes: [u8; 32] = account.data
227                [WHIRLPOOL_TOKEN_MINT_B_OFFSET..WHIRLPOOL_TOKEN_MINT_B_OFFSET + 32]
228                .try_into()
229                .map_err(|_| OrcaError::Error("Failed to convert mint B bytes".to_string()))?;
230            let mint_a = Pubkey::new_from_array(mint_a_bytes);
231            let mint_b = Pubkey::new_from_array(mint_b_bytes);
232            if mint_a == token_pubkey || mint_b == token_pubkey {
233                pool_addresses.push(pubkey.to_string());
234            }
235        }
236        self.cache_pools_for_token(token_mint, &pool_addresses)
237            .await?;
238        Ok(pool_addresses)
239    }
240
241    /// Retrieves cached pools for a token
242    async fn get_cached_pools_for_token(
243        &self,
244        token_mint: &str,
245    ) -> OrcaResult<Option<Vec<String>>> {
246        todo!();
247        Ok(None)
248    }
249
250    async fn cache_pools_for_token(&self, token_mint: &str, pools: &[String]) -> OrcaResult<()> {
251        todo!();
252        Ok(())
253    }
254
255    pub async fn find_pools_by_token_onchain(&self, token_mint: &str) -> OrcaResult<Vec<String>> {
256        let client = self
257            .solana
258            .client
259            .as_ref()
260            .ok_or(OrcaError::Error("RPC client not available".to_string()))?;
261        let token_pubkey = Pubkey::from_str(token_mint)
262            .map_err(|e| OrcaError::Error(format!("Invalid token mint: {}", e)))?;
263        let filters = vec![
264            solana_client::rpc_filter::RpcFilterType::Memcmp(
265                solana_client::rpc_filter::Memcmp::new_base58_encoded(
266                    WHIRLPOOL_TOKEN_MINT_A_OFFSET,
267                    &token_pubkey.to_bytes(),
268                ),
269            ),
270            solana_client::rpc_filter::RpcFilterType::Memcmp(
271                solana_client::rpc_filter::Memcmp::new_base58_encoded(
272                    WHIRLPOOL_TOKEN_MINT_B_OFFSET,
273                    &token_pubkey.to_bytes(),
274                ),
275            ),
276        ];
277        let accounts = client
278            .get_program_accounts_with_config(
279                &self.whirlpool_program_id,
280                solana_client::rpc_config::RpcProgramAccountsConfig {
281                    filters: Some(filters),
282                    account_config: RpcAccountInfoConfig {
283                        encoding: Some(UiAccountEncoding::Base64),
284                        data_slice: None,
285                        commitment: Some(CommitmentConfig::confirmed()),
286                        min_context_slot: None,
287                    },
288                    with_context: None,
289                    sort_results: None,
290                },
291            )
292            .await
293            .map_err(|e| OrcaError::Error(format!("Failed to get program accounts: {}", e)))?;
294        let pool_addresses: Vec<String> = accounts
295            .iter()
296            .map(|(pubkey, _account)| pubkey.to_string())
297            .collect();
298        Ok(pool_addresses)
299    }
300
301    /// Gets a quote for swapping between two tokens
302    ///
303    /// # Example
304    /// ```
305    /// let quote = client.get_quote_from_pool(
306    ///     "So11111111111111111111111111111111111111112",
307    ///     "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
308    ///     1000000,
309    ///     0.5
310    /// ).await?;
311    /// println!("Output amount: {}", quote.output_amount);
312    /// ```
313    pub async fn get_quote_from_pool(
314        &self,
315        input_mint: &str,
316        output_mint: &str,
317        input_amount: u64,
318        slippage: f64,
319    ) -> OrcaResult<QuoteResult> {
320        let pools = self.find_pools_by_token_onchain(input_mint).await?;
321        for pool_address in pools {
322            if let Ok(pool_info) = self.get_pool_state_onchain(&pool_address).await {
323                if (pool_info.token_mint_a == input_mint && pool_info.token_mint_b == output_mint)
324                    || (pool_info.token_mint_a == output_mint
325                        && pool_info.token_mint_b == input_mint)
326                {
327                    return self
328                        .calculate_quote_from_pool_state(
329                            &pool_info,
330                            input_mint,
331                            output_mint,
332                            input_amount,
333                            slippage,
334                        )
335                        .await;
336                }
337            }
338        }
339        Err(OrcaError::Error("No pool found for token pair".to_string()))
340    }
341
342    async fn calculate_quote_from_pool_state(
343        &self,
344        pool: &PoolInfo,
345        input_mint: &str,
346        output_mint: &str,
347        input_amount: u64,
348        slippage: f64,
349    ) -> OrcaResult<QuoteResult> {
350        let is_input_a = input_mint == pool.token_mint_a;
351        let sqrt_price = pool.sqrt_price as f64;
352        let scale_factor = 2f64.powi(64);
353        let price = (sqrt_price * sqrt_price) / scale_factor;
354        let output_amount = if is_input_a {
355            (input_amount as f64 * price) as u64
356        } else {
357            (input_amount as f64 / price) as u64
358        };
359        let fee_amount = (input_amount as f64
360            * (pool.trade_fee_numerator as f64 / pool.trade_fee_denominator as f64))
361            as u64;
362        let min_output_amount = (output_amount as f64 * (1.0 - slippage / 100.0)) as u64;
363        let price_impact = self
364            .calculate_price_impact(pool, input_amount, is_input_a)
365            .await?;
366        Ok(QuoteResult {
367            input_amount,
368            output_amount,
369            min_output_amount,
370            price_impact,
371            fee_amount,
372        })
373    }
374
375    async fn calculate_price_impact(
376        &self,
377        pool: &PoolInfo,
378        input_amount: u64,
379        is_input_a: bool,
380    ) -> OrcaResult<f64> {
381        let liquidity = pool.liquidity as f64;
382        let impact = (input_amount as f64) / liquidity * 100.0;
383        Ok(impact.min(100.0))
384    }
385
386    pub async fn derive_price_from_pool_state(
387        &self,
388        pool: &PoolInfo,
389        base_mint: &str,
390    ) -> OrcaResult<f64> {
391        let sqrt_price = pool.sqrt_price as f64;
392        let scale_factor = 2f64.powi(64);
393        let price = (sqrt_price * sqrt_price) / scale_factor;
394        if base_mint == pool.token_mint_a {
395            Ok(price)
396        } else {
397            Ok(1.0 / price)
398        }
399    }
400
401    /// Gets all pools containing a specific token from on-chain data
402    pub async fn get_pools_by_token_onchain(&self, token_mint: &str) -> OrcaResult<Vec<String>> {
403        let client = self
404            .solana
405            .client
406            .as_ref()
407            .ok_or(OrcaError::Error("RPC client not available".to_string()))?;
408        let token_pubkey = Pubkey::from_str(token_mint)
409            .map_err(|e| OrcaError::Error(format!("Invalid token mint: {}", e)))?;
410        let accounts = client
411            .get_program_accounts(&self.whirlpool_program_id)
412            .await
413            .map_err(|e| OrcaError::Error(format!("Failed to get program accounts: {}", e)))?;
414        let mut pool_addresses = Vec::new();
415        for (pubkey, account) in accounts {
416            if account.data.len() < crate::global::WHIRLPOOL_TOKEN_MINT_B_OFFSET + 32 {
417                continue;
418            }
419            let mint_a_bytes: [u8; 32] = account.data[crate::global::WHIRLPOOL_TOKEN_MINT_A_OFFSET
420                ..crate::global::WHIRLPOOL_TOKEN_MINT_A_OFFSET + 32]
421                .try_into()
422                .map_err(|_| OrcaError::Error("Failed to convert mint A bytes".to_string()))?;
423            let mint_b_bytes: [u8; 32] = account.data[crate::global::WHIRLPOOL_TOKEN_MINT_B_OFFSET
424                ..crate::global::WHIRLPOOL_TOKEN_MINT_B_OFFSET + 32]
425                .try_into()
426                .map_err(|_| OrcaError::Error("Failed to convert mint B bytes".to_string()))?;
427            let mint_a = Pubkey::new_from_array(mint_a_bytes);
428            let mint_b = Pubkey::new_from_array(mint_b_bytes);
429            if mint_a == token_pubkey || mint_b == token_pubkey {
430                pool_addresses.push(pubkey.to_string());
431            }
432        }
433        Ok(pool_addresses)
434    }
435}