pinocchio_token/instructions/
initialize_account_3.rs

1use core::slice::from_raw_parts;
2
3use solana_account_view::AccountView;
4use solana_address::Address;
5use solana_instruction_view::{cpi::invoke, InstructionAccount, InstructionView};
6use solana_program_error::ProgramResult;
7
8use crate::{write_bytes, UNINIT_BYTE};
9
10/// Initialize a new Token Account.
11///
12/// ### Accounts:
13///   0. `[WRITE]`  The account to initialize.
14///   1. `[]` The mint this account will be associated with.
15pub struct InitializeAccount3<'a> {
16    /// New Account.
17    pub account: &'a AccountView,
18    /// Mint Account.
19    pub mint: &'a AccountView,
20    /// Owner of the new Account.
21    pub owner: &'a Address,
22}
23
24impl InitializeAccount3<'_> {
25    #[inline(always)]
26    pub fn invoke(&self) -> ProgramResult {
27        // Instruction accounts
28        let instruction_accounts: [InstructionAccount; 2] = [
29            InstructionAccount::writable(self.account.address()),
30            InstructionAccount::readonly(self.mint.address()),
31        ];
32
33        // instruction data
34        // -  [0]: instruction discriminator (1 byte, u8)
35        // -  [1..33]: owner (32 bytes, Address)
36        let mut instruction_data = [UNINIT_BYTE; 33];
37
38        // Set discriminator as u8 at offset [0]
39        write_bytes(&mut instruction_data, &[18]);
40        // Set owner as [u8; 32] at offset [1..33]
41        write_bytes(&mut instruction_data[1..], self.owner.as_array());
42
43        let instruction = InstructionView {
44            program_id: &crate::ID,
45            accounts: &instruction_accounts,
46            data: unsafe { from_raw_parts(instruction_data.as_ptr() as _, 33) },
47        };
48
49        invoke(&instruction, &[self.account, self.mint])
50    }
51}