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 spl_associated_token_account_interface::instruction::create_associated_token_account;
6
7use super::TOKEN_ID;
8
9/// ### Description
10/// Builder for the [`create_associated_token_account`] instruction.
11///
12/// ### Optional fields
13/// - `owner`: `payer` by default.
14/// - `token_program_id`: [`TOKEN_ID`] by default.
15#[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    /// Creates a new instance of [`create_associated_token_account`] instruction.
26    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    /// Sets the owner of the account with single owner.
31    pub fn owner(mut self, owner: &'a Address) -> Self {
32        self.owner = Some(*owner);
33        self
34    }
35
36    /// Sets the token program id for the instruction.
37    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    /// Sends the transaction.
43    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}