Skip to main content

solana_pipkit/
token_utils.rs

1//! SPL Token utilities for common operations.
2//!
3//! Provides helpers for token minting, burning, transfers, and account management.
4
5use solana_client::nonblocking::rpc_client::RpcClient;
6use solana_sdk::{
7    commitment_config::CommitmentConfig,
8    instruction::Instruction,
9    message::Message,
10    pubkey::Pubkey,
11    signature::{Keypair, Signer},
12    transaction::Transaction,
13};
14use spl_token::{
15    instruction as token_instruction,
16    solana_program::program_pack::Pack,
17    state::{Account as TokenAccount, Mint},
18};
19
20use crate::{pda::find_associated_token_address, Result, ToolkitError};
21
22/// Token client for SPL token operations.
23pub struct TokenClient {
24    client: RpcClient,
25    payer: Keypair,
26}
27
28impl TokenClient {
29    pub fn new(rpc_url: &str, payer: Keypair) -> Self {
30        Self {
31            client: RpcClient::new_with_commitment(
32                rpc_url.to_string(),
33                CommitmentConfig::confirmed(),
34            ),
35            payer,
36        }
37    }
38
39    /// Burn tokens from a token account.
40    pub async fn burn(
41        &self,
42        mint: &Pubkey,
43        token_account: &Pubkey,
44        amount: u64,
45    ) -> Result<()> {
46        let instruction = token_instruction::burn(
47            &spl_token::id(),
48            token_account,
49            mint,
50            &self.payer.pubkey(),
51            &[],
52            amount,
53        )?;
54
55        self.send_transaction(vec![instruction]).await
56    }
57
58    /// Burn tokens and close the account if empty.
59    #[allow(clippy::vec_init_then_push)]
60    pub async fn burn_and_close(
61        &self,
62        mint: &Pubkey,
63        token_account: &Pubkey,
64        amount: u64,
65    ) -> Result<u64> {
66        let mut instructions = vec![];
67
68        // Burn instruction
69        instructions.push(token_instruction::burn(
70            &spl_token::id(),
71            token_account,
72            mint,
73            &self.payer.pubkey(),
74            &[],
75            amount,
76        )?);
77
78        // Close account instruction
79        instructions.push(token_instruction::close_account(
80            &spl_token::id(),
81            token_account,
82            &self.payer.pubkey(),
83            &self.payer.pubkey(),
84            &[],
85        )?);
86
87        // Get account balance before closing
88        let account = self.client.get_account(token_account).await?;
89        let lamports = account.lamports;
90
91        self.send_transaction(instructions).await?;
92
93        Ok(lamports)
94    }
95
96    /// Transfer tokens between accounts.
97    pub async fn transfer(
98        &self,
99        _mint: &Pubkey,
100        source: &Pubkey,
101        destination: &Pubkey,
102        amount: u64,
103    ) -> Result<()> {
104        let instruction = token_instruction::transfer(
105            &spl_token::id(),
106            source,
107            destination,
108            &self.payer.pubkey(),
109            &[],
110            amount,
111        )?;
112
113        self.send_transaction(vec![instruction]).await
114    }
115
116    /// Create an associated token account.
117    pub async fn create_associated_token_account(
118        &self,
119        wallet: &Pubkey,
120        mint: &Pubkey,
121    ) -> Result<Pubkey> {
122        let (ata, _) = find_associated_token_address(wallet, mint);
123
124        let instruction =
125            spl_associated_token_account::instruction::create_associated_token_account(
126                &self.payer.pubkey(),
127                wallet,
128                mint,
129                &spl_token::id(),
130            );
131
132        self.send_transaction(vec![instruction]).await?;
133
134        Ok(ata)
135    }
136
137    /// Get or create associated token account.
138    pub async fn get_or_create_ata(
139        &self,
140        wallet: &Pubkey,
141        mint: &Pubkey,
142    ) -> Result<Pubkey> {
143        let (ata, _) = find_associated_token_address(wallet, mint);
144
145        // Check if account exists
146        match self.client.get_account(&ata).await {
147            Ok(_) => Ok(ata),
148            Err(_) => self.create_associated_token_account(wallet, mint).await,
149        }
150    }
151
152    /// Close a token account and recover rent.
153    pub async fn close_account(&self, token_account: &Pubkey) -> Result<u64> {
154        let account = self.client.get_account(token_account).await?;
155        let lamports = account.lamports;
156
157        let instruction = token_instruction::close_account(
158            &spl_token::id(),
159            token_account,
160            &self.payer.pubkey(),
161            &self.payer.pubkey(),
162            &[],
163        )?;
164
165        self.send_transaction(vec![instruction]).await?;
166
167        Ok(lamports)
168    }
169
170    /// Get token account balance.
171    pub async fn get_balance(&self, token_account: &Pubkey) -> Result<u64> {
172        let account = self.client.get_account(token_account).await?;
173        let token_account = TokenAccount::unpack(&account.data)
174            .map_err(|e| ToolkitError::InvalidAccountData(e.to_string()))?;
175        Ok(token_account.amount)
176    }
177
178    /// Get mint info.
179    pub async fn get_mint_info(&self, mint: &Pubkey) -> Result<MintInfo> {
180        let account = self.client.get_account(mint).await?;
181        let mint_data = Mint::unpack(&account.data)
182            .map_err(|e| ToolkitError::InvalidAccountData(e.to_string()))?;
183
184        Ok(MintInfo {
185            supply: mint_data.supply,
186            decimals: mint_data.decimals,
187            is_initialized: mint_data.is_initialized,
188            mint_authority: mint_data.mint_authority.into(),
189            freeze_authority: mint_data.freeze_authority.into(),
190        })
191    }
192
193    async fn send_transaction(&self, instructions: Vec<Instruction>) -> Result<()> {
194        let recent_blockhash = self.client.get_latest_blockhash().await?;
195        let message = Message::new(&instructions, Some(&self.payer.pubkey()));
196        let transaction = Transaction::new(&[&self.payer], message, recent_blockhash);
197
198        self.client
199            .send_and_confirm_transaction(&transaction)
200            .await?;
201
202        Ok(())
203    }
204}
205
206/// Mint information.
207#[derive(Debug, Clone)]
208pub struct MintInfo {
209    pub supply: u64,
210    pub decimals: u8,
211    pub is_initialized: bool,
212    pub mint_authority: Option<Pubkey>,
213    pub freeze_authority: Option<Pubkey>,
214}
215
216/// Standalone burn function.
217pub async fn burn_tokens(
218    rpc_url: &str,
219    payer: Keypair,
220    mint: &Pubkey,
221    token_account: &Pubkey,
222    amount: u64,
223) -> Result<()> {
224    let client = TokenClient::new(rpc_url, payer);
225    client.burn(mint, token_account, amount).await
226}
227
228/// Standalone close account function.
229pub async fn close_token_account(
230    rpc_url: &str,
231    payer: Keypair,
232    token_account: &Pubkey,
233) -> Result<u64> {
234    let client = TokenClient::new(rpc_url, payer);
235    client.close_account(token_account).await
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    #[test]
243    fn test_mint_info_debug() {
244        let info = MintInfo {
245            supply: 1_000_000,
246            decimals: 9,
247            is_initialized: true,
248            mint_authority: None,
249            freeze_authority: None,
250        };
251        assert_eq!(info.decimals, 9);
252    }
253}