initialize_account_2.rs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. use core::slice::from_raw_parts;
  2. use pinocchio::{
  3. account_info::AccountInfo,
  4. instruction::{AccountMeta, Instruction, Signer},
  5. program::invoke_signed,
  6. pubkey::Pubkey,
  7. ProgramResult,
  8. };
  9. use crate::{write_bytes, UNINIT_BYTE};
  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
  16. pub struct InitializeAccount2<'a> {
  17. /// New Account.
  18. pub account: &'a AccountInfo,
  19. /// Mint Account.
  20. pub mint: &'a AccountInfo,
  21. /// Rent Sysvar Account
  22. pub rent_sysvar: &'a AccountInfo,
  23. /// Owner of the new Account.
  24. pub owner: &'a Pubkey,
  25. }
  26. impl InitializeAccount2<'_> {
  27. #[inline(always)]
  28. pub fn invoke(&self) -> ProgramResult {
  29. self.invoke_signed(&[])
  30. }
  31. #[inline(always)]
  32. pub fn invoke_signed(&self, signers: &[Signer]) -> ProgramResult {
  33. // account metadata
  34. let account_metas: [AccountMeta; 3] = [
  35. AccountMeta::writable(self.account.key()),
  36. AccountMeta::readonly(self.mint.key()),
  37. AccountMeta::readonly(self.rent_sysvar.key()),
  38. ];
  39. // instruction data
  40. // - [0]: instruction discriminator (1 byte, u8)
  41. // - [1..33]: owner (32 bytes, Pubkey)
  42. let mut instruction_data = [UNINIT_BYTE; 33];
  43. // Set discriminator as u8 at offset [0]
  44. write_bytes(&mut instruction_data, &[16]);
  45. // Set owner as [u8; 32] at offset [1..33]
  46. write_bytes(&mut instruction_data[1..], self.owner);
  47. let instruction = Instruction {
  48. program_id: &crate::ID,
  49. accounts: &account_metas,
  50. data: unsafe { from_raw_parts(instruction_data.as_ptr() as _, 33) },
  51. };
  52. invoke_signed(
  53. &instruction,
  54. &[self.account, self.mint, self.rent_sysvar],
  55. signers,
  56. )
  57. }
  58. }