litesvm_token/
create_ata.rs1use {
2 super::TOKEN_ID,
3 litesvm::{types::FailedTransactionMetadata, LiteSVM},
4 solana_keypair::Keypair,
5 solana_pubkey::Pubkey,
6 solana_signer::Signer,
7 solana_transaction::Transaction,
8 spl_associated_token_account_interface::instruction::create_associated_token_account,
9};
10
11pub struct CreateAssociatedTokenAccount<'a> {
18 svm: &'a mut LiteSVM,
19 payer: &'a Keypair,
20 mint: &'a Pubkey,
21 token_program_id: Option<&'a Pubkey>,
22 owner: Option<Pubkey>,
23}
24
25impl<'a> CreateAssociatedTokenAccount<'a> {
26 pub fn new(svm: &'a mut LiteSVM, payer: &'a Keypair, mint: &'a Pubkey) -> Self {
28 CreateAssociatedTokenAccount {
29 svm,
30 payer,
31 owner: None,
32 token_program_id: None,
33 mint,
34 }
35 }
36
37 pub fn owner(mut self, owner: &'a Pubkey) -> Self {
39 self.owner = Some(*owner);
40 self
41 }
42
43 pub fn token_program_id(mut self, program_id: &'a Pubkey) -> Self {
45 self.token_program_id = Some(program_id);
46 self
47 }
48
49 pub fn send(self) -> Result<Pubkey, FailedTransactionMetadata> {
51 let token_program_id = self.token_program_id.unwrap_or(&TOKEN_ID);
52 let payer_pk = self.payer.pubkey();
53
54 let authority = self.owner.unwrap_or(payer_pk);
55
56 let ix =
57 create_associated_token_account(&payer_pk, &authority, self.mint, token_program_id);
58
59 let block_hash = self.svm.latest_blockhash();
60 let tx =
61 Transaction::new_signed_with_payer(&[ix], Some(&payer_pk), &[self.payer], block_hash);
62
63 self.svm.send_transaction(tx)?;
64
65 let ata = spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
66 &authority,
67 self.mint,
68 token_program_id,
69 );
70
71 Ok(ata)
72 }
73}