Skip to main content

orca_sdk/
balance.rs

1use super::*;
2use crate::types::OrcaResult;
3use base64::{Engine, prelude::BASE64_STANDARD};
4use solana_account_decoder::{UiAccountData, UiAccountEncoding};
5use solana_client::rpc_request::TokenAccountsFilter;
6use solana_sdk::program_pack::Pack;
7
8impl OrcaClient {
9    /// Get the balance of a specific token for a given owner and mint
10    ///
11    /// # Params
12    /// owner - The public key of the token account owner
13    /// mint - The public key of the token mint
14    ///
15    /// # Example
16    /// ```rust
17    /// use solana_sdk::pubkey;
18    ///
19    /// # async fn example(client: &OrcaClient) -> OrcaResult<()> {
20    /// let owner = pubkey!("OwnerPublicKeyHere");
21    /// let mint = pubkey!("MintPublicKeyHere");
22    /// let balance = client.get_token_balance(&owner, &mint).await?;
23    /// println!("Token balance: {}", balance);
24    /// # Ok(())
25    /// # }
26    /// ```
27    pub async fn get_token_balance(&self, owner: &Pubkey, mint: &Pubkey) -> OrcaResult<u64> {
28        let token_accounts = self
29            .solana
30            .client
31            .as_ref()
32            .ok_or(OrcaError::Error("RPC client not available".to_string()))?
33            .get_token_accounts_by_owner(owner, TokenAccountsFilter::Mint(*mint))
34            .await
35            .map_err(|e| OrcaError::Error(format!("Failed to get token accounts: {}", e)))?;
36        if let Some(account) = token_accounts.first() {
37            let account_data_bytes = self.decode_account_data(&account.account.data)?;
38            let account_data: spl_token::state::Account =
39                spl_token::state::Account::unpack(&account_data_bytes).map_err(|e| {
40                    OrcaError::Error(format!("Failed to unpack token account: {}", e))
41                })?;
42            Ok(account_data.amount)
43        } else {
44            Ok(0)
45        }
46    }
47
48    /// Get balances for all tokens owned by a specific account
49    ///
50    /// # Params
51    /// owner - The public key of the token account owner
52    ///
53    /// # Example
54    /// ```rust
55    /// use solana_sdk::pubkey;
56    ///
57    /// # async fn example(client: &OrcaClient) -> OrcaResult<()> {
58    /// let owner = pubkey!("OwnerPublicKeyHere");
59    /// let balances = client.get_all_token_balances(&owner).await?;
60    /// for (mint, balance) in balances {
61    ///     println!("Mint: {}, Balance: {}", mint, balance);
62    /// }
63    /// # Ok(())
64    /// # }
65    /// ```
66    pub async fn get_all_token_balances(&self, owner: &Pubkey) -> OrcaResult<Vec<(Pubkey, u64)>> {
67        let token_accounts = self
68            .solana
69            .client
70            .as_ref()
71            .ok_or(OrcaError::Error("RPC client not available".to_string()))?
72            .get_token_accounts_by_owner(owner, TokenAccountsFilter::ProgramId(spl_token::id()))
73            .await
74            .map_err(|e| OrcaError::Error(format!("Failed to get token accounts: {}", e)))?;
75        let mut balances = Vec::new();
76        for account in token_accounts {
77            let account_data_bytes = self.decode_account_data(&account.account.data)?;
78            let account_data: spl_token::state::Account =
79                spl_token::state::Account::unpack(&account_data_bytes).map_err(|e| {
80                    OrcaError::Error(format!("Failed to unpack token account: {}", e))
81                })?;
82
83            if account_data.amount > 0 {
84                balances.push((account_data.mint, account_data.amount));
85            }
86        }
87        Ok(balances)
88    }
89
90    /// Ensure a token account exists for the given keypair and mint
91    /// Creates the account if it doesn't exist
92    ///
93    /// # Params
94    /// keypair - The keypair that owns the token account
95    /// mint - The public key of the token mint
96    ///
97    /// # Example
98    /// ```rust
99    /// use solana_sdk::{pubkey, signer::keypair::Keypair};
100    ///
101    /// # async fn example(client: &OrcaClient) -> OrcaResult<()> {
102    /// let keypair = Keypair::new();
103    /// let mint = pubkey!("MintPublicKeyHere");
104    /// let token_account = client.ensure_token_account(&keypair, &mint).await?;
105    /// println!("Token account: {}", token_account);
106    /// # Ok(())
107    /// # }
108    /// ```
109    pub async fn ensure_token_account(
110        &self,
111        keypair: &Keypair,
112        mint: &Pubkey,
113    ) -> OrcaResult<Pubkey> {
114        let associated_token_address = self.get_associated_token_address(&keypair.pubkey(), mint);
115        match self
116            .solana
117            .client
118            .as_ref()
119            .ok_or(OrcaError::Error("RPC client not available".to_string()))?
120            .get_account(&associated_token_address)
121            .await
122        {
123            Ok(_) => Ok(associated_token_address),
124            Err(_) => self.create_associated_token_account(keypair, mint).await,
125        }
126    }
127
128    /// Create an associated token account for the given keypair and mint
129    ///
130    /// # Params
131    /// keypair - The keypair that will own the token account
132    /// mint - The public key of the token mint
133    ///
134    /// # Example
135    /// ```rust
136    /// use solana_sdk::{pubkey, signer::keypair::Keypair};
137    ///
138    /// # async fn example(client: &OrcaClient) -> OrcaResult<()> {
139    /// let keypair = Keypair::new();
140    /// let mint = pubkey!("MintPublicKeyHere");
141    /// let token_account = client.create_associated_token_account(&keypair, &mint).await?;
142    /// println!("Created token account: {}", token_account);
143    /// # Ok(())
144    /// # }
145    /// ```
146    pub async fn create_associated_token_account(
147        &self,
148        keypair: &Keypair,
149        mint: &Pubkey,
150    ) -> OrcaResult<Pubkey> {
151        let recent_blockhash = self
152            .solana
153            .client
154            .as_ref()
155            .ok_or(OrcaError::Error("RPC client not available".to_string()))?
156            .get_latest_blockhash()
157            .await
158            .map_err(|e| OrcaError::Error(format!("Failed to get blockhash: {}", e)))?;
159        let instruction =
160            spl_associated_token_account::instruction::create_associated_token_account(
161                &keypair.pubkey(),
162                &keypair.pubkey(),
163                mint,
164                &spl_token::id(),
165            );
166        let message = Message::new(&[instruction], Some(&keypair.pubkey()));
167        let transaction = Transaction::new(&[keypair], message, recent_blockhash);
168        self.solana
169            .client
170            .as_ref()
171            .ok_or(OrcaError::Error("RPC client not available".to_string()))?
172            .send_and_confirm_transaction(&transaction)
173            .await
174            .map_err(|e| OrcaError::Error(format!("Failed to create token account: {}", e)))?;
175        Ok(self.get_associated_token_address(&keypair.pubkey(), mint))
176    }
177
178    /// Get the total supply of a token mint
179    ///
180    /// # Params
181    /// mint - The public key of the token mint
182    ///
183    /// # Example
184    /// ```rust
185    /// use solana_sdk::pubkey;
186    ///
187    /// # async fn example(client: &OrcaClient) -> OrcaResult<()> {
188    /// let mint = pubkey!("MintPublicKeyHere");
189    /// let supply = client.get_token_supply(&mint).await?;
190    /// println!("Token supply: {}", supply);
191    /// # Ok(())
192    /// # }
193    /// ```
194    pub async fn get_token_supply(&self, mint: &Pubkey) -> OrcaResult<u64> {
195        let mint_account = self
196            .solana
197            .client
198            .as_ref()
199            .ok_or(OrcaError::Error("RPC client not available".to_string()))?
200            .get_account(mint)
201            .await
202            .map_err(|e| OrcaError::Error(format!("Failed to get mint account: {}", e)))?;
203        let mint_data: spl_token::state::Mint = spl_token::state::Mint::unpack(&mint_account.data)
204            .map_err(|e| OrcaError::Error(format!("Failed to unpack mint data: {}", e)))?;
205        Ok(mint_data.supply)
206    }
207
208    /// Decode account data from various encoding formats
209    ///
210    /// # Params
211    /// ui_account_data - The UI account data to decode
212    ///
213    pub fn decode_account_data(&self, ui_account_data: &UiAccountData) -> OrcaResult<Vec<u8>> {
214        match ui_account_data {
215            UiAccountData::Binary(data, encoding) => match encoding {
216                UiAccountEncoding::Base64 => BASE64_STANDARD
217                    .decode(data)
218                    .map_err(|e| OrcaError::Error(format!("Base64 decode error: {}", e))),
219                UiAccountEncoding::Base64Zstd => {
220                    let compressed_data = BASE64_STANDARD
221                        .decode(data)
222                        .map_err(|e| OrcaError::Error(format!("Base64 decode error: {}", e)))?;
223                    zstd::decode_all(&compressed_data[..])
224                        .map_err(|e| OrcaError::Error(format!("Zstd decode error: {}", e)))
225                }
226                _ => Err(OrcaError::Error(format!(
227                    "Unsupported encoding: {:?}",
228                    encoding
229                ))),
230            },
231            _ => Err(OrcaError::Error(
232                "Unsupported account data format".to_string(),
233            )),
234        }
235    }
236}