hpsvm_token/
create_ata.rs1use hpsvm::{HPSVM, types::FailedTransactionMetadata};
2use solana_address::Address;
3use solana_keypair::Keypair;
4use solana_signer::Signer;
5use spl_associated_token_account_interface::instruction::create_associated_token_account;
6
7use super::TOKEN_ID;
8
9#[derive(Debug)]
16pub struct CreateAssociatedTokenAccount<'a> {
17 svm: &'a mut HPSVM,
18 payer: &'a Keypair,
19 mint: &'a Address,
20 token_program_id: Option<&'a Address>,
21 owner: Option<Address>,
22}
23
24impl<'a> CreateAssociatedTokenAccount<'a> {
25 pub fn new(svm: &'a mut HPSVM, payer: &'a Keypair, mint: &'a Address) -> Self {
27 CreateAssociatedTokenAccount { svm, payer, owner: None, token_program_id: None, mint }
28 }
29
30 pub fn owner(mut self, owner: &'a Address) -> Self {
32 self.owner = Some(*owner);
33 self
34 }
35
36 pub fn token_program_id(mut self, program_id: &'a Address) -> Self {
38 self.token_program_id = Some(program_id);
39 self
40 }
41
42 pub fn send(self) -> Result<Address, FailedTransactionMetadata> {
44 let token_program_id = self.token_program_id.unwrap_or(&TOKEN_ID);
45 let payer_pk = self.payer.pubkey();
46
47 let authority = self.owner.unwrap_or(payer_pk);
48
49 let ix =
50 create_associated_token_account(&payer_pk, &authority, self.mint, token_program_id);
51
52 super::sign_and_send(self.svm, self.payer, &[], ix)?;
53
54 let ata = spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
55 &authority,
56 self.mint,
57 token_program_id,
58 );
59
60 Ok(ata)
61 }
62}