pinocchio_token/instructions/
initialize_account_2.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.
15///   3. `[]` Rent sysvar
16pub struct InitializeAccount2<'a> {
17    /// New Account.
18    pub account: &'a AccountView,
19    /// Mint Account.
20    pub mint: &'a AccountView,
21    /// Rent Sysvar Account
22    pub rent_sysvar: &'a AccountView,
23    /// Owner of the new Account.
24    pub owner: &'a Address,
25}
26
27impl InitializeAccount2<'_> {
28    #[inline(always)]
29    pub fn invoke(&self) -> ProgramResult {
30        // Instruction accounts
31        let instruction_accounts: [InstructionAccount; 3] = [
32            InstructionAccount::writable(self.account.address()),
33            InstructionAccount::readonly(self.mint.address()),
34            InstructionAccount::readonly(self.rent_sysvar.address()),
35        ];
36
37        // instruction data
38        // -  [0]: instruction discriminator (1 byte, u8)
39        // -  [1..33]: owner (32 bytes, Address)
40        let mut instruction_data = [UNINIT_BYTE; 33];
41
42        // Set discriminator as u8 at offset [0]
43        write_bytes(&mut instruction_data, &[16]);
44        // Set owner as [u8; 32] at offset [1..33]
45        write_bytes(&mut instruction_data[1..], self.owner.as_array());
46
47        let instruction = InstructionView {
48            program_id: &crate::ID,
49            accounts: &instruction_accounts,
50            data: unsafe { from_raw_parts(instruction_data.as_ptr() as _, 33) },
51        };
52
53        invoke(&instruction, &[self.account, self.mint, self.rent_sysvar])
54    }
55}