litesvm_token/
mint_to.rs

1use {
2    super::{get_multisig_signers, spl_token::instruction::mint_to, TOKEN_ID},
3    litesvm::{types::FailedTransactionMetadata, LiteSVM},
4    smallvec::{smallvec, SmallVec},
5    solana_keypair::Keypair,
6    solana_pubkey::Pubkey,
7    solana_signer::{signers::Signers, Signer},
8    solana_transaction::Transaction,
9};
10
11/// ### Description
12/// Builder for the [`mint_to`] instruction.
13///
14/// ### Optional fields
15/// - `owner`: payer by default.
16/// - `token_program_id`: [`TOKEN_ID`] by default.
17pub struct MintTo<'a> {
18    svm: &'a mut LiteSVM,
19    payer: &'a Keypair,
20    mint: &'a Pubkey,
21    destination: &'a Pubkey,
22    token_program_id: Option<&'a Pubkey>,
23    owner: Option<Pubkey>,
24    signers: SmallVec<[&'a Keypair; 1]>,
25    amount: u64,
26}
27
28impl<'a> MintTo<'a> {
29    /// Creates a new instance of [`mint_to`] instruction.
30    pub fn new(
31        svm: &'a mut LiteSVM,
32        payer: &'a Keypair,
33        mint: &'a Pubkey,
34        destination: &'a Pubkey,
35        amount: u64,
36    ) -> Self {
37        MintTo {
38            svm,
39            payer,
40            mint,
41            destination,
42            token_program_id: None,
43            signers: smallvec![payer],
44            owner: None,
45            amount,
46        }
47    }
48
49    /// Sets the token program id of the mint account.
50    pub fn token_program_id(mut self, program_id: &'a Pubkey) -> Self {
51        self.token_program_id = Some(program_id);
52        self
53    }
54
55    pub fn owner(mut self, owner: &'a Keypair) -> Self {
56        self.owner = Some(owner.pubkey());
57        self.signers = smallvec![owner];
58        self
59    }
60
61    pub fn multisig(mut self, multisig: &'a Pubkey, signers: &'a [&'a Keypair]) -> Self {
62        self.owner = Some(*multisig);
63        self.signers = SmallVec::from(signers);
64        self
65    }
66
67    /// Sends the transaction.
68    pub fn send(self) -> Result<(), FailedTransactionMetadata> {
69        let payer_pk = self.payer.pubkey();
70        let token_program_id = self.token_program_id.unwrap_or(&TOKEN_ID);
71
72        let authority = self.owner.unwrap_or(payer_pk);
73        let signing_keys = self.signers.pubkeys();
74        let signer_keys = get_multisig_signers(&authority, &signing_keys);
75
76        let ix = mint_to(
77            token_program_id,
78            self.mint,
79            self.destination,
80            &authority,
81            &signer_keys,
82            self.amount,
83        )?;
84
85        let block_hash = self.svm.latest_blockhash();
86        let mut tx = Transaction::new_with_payer(&[ix], Some(&payer_pk));
87        tx.partial_sign(&[self.payer], block_hash);
88        tx.partial_sign(self.signers.as_ref(), block_hash);
89
90        self.svm.send_transaction(tx)?;
91
92        Ok(())
93    }
94}