|
| 1 | +use core::slice::from_raw_parts; |
| 2 | + |
| 3 | +use pinocchio::{ |
| 4 | + account_info::AccountInfo, |
| 5 | + instruction::{AccountMeta, Instruction, Signer}, |
| 6 | + program::invoke_signed, |
| 7 | + pubkey::Pubkey, |
| 8 | + ProgramResult, |
| 9 | +}; |
| 10 | + |
| 11 | +use crate::{write_bytes, UNINIT_BYTE}; |
| 12 | + |
| 13 | +/// Approves a delegate. |
| 14 | +/// |
| 15 | +/// ### Accounts: |
| 16 | +/// 0. `[WRITE]` The source account. |
| 17 | +/// 1. `[]` The token mint. |
| 18 | +/// 2. `[]` The delegate. |
| 19 | +/// 3. `[SIGNER]` The source account owner. |
| 20 | +pub struct ApproveChecked<'a> { |
| 21 | + /// Source Account. |
| 22 | + pub source: &'a AccountInfo, |
| 23 | + /// Mint Account. |
| 24 | + pub mint: &'a AccountInfo, |
| 25 | + /// Delegate Account. |
| 26 | + pub delegate: &'a AccountInfo, |
| 27 | + /// Source Owner Account. |
| 28 | + pub authority: &'a AccountInfo, |
| 29 | + /// Amount. |
| 30 | + pub amount: u64, |
| 31 | + /// Decimals. |
| 32 | + pub decimals: u8, |
| 33 | + /// Token Program |
| 34 | + pub token_program: &'a Pubkey, |
| 35 | +} |
| 36 | + |
| 37 | +impl ApproveChecked<'_> { |
| 38 | + #[inline(always)] |
| 39 | + pub fn invoke(&self) -> ProgramResult { |
| 40 | + self.invoke_signed(&[]) |
| 41 | + } |
| 42 | + |
| 43 | + pub fn invoke_signed(&self, signers: &[Signer]) -> ProgramResult { |
| 44 | + // Account metadata |
| 45 | + let account_metas: [AccountMeta; 4] = [ |
| 46 | + AccountMeta::writable(self.source.key()), |
| 47 | + AccountMeta::readonly(self.mint.key()), |
| 48 | + AccountMeta::readonly(self.delegate.key()), |
| 49 | + AccountMeta::readonly_signer(self.authority.key()), |
| 50 | + ]; |
| 51 | + |
| 52 | + // Instruction data |
| 53 | + // - [0] : instruction discriminator (1 byte, u8) |
| 54 | + // - [1..9]: amount (8 bytes, u64) |
| 55 | + // - [9] : decimals (1 byte, u8) |
| 56 | + let mut instruction_data = [UNINIT_BYTE; 10]; |
| 57 | + |
| 58 | + // Set discriminator as u8 at offset [0] |
| 59 | + write_bytes(&mut instruction_data, &[13]); |
| 60 | + // Set amount as u64 at offset [1..9] |
| 61 | + write_bytes(&mut instruction_data[1..9], &self.amount.to_le_bytes()); |
| 62 | + // Set decimals as u8 at offset [9] |
| 63 | + write_bytes(&mut instruction_data[9..], &[self.decimals]); |
| 64 | + |
| 65 | + let instruction = Instruction { |
| 66 | + program_id: self.token_program, |
| 67 | + accounts: &account_metas, |
| 68 | + data: unsafe { from_raw_parts(instruction_data.as_ptr() as _, 10) }, |
| 69 | + }; |
| 70 | + |
| 71 | + invoke_signed( |
| 72 | + &instruction, |
| 73 | + &[self.source, self.mint, self.delegate, self.authority], |
| 74 | + signers, |
| 75 | + ) |
| 76 | + } |
| 77 | +} |
0 commit comments