-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathapprove.rs
67 lines (58 loc) · 1.83 KB
/
approve.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use core::slice::from_raw_parts;
use {
pinocchio::{
account_info::AccountInfo,
instruction::{AccountMeta, Instruction, Signer},
ProgramResult,
},
pinocchio_cpi::invoke_signed,
};
use crate::{write_bytes, UNINIT_BYTE};
/// Approves a delegate.
///
/// ### Accounts:
/// 0. `[WRITE]` The token account.
/// 1. `[]` The delegate.
/// 2. `[SIGNER]` The source account owner.
pub struct Approve<'a> {
/// Source Account.
pub source: &'a AccountInfo,
/// Delegate Account
pub delegate: &'a AccountInfo,
/// Source Owner Account
pub authority: &'a AccountInfo,
/// Amount
pub amount: u64,
}
impl Approve<'_> {
#[inline(always)]
pub fn invoke(&self) -> ProgramResult {
self.invoke_signed(&[])
}
pub fn invoke_signed(&self, signers: &[Signer]) -> ProgramResult {
// Account metadata
let account_metas: [AccountMeta; 3] = [
AccountMeta::writable(self.source.key()),
AccountMeta::readonly(self.delegate.key()),
AccountMeta::readonly_signer(self.authority.key()),
];
// Instruction data
// - [0]: instruction discriminator (1 byte, u8)
// - [1..9]: amount (8 bytes, u64)
let mut instruction_data = [UNINIT_BYTE; 9];
// Set discriminator as u8 at offset [0]
write_bytes(&mut instruction_data, &[4]);
// Set amount as u64 at offset [1..9]
write_bytes(&mut instruction_data[1..], &self.amount.to_le_bytes());
let instruction = Instruction {
program_id: &crate::ID,
accounts: &account_metas,
data: unsafe { from_raw_parts(instruction_data.as_ptr() as _, 9) },
};
invoke_signed(
&instruction,
&[self.source, self.delegate, self.authority],
signers,
)
}
}