Skip to main content

orca_sdk/
liquidity.rs

1use super::*;
2use crate::{pool::PoolInfo, types::OrcaResult};
3use solana_program::example_mocks::solana_sdk::system_program;
4use solana_sdk::{
5    instruction::{AccountMeta, Instruction},
6    program_pack::Pack,
7    sysvar,
8};
9use std::str::FromStr;
10
11/// Represents a liquidity position in a concentrated liquidity pool
12#[derive(Debug, Clone)]
13pub struct LiquidityPosition {
14    pub pool_address: Pubkey,
15    pub token_a_amount: u64,
16    pub token_b_amount: u64,
17    pub lp_token_amount: u64,
18    pub lower_tick: i32,
19    pub upper_tick: i32,
20    pub position_mint: Pubkey,
21    pub position_token_account: Pubkey,
22}
23
24/// Configuration for adding liquidity with slippage protection
25#[derive(Debug, Clone)]
26pub struct AddLiquidityConfig {
27    pub slippage_tolerance: f64,
28    pub max_iterations: u8,
29}
30
31impl Default for AddLiquidityConfig {
32    fn default() -> Self {
33        Self {
34            slippage_tolerance: 0.5,
35            max_iterations: 3,
36        }
37    }
38}
39
40impl OrcaClient {
41    /// Adds liquidity to a concentrated liquidity pool within specified tick range
42    ///
43    /// # Params
44    /// keypair - Keypair for transaction signing
45    /// pool - Pool information
46    /// token_a_amount - Amount of token A to deposit
47    /// token_b_amount - Amount of token B to deposit  
48    /// lower_tick - Lower tick boundary for position
49    /// upper_tick - Upper tick boundary for position
50    /// config - Optional configuration for slippage and iterations
51    ///
52    /// # Example
53    /// ```rust
54    /// use orca_rs::client::OrcaClient;
55    /// use solana_sdk::signature::Keypair;
56    ///
57    /// let client = OrcaClient::new("https://api.mainnet-beta.solana.com");
58    /// let keypair = Keypair::new();
59    /// let pool_info = client.get_pool("whirlpool_address").await?;
60    ///
61    /// let signature = client.add_liquidity(
62    ///     &keypair,
63    ///     &pool_info,
64    ///     1000000, // 1 token A
65    ///     2000000, // 2 token B  
66    ///     -1000,   // lower tick
67    ///     1000,    // upper tick
68    ///     None,    // use default config
69    /// ).await?;
70    /// ```
71    pub async fn add_liquidity(
72        &self,
73        keypair: &Keypair,
74        pool: &PoolInfo,
75        token_a_amount: u64,
76        token_b_amount: u64,
77        lower_tick: i32,
78        upper_tick: i32,
79        config: Option<AddLiquidityConfig>,
80    ) -> OrcaResult<Signature> {
81        let token_a_mint = Pubkey::from_str(&pool.token_mint_a)
82            .map_err(|e| OrcaError::Error(format!("Invalid token mint A: {}", e)))?;
83        let token_b_mint = Pubkey::from_str(&pool.token_mint_b)
84            .map_err(|e| OrcaError::Error(format!("Invalid token mint B: {}", e)))?;
85        let token_a_account = self.ensure_token_account(keypair, &token_a_mint).await?;
86        let token_b_account = self.ensure_token_account(keypair, &token_b_mint).await?;
87        let pool_pubkey = Pubkey::from_str(&pool.address)
88            .map_err(|e| OrcaError::Error(format!("Invalid pool address: {}", e)))?;
89        let recent_blockhash = self
90            .solana
91            .client
92            .as_ref()
93            .ok_or(OrcaError::Error("RPC client not available".to_string()))?
94            .get_latest_blockhash()
95            .await
96            .map_err(|e| OrcaError::Error(format!("Failed to get blockhash: {}", e)))?;
97        let position_mint = Keypair::new();
98        let position_token_account =
99            self.get_associated_token_address(&keypair.pubkey(), &position_mint.pubkey());
100        let open_position_instruction = self.build_open_position_instruction(
101            &keypair.pubkey(),
102            &pool_pubkey,
103            &position_mint.pubkey(),
104            &position_token_account,
105            lower_tick,
106            upper_tick,
107        )?;
108        let increase_liquidity_instruction = self.build_increase_liquidity_instruction(
109            &keypair.pubkey(),
110            &pool_pubkey,
111            &position_token_account,
112            &token_a_account,
113            &token_b_account,
114            &token_a_mint,
115            &token_b_mint,
116            &position_mint.pubkey(),
117            token_a_amount,
118            token_b_amount,
119        )?;
120        let message = Message::new(
121            &[open_position_instruction, increase_liquidity_instruction],
122            Some(&keypair.pubkey()),
123        );
124        let transaction = Transaction::new(&[keypair, &position_mint], message, recent_blockhash);
125        self.solana
126            .client
127            .as_ref()
128            .ok_or(OrcaError::Error("RPC client not available".to_string()))?
129            .send_and_confirm_transaction(&transaction)
130            .await
131            .map_err(|e| OrcaError::Error(format!("Failed to add liquidity: {}", e)))
132    }
133
134    /// Removes liquidity from a position and closes it
135    ///
136    /// # Params
137    /// keypair - Keypair for transaction signing
138    /// position - Liquidity position to remove
139    ///
140    /// # Example
141    /// ```rust
142    /// use orca_rs::client::OrcaClient;
143    /// use solana_sdk::signature::Keypair;
144    ///
145    /// let client = OrcaClient::new("https://api.mainnet-beta.solana.com");
146    /// let keypair = Keypair::new();
147    /// let positions = client.get_liquidity_positions(&keypair.pubkey()).await?;
148    ///
149    /// if let Some(position) = positions.first() {
150    ///     let signature = client.remove_liquidity(&keypair, position).await?;
151    /// }
152    /// ```
153    pub async fn remove_liquidity(
154        &self,
155        keypair: &Keypair,
156        position: &LiquidityPosition,
157    ) -> OrcaResult<Signature> {
158        let recent_blockhash = self
159            .solana
160            .client
161            .as_ref()
162            .ok_or(OrcaError::Error("RPC client not available".to_string()))?
163            .get_latest_blockhash()
164            .await
165            .map_err(|e| OrcaError::Error(format!("Failed to get blockhash: {}", e)))?;
166        let decrease_liquidity_instruction = self.build_decrease_liquidity_instruction(
167            &keypair.pubkey(),
168            &position.pool_address,
169            &position.position_token_account,
170            &position.position_mint,
171            position.lp_token_amount,
172        )?;
173        let close_position_instruction = self.build_close_position_instruction(
174            &keypair.pubkey(),
175            &position.pool_address,
176            &position.position_token_account,
177            &position.position_mint,
178        )?;
179        let message = Message::new(
180            &[decrease_liquidity_instruction, close_position_instruction],
181            Some(&keypair.pubkey()),
182        );
183        let transaction = Transaction::new(&[keypair], message, recent_blockhash);
184        self.solana
185            .client
186            .as_ref()
187            .ok_or(OrcaError::Error("RPC client not available".to_string()))?
188            .send_and_confirm_transaction(&transaction)
189            .await
190            .map_err(|e| OrcaError::Error(format!("Failed to remove liquidity: {}", e)))
191    }
192
193    /// Retrieves all liquidity positions for a given owner
194    ///
195    /// # Params
196    /// owner - Public key of the position owner
197    ///
198    /// # Example
199    /// ```rust
200    /// use orca_rs::client::OrcaClient;
201    /// use solana_sdk::pubkey::Pubkey;
202    ///
203    /// let client = OrcaClient::new("https://api.mainnet-beta.solana.com");
204    /// let owner = Pubkey::new_unique();
205    /// let positions = client.get_liquidity_positions(&owner).await?;
206    ///
207    /// for position in positions {
208    ///     println!("Position: {} LP tokens", position.lp_token_amount);
209    /// }
210    /// ```
211    pub async fn get_liquidity_positions(
212        &self,
213        owner: &Pubkey,
214    ) -> OrcaResult<Vec<LiquidityPosition>> {
215        let token_accounts = self
216            .solana
217            .client
218            .as_ref()
219            .ok_or(OrcaError::Error("RPC client not available".to_string()))?
220            .get_token_accounts_by_owner(
221                owner,
222                solana_client::rpc_request::TokenAccountsFilter::ProgramId(spl_token::id()),
223            )
224            .await
225            .map_err(|e| OrcaError::Error(format!("Failed to get token accounts: {}", e)))?;
226        let mut positions = Vec::new();
227        for account in token_accounts {
228            let account_data_bytes = self.decode_account_data(&account.account.data)?;
229            let token_account = spl_token::state::Account::unpack_from_slice(&account_data_bytes)
230                .map_err(|e| {
231                OrcaError::Error(format!("Failed to unpack token account: {}", e))
232            })?;
233            if token_account.amount > 0 && self.is_position_token(&token_account.mint).await? {
234                let position = LiquidityPosition {
235                    pool_address: Pubkey::default(), // 需要从链上数据解析
236                    token_a_amount: 0,
237                    token_b_amount: 0,
238                    lp_token_amount: token_account.amount,
239                    lower_tick: 0,
240                    upper_tick: 0,
241                    position_mint: token_account.mint,
242                    position_token_account: Pubkey::from_str(&account.pubkey)
243                        .map_err(|e| OrcaError::Error(format!("Invalid account pubkey: {}", e)))?,
244                };
245                positions.push(position);
246            }
247        }
248        Ok(positions)
249    }
250
251    async fn is_position_token(&self, mint: &Pubkey) -> OrcaResult<bool> {
252        let client = self
253            .solana
254            .client
255            .as_ref()
256            .ok_or(OrcaError::Error("RPC client not available".to_string()))?;
257        let mint_account = match client.get_account(mint).await {
258            Ok(account) => account,
259            Err(_) => return Ok(false),
260        };
261        let token_data = spl_token::state::Mint::unpack(&mint_account.data)
262            .map_err(|e| OrcaError::Error(format!("Failed to unpack mint data: {}", e)))?;
263        if self
264            .is_position_token_by_metadata(mint, &token_data)
265            .await?
266        {
267            return Ok(true);
268        }
269        if self.is_position_token_by_holders(mint).await? {
270            return Ok(true);
271        }
272        if self.is_position_token_by_pool_association(mint).await? {
273            return Ok(true);
274        }
275        Ok(false)
276    }
277
278    async fn is_position_token_by_metadata(
279        &self,
280        mint: &Pubkey,
281        token_data: &spl_token::state::Mint,
282    ) -> OrcaResult<bool> {
283        let token_name = self.get_token_name(mint).await.unwrap_or_default();
284        let token_symbol = self.get_token_symbol(mint).await.unwrap_or_default();
285        let position_patterns = ["position", "LP", "liquidity", "whirlpool", "concentrated"];
286        for pattern in &position_patterns {
287            if token_name.to_lowercase().contains(pattern)
288                || token_symbol.to_lowercase().contains(pattern)
289            {
290                return Ok(true);
291            }
292        }
293        if token_data.decimals == 6 || token_data.decimals == 9 {
294            return self.verify_position_token(mint).await;
295        }
296        Ok(false)
297    }
298
299    async fn is_position_token_by_holders(&self, mint: &Pubkey) -> OrcaResult<bool> {
300        let client = self
301            .solana
302            .client
303            .as_ref()
304            .ok_or(OrcaError::Error("RPC client not available".to_string()))?;
305        let token_accounts = client
306            .get_token_accounts_by_owner(
307                &self.whirlpool_program_id,
308                solana_client::rpc_request::TokenAccountsFilter::Mint(*mint),
309            )
310            .await;
311        if let Ok(accounts) = token_accounts {
312            if !accounts.is_empty() {
313                return Ok(true);
314            }
315        }
316        Ok(false)
317    }
318
319    async fn is_position_token_by_pool_association(&self, mint: &Pubkey) -> OrcaResult<bool> {
320        let pools = self.get_all_whirlpools().await?;
321        for pool in pools {
322            if let Ok(pool_info) = self.get_pool_state_onchain(&pool).await {
323                if pool_info.lp_token_mint == mint.to_string() {
324                    return Ok(true);
325                }
326            }
327        }
328        Ok(false)
329    }
330
331    async fn get_all_whirlpools(&self) -> OrcaResult<Vec<String>> {
332        let client = self
333            .solana
334            .client
335            .as_ref()
336            .ok_or(OrcaError::Error("RPC client not available".to_string()))?;
337        let accounts = client
338            .get_program_accounts(&self.whirlpool_program_id)
339            .await
340            .map_err(|e| OrcaError::Error(format!("Failed to get program accounts: {}", e)))?;
341        Ok(accounts
342            .into_iter()
343            .map(|(pubkey, _)| pubkey.to_string())
344            .collect())
345    }
346
347    /// Verifies if a token is a valid Whirlpool position token
348    ///
349    /// # Params
350    /// mint - The position token mint address to verify
351    ///
352    /// # Example
353    /// ```rust
354    /// use orca_rs::client::OrcaClient;
355    /// use solana_sdk::pubkey::Pubkey;
356    ///
357    /// let client = OrcaClient::new("https://api.mainnet-beta.solana.com");
358    /// let mint = Pubkey::new_unique();
359    /// let is_position = client.verify_position_token(&mint).await?;
360    /// println!("Is position token: {}", is_position);
361    /// ```
362    async fn verify_position_token(&self, mint: &Pubkey) -> OrcaResult<bool> {
363        let client = self
364            .solana
365            .client
366            .as_ref()
367            .ok_or(OrcaError::Error("RPC client not available".to_string()))?;
368        // Method 1: Check if there's a position account for this mint
369        let position_pda = self.get_position_pda(mint);
370        match client.get_account(&position_pda).await {
371            Ok(account) => {
372                // Verify the account is owned by whirlpool program and has data
373                Ok(account.owner == self.whirlpool_program_id && account.data.len() >= 216) // Minimum position account size
374            }
375            Err(_) => Ok(false),
376        }
377    }
378
379    /// Derives the position PDA from the position token mint
380    fn get_position_pda(&self, position_mint: &Pubkey) -> Pubkey {
381        let (pda, _) = Pubkey::find_program_address(
382            &[b"position", position_mint.as_ref()],
383            &self.whirlpool_program_id,
384        );
385        pda
386    }
387
388    async fn get_token_name(&self, mint: &Pubkey) -> OrcaResult<String> {
389        let client = self
390            .solana
391            .client
392            .as_ref()
393            .ok_or(OrcaError::Error("RPC client not available".to_string()))?;
394        let metadata_program = Pubkey::from_str(crate::global::TOKEN_METADATA_PROGRAM_ID)
395            .map_err(|e| OrcaError::Error(format!("Invalid metadata program ID: {}", e)))?;
396        let (metadata_address, _) = Pubkey::find_program_address(
397            &[b"metadata", metadata_program.as_ref(), mint.as_ref()],
398            &metadata_program,
399        );
400        match client.get_account(&metadata_address).await {
401            Ok(account) => {
402                if account.data.len() > 120 {
403                    let name_data = &account.data[69..109];
404                    let name = String::from_utf8_lossy(name_data)
405                        .trim_end_matches('\0')
406                        .to_string();
407                    if !name.is_empty() {
408                        return Ok(name);
409                    }
410                }
411                Ok("Unknown".to_string())
412            }
413            Err(_) => Ok("Unknown".to_string()),
414        }
415    }
416
417    async fn get_token_symbol(&self, mint: &Pubkey) -> OrcaResult<String> {
418        let client = self
419            .solana
420            .client
421            .as_ref()
422            .ok_or(OrcaError::Error("RPC client not available".to_string()))?;
423        let metadata_program = Pubkey::from_str(crate::global::TOKEN_METADATA_PROGRAM_ID)
424            .map_err(|e| OrcaError::Error(format!("Invalid metadata program ID: {}", e)))?;
425        let (metadata_address, _) = Pubkey::find_program_address(
426            &[b"metadata", metadata_program.as_ref(), mint.as_ref()],
427            &metadata_program,
428        );
429        match client.get_account(&metadata_address).await {
430            Ok(account) => {
431                if account.data.len() > 120 {
432                    let symbol_data = &account.data[109..119];
433                    let symbol = String::from_utf8_lossy(symbol_data)
434                        .trim_end_matches('\0')
435                        .to_string();
436                    if !symbol.is_empty() {
437                        return Ok(symbol);
438                    }
439                }
440                Ok("UNK".to_string())
441            }
442            Err(_) => Ok("UNK".to_string()),
443        }
444    }
445
446    fn build_open_position_instruction(
447        &self,
448        owner: &Pubkey,
449        pool: &Pubkey,
450        position_mint: &Pubkey,
451        position_token_account: &Pubkey,
452        lower_tick: i32,
453        upper_tick: i32,
454    ) -> OrcaResult<Instruction> {
455        let accounts = vec![
456            AccountMeta::new_readonly(self.whirlpool_program_id, false),
457            AccountMeta::new_readonly(*owner, true),
458            AccountMeta::new(*position_mint, true),
459            AccountMeta::new(*position_token_account, false),
460            AccountMeta::new(*pool, false),
461            AccountMeta::new_readonly(spl_token::id(), false),
462            AccountMeta::new_readonly(system_program::id(), false),
463            AccountMeta::new_readonly(sysvar::rent::id(), false),
464        ];
465        let mut data = vec![0x08]; // open_position instruction discriminator
466        data.extend_from_slice(&lower_tick.to_le_bytes());
467        data.extend_from_slice(&upper_tick.to_le_bytes());
468        Ok(Instruction {
469            program_id: self.whirlpool_program_id,
470            accounts,
471            data,
472        })
473    }
474
475    fn build_increase_liquidity_instruction(
476        &self,
477        owner: &Pubkey,
478        pool: &Pubkey,
479        position_token_account: &Pubkey,
480        token_a_account: &Pubkey,
481        token_b_account: &Pubkey,
482        token_a_mint: &Pubkey,
483        token_b_mint: &Pubkey,
484        position_mint: &Pubkey,
485        token_a_amount: u64,
486        token_b_amount: u64,
487    ) -> OrcaResult<Instruction> {
488        let token_vault_a = self.get_associated_token_address(pool, token_a_mint);
489        let token_vault_b = self.get_associated_token_address(pool, token_b_mint);
490        let accounts = vec![
491            AccountMeta::new_readonly(self.whirlpool_program_id, false),
492            AccountMeta::new_readonly(*owner, true),
493            AccountMeta::new(*position_token_account, false),
494            AccountMeta::new(*pool, false),
495            AccountMeta::new(*token_a_account, false),
496            AccountMeta::new(*token_b_account, false),
497            AccountMeta::new(token_vault_a, false),
498            AccountMeta::new(token_vault_b, false),
499            AccountMeta::new(*position_mint, false),
500            AccountMeta::new_readonly(spl_token::id(), false),
501            AccountMeta::new_readonly(system_program::id(), false),
502        ];
503        let mut data = vec![0x09]; // increase_liquidity instruction discriminator
504        data.extend_from_slice(&token_a_amount.to_le_bytes());
505        data.extend_from_slice(&token_b_amount.to_le_bytes());
506        Ok(Instruction {
507            program_id: self.whirlpool_program_id,
508            accounts,
509            data,
510        })
511    }
512
513    fn build_decrease_liquidity_instruction(
514        &self,
515        owner: &Pubkey,
516        pool: &Pubkey,
517        position_token_account: &Pubkey,
518        position_mint: &Pubkey,
519        liquidity_amount: u64,
520    ) -> OrcaResult<Instruction> {
521        let accounts = vec![
522            AccountMeta::new_readonly(self.whirlpool_program_id, false),
523            AccountMeta::new_readonly(*owner, true),
524            AccountMeta::new(*position_token_account, false),
525            AccountMeta::new(*pool, false),
526            AccountMeta::new(*position_mint, false),
527            AccountMeta::new_readonly(spl_token::id(), false),
528        ];
529        let mut data = vec![0x0A]; // decrease_liquidity instruction discriminator
530        data.extend_from_slice(&liquidity_amount.to_le_bytes());
531        Ok(Instruction {
532            program_id: self.whirlpool_program_id,
533            accounts,
534            data,
535        })
536    }
537
538    fn build_close_position_instruction(
539        &self,
540        owner: &Pubkey,
541        pool: &Pubkey,
542        position_token_account: &Pubkey,
543        position_mint: &Pubkey,
544    ) -> OrcaResult<Instruction> {
545        let accounts = vec![
546            AccountMeta::new_readonly(self.whirlpool_program_id, false),
547            AccountMeta::new_readonly(*owner, true),
548            AccountMeta::new(*position_token_account, false),
549            AccountMeta::new(*pool, false),
550            AccountMeta::new(*position_mint, false),
551            AccountMeta::new_readonly(spl_token::id(), false),
552        ];
553        let data = vec![0x0B]; // close_position instruction discriminator
554        Ok(Instruction {
555            program_id: self.whirlpool_program_id,
556            accounts,
557            data,
558        })
559    }
560}