pinocchio_token/instructions/
mint_to.rs

1use core::slice::from_raw_parts;
2
3use solana_account_view::AccountView;
4use solana_instruction_view::{
5    cpi::{invoke_signed, Signer},
6    InstructionAccount, InstructionView,
7};
8use solana_program_error::ProgramResult;
9
10use crate::{write_bytes, UNINIT_BYTE};
11
12/// Mints new tokens to an account.
13///
14/// ### Accounts:
15///   0. `[WRITE]` The mint.
16///   1. `[WRITE]` The account to mint tokens to.
17///   2. `[SIGNER]` The mint's minting authority.
18pub struct MintTo<'a> {
19    /// Mint Account.
20    pub mint: &'a AccountView,
21    /// Token Account.
22    pub account: &'a AccountView,
23    /// Mint Authority
24    pub mint_authority: &'a AccountView,
25    /// Amount
26    pub amount: u64,
27}
28
29impl MintTo<'_> {
30    #[inline(always)]
31    pub fn invoke(&self) -> ProgramResult {
32        self.invoke_signed(&[])
33    }
34
35    #[inline(always)]
36    pub fn invoke_signed(&self, signers: &[Signer]) -> ProgramResult {
37        // Instruction accounts
38        let instruction_accounts: [InstructionAccount; 3] = [
39            InstructionAccount::writable(self.mint.address()),
40            InstructionAccount::writable(self.account.address()),
41            InstructionAccount::readonly_signer(self.mint_authority.address()),
42        ];
43
44        // Instruction data layout:
45        // -  [0]: instruction discriminator (1 byte, u8)
46        // -  [1..9]: amount (8 bytes, u64)
47        let mut instruction_data = [UNINIT_BYTE; 9];
48
49        // Set discriminator as u8 at offset [0]
50        write_bytes(&mut instruction_data, &[7]);
51        // Set amount as u64 at offset [1..9]
52        write_bytes(&mut instruction_data[1..9], &self.amount.to_le_bytes());
53
54        let instruction = InstructionView {
55            program_id: &crate::ID,
56            accounts: &instruction_accounts,
57            data: unsafe { from_raw_parts(instruction_data.as_ptr() as _, 9) },
58        };
59
60        invoke_signed(
61            &instruction,
62            &[self.mint, self.account, self.mint_authority],
63            signers,
64        )
65    }
66}