Skip to main content

hpsvm_token/
create_ata.rs

1use hpsvm::{HPSVM, types::FailedTransactionMetadata};
2use solana_address::Address;
3use solana_keypair::Keypair;
4use solana_signer::Signer;
5use solana_transaction::Transaction;
6use spl_associated_token_account_interface::instruction::create_associated_token_account;
7
8use super::TOKEN_ID;
9
10/// ### Description
11/// Builder for the [`create_associated_token_account`] instruction.
12///
13/// ### Optional fields
14/// - `owner`: `payer` by default.
15/// - `token_program_id`: [`TOKEN_ID`] by default.
16#[derive(Debug)]
17pub struct CreateAssociatedTokenAccount<'a> {
18    svm: &'a mut HPSVM,
19    payer: &'a Keypair,
20    mint: &'a Address,
21    token_program_id: Option<&'a Address>,
22    owner: Option<Address>,
23}
24
25impl<'a> CreateAssociatedTokenAccount<'a> {
26    /// Creates a new instance of [`create_associated_token_account`] instruction.
27    pub fn new(svm: &'a mut HPSVM, payer: &'a Keypair, mint: &'a Address) -> Self {
28        CreateAssociatedTokenAccount { svm, payer, owner: None, token_program_id: None, mint }
29    }
30
31    /// Sets the owner of the account with single owner.
32    pub fn owner(mut self, owner: &'a Address) -> Self {
33        self.owner = Some(*owner);
34        self
35    }
36
37    /// Sets the token program id for the instruction.
38    pub fn token_program_id(mut self, program_id: &'a Address) -> Self {
39        self.token_program_id = Some(program_id);
40        self
41    }
42
43    /// Sends the transaction.
44    pub fn send(self) -> Result<Address, FailedTransactionMetadata> {
45        let token_program_id = self.token_program_id.unwrap_or(&TOKEN_ID);
46        let payer_pk = self.payer.pubkey();
47
48        let authority = self.owner.unwrap_or(payer_pk);
49
50        let ix =
51            create_associated_token_account(&payer_pk, &authority, self.mint, token_program_id);
52
53        let block_hash = self.svm.latest_blockhash();
54        let tx =
55            Transaction::new_signed_with_payer(&[ix], Some(&payer_pk), &[self.payer], block_hash);
56
57        self.svm.send_transaction(tx)?;
58
59        let ata = spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
60            &authority,
61            self.mint,
62            token_program_id,
63        );
64
65        Ok(ata)
66    }
67}