Skip to main content

orca_sdk/
trade.rs

1use super::*;
2use crate::types::OrcaResult;
3use solana_sdk::message::{AccountMeta, Instruction};
4use std::str::FromStr;
5
6#[derive(Debug, Clone)]
7pub struct TradeConfig {
8    pub slippage: f64,
9    pub max_iterations: u8,
10}
11
12impl Default for TradeConfig {
13    fn default() -> Self {
14        Self {
15            slippage: 0.5,
16            max_iterations: 3,
17        }
18    }
19}
20
21impl OrcaClient {
22    /// Executes a token swap between specified input and output mints
23    ///
24    /// # Arguments
25    /// keypair - Keypair for signing the transaction
26    /// input_mint - Mint address of the input token
27    /// output_mint - Mint address of the output token
28    /// amount - Amount of input tokens to swap
29    /// config - Optional trade configuration parameters
30    ///
31    /// # Returns
32    /// Transaction signature if successful
33    ///
34    /// # Examples
35    /// ```rust
36    /// use orca_sdk::client::OrcaClient;
37    /// use solana_sdk::signature::Keypair;
38    ///
39    /// let client = OrcaClient::new();
40    /// let keypair = Keypair::new();
41    /// let input_mint = "So11111111111111111111111111111111111111112";
42    /// let output_mint = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
43    /// let amount = 1_000_000; // 1 SOL
44    ///
45    /// let signature = client.swap(&keypair, input_mint, output_mint, amount, None).await?;
46    /// println!("Swap completed with signature: {}", signature);
47    /// ```
48    pub async fn swap(
49        &self,
50        keypair: &Keypair,
51        input_mint: &str,
52        output_mint: &str,
53        amount: u64,
54        config: Option<TradeConfig>,
55    ) -> OrcaResult<Signature> {
56        let config = config.unwrap_or_default();
57        let quote = self
58            .get_quote_from_pool(input_mint, output_mint, amount, config.slippage)
59            .await?;
60        let input_mint_pubkey = Pubkey::from_str(input_mint)
61            .map_err(|e| OrcaError::Error(format!("Invalid input mint: {}", e)))?;
62        let output_mint_pubkey = Pubkey::from_str(output_mint)
63            .map_err(|e| OrcaError::Error(format!("Invalid output mint: {}", e)))?;
64        let input_token_account = self
65            .ensure_token_account(keypair, &input_mint_pubkey)
66            .await?;
67        let output_token_account = self
68            .ensure_token_account(keypair, &output_mint_pubkey)
69            .await?;
70        let pools = self.find_pools_by_token_onchain(input_mint).await?;
71        let target_pool = {
72            let mut found_pool = None;
73            for pool in pools {
74                if let Ok(pool_info) = self.get_pool_state_onchain(&pool).await {
75                    if (pool_info.token_mint_a == input_mint
76                        && pool_info.token_mint_b == output_mint)
77                        || (pool_info.token_mint_a == output_mint
78                            && pool_info.token_mint_b == input_mint)
79                    {
80                        found_pool = Some(pool.clone());
81                        break;
82                    }
83                }
84            }
85            found_pool
86        }
87        .ok_or(OrcaError::Error("No suitable pool found".to_string()))?;
88        let pool_pubkey = Pubkey::from_str(&target_pool)
89            .map_err(|e| OrcaError::Error(format!("Invalid pool address: {}", e)))?;
90        let recent_blockhash = self
91            .solana
92            .client
93            .as_ref()
94            .ok_or(OrcaError::Error("RPC client not available".to_string()))?
95            .get_latest_blockhash()
96            .await
97            .map_err(|e| OrcaError::Error(format!("Failed to get blockhash: {}", e)))?;
98        let swap_instruction = self.build_swap_instruction(
99            &keypair.pubkey(),
100            &pool_pubkey,
101            &input_token_account,
102            &output_token_account,
103            &input_mint_pubkey,
104            &output_mint_pubkey,
105            amount,
106            quote.min_output_amount,
107        )?;
108        let message = Message::new(&[swap_instruction], Some(&keypair.pubkey()));
109        let transaction = Transaction::new(&[keypair], message, recent_blockhash);
110        self.solana
111            .client
112            .as_ref()
113            .ok_or(OrcaError::Error("RPC client not available".to_string()))?
114            .send_and_confirm_transaction(&transaction)
115            .await
116            .map_err(|e| OrcaError::Error(format!("Failed to execute swap: {}", e)))
117    }
118
119    /// Constructs a swap instruction for the Whirlpool program
120    ///
121    /// # Arguments
122    /// owner - Owner of the token accounts
123    /// pool - Whirlpool address
124    /// input_token_account - Input token account
125    /// output_token_account - Output token account
126    /// input_mint - Input token mint
127    /// output_mint - Output token mint
128    /// input_amount - Amount of input tokens
129    /// min_output_amount - Minimum amount of output tokens to receive
130    ///
131    /// # Examples
132    /// ```rust
133    /// use orca_sdk::client::OrcaClient;
134    /// use solana_sdk::pubkey::Pubkey;
135    ///
136    /// let client = OrcaClient::new_with_defaults();
137    /// let owner = Pubkey::new_unique();
138    /// let pool = Pubkey::new_unique();
139    /// let input_token_account = Pubkey::new_unique();
140    /// let output_token_account = Pubkey::new_unique();
141    /// let input_mint = Pubkey::new_unique();
142    /// let output_mint = Pubkey::new_unique();
143    /// let input_amount = 1_000_000;
144    /// let min_output_amount = 500_000;
145    ///
146    /// let instruction = client.build_swap_instruction(
147    ///     &owner,
148    ///     &pool,
149    ///     &input_token_account,
150    ///     &output_token_account,
151    ///     &input_mint,
152    ///     &output_mint,
153    ///     input_amount,
154    ///     min_output_amount,
155    /// )?;
156    /// ```
157    fn build_swap_instruction(
158        &self,
159        owner: &Pubkey,
160        pool: &Pubkey,
161        input_token_account: &Pubkey,
162        output_token_account: &Pubkey,
163        input_mint: &Pubkey,
164        output_mint: &Pubkey,
165        input_amount: u64,
166        min_output_amount: u64,
167    ) -> OrcaResult<Instruction> {
168        let token_vault_a = self.get_associated_token_address(pool, input_mint);
169        let token_vault_b = self.get_associated_token_address(pool, output_mint);
170        let accounts = vec![
171            AccountMeta::new_readonly(self.whirlpool_program_id, false),
172            AccountMeta::new_readonly(*owner, true),
173            AccountMeta::new(*pool, false),
174            AccountMeta::new(*input_token_account, false),
175            AccountMeta::new(*output_token_account, false),
176            AccountMeta::new(token_vault_a, false),
177            AccountMeta::new(token_vault_b, false),
178            AccountMeta::new_readonly(spl_token::id(), false),
179        ];
180        let mut data = vec![0x01]; // swap instruction discriminator
181        data.extend_from_slice(&input_amount.to_le_bytes());
182        data.extend_from_slice(&min_output_amount.to_le_bytes());
183        Ok(Instruction {
184            program_id: self.whirlpool_program_id,
185            accounts,
186            data,
187        })
188    }
189}