use {
crate::{
onchain::{write_bytes, UNINIT_BYTE},
program::ID,
},
core::{mem::MaybeUninit, slice::from_raw_parts},
pinocchio::{
account_info::AccountInfo,
instruction::{AccountMeta, Instruction, Signer},
program::invoke_signed,
ProgramResult,
},
};
pub struct CreateWhitelist<'a> {
pub whitelist_account: &'a AccountInfo,
pub whitelist_authority: &'a AccountInfo,
pub funder: &'a AccountInfo,
pub system_program: &'a AccountInfo,
}
impl<'a> CreateWhitelist<'a> {
#[inline(always)]
pub fn invoke(&self) -> ProgramResult {
self.invoke_signed(&[])
}
fn create_instruction_data() -> [MaybeUninit<u8>; 1] {
let mut instruction_data = [UNINIT_BYTE; 1];
write_bytes(&mut instruction_data, &[0]);
instruction_data
}
pub fn invoke_signed(&self, signers: &[Signer]) -> ProgramResult {
let account_metas: [AccountMeta; 4] = [
AccountMeta::writable(self.whitelist_account.key()),
AccountMeta::readonly_signer(self.whitelist_authority.key()),
AccountMeta::writable_signer(self.funder.key()),
AccountMeta::readonly(self.system_program.key()),
];
let instruction_data = Self::create_instruction_data();
let instruction = Instruction {
program_id: &ID,
accounts: &account_metas,
data: unsafe { from_raw_parts(instruction_data.as_ptr() as _, 1) },
};
invoke_signed(
&instruction,
&[
self.whitelist_account,
self.whitelist_authority,
self.funder,
self.system_program,
],
signers,
)
}
}
pub fn create_whitelist(
whitelist_account: &AccountInfo,
whitelist_authority: &AccountInfo,
funder: &AccountInfo,
system_program: &AccountInfo,
) -> ProgramResult {
let ix = CreateWhitelist {
whitelist_account,
whitelist_authority,
funder,
system_program,
};
ix.invoke()
}
pub fn create_whitelist_with_seed(
whitelist_account: &AccountInfo,
whitelist_authority: &AccountInfo,
funder: &AccountInfo,
system_program: &AccountInfo,
signer_seeds: &[Signer],
) -> ProgramResult {
let ix = CreateWhitelist {
whitelist_account,
whitelist_authority,
funder,
system_program,
};
ix.invoke_signed(signer_seeds)
}
#[cfg(test)]
mod tests {
use {super::*, crate::instructions::ProgramWhitelistInstruction};
#[test]
fn test_instruction_data_creation() {
let instruction_data = CreateWhitelist::create_instruction_data();
let instruction = Instruction {
program_id: &ID,
accounts: &[], data: unsafe { from_raw_parts(instruction_data.as_ptr() as _, 1) },
};
let parsed_ix = ProgramWhitelistInstruction::unpack(instruction.data).unwrap();
match parsed_ix {
ProgramWhitelistInstruction::CreateWhitelist {} => (),
_ => panic!("Parsed incorrect instruction type"),
}
}
}