|
| 1 | +use core::slice::from_raw_parts; |
| 2 | + |
| 3 | +use pinocchio::{ |
| 4 | + account_info::AccountInfo, |
| 5 | + cpi::slice_invoke_signed, |
| 6 | + instruction::{AccountMeta, Instruction, Signer}, |
| 7 | + ProgramResult, |
| 8 | +}; |
| 9 | + |
| 10 | +extern crate alloc; |
| 11 | + |
| 12 | +use alloc::vec::Vec; |
| 13 | + |
| 14 | +use crate::{write_bytes, UNINIT_BYTE}; |
| 15 | + |
| 16 | +/// Initialize a new Multisig. |
| 17 | +/// |
| 18 | +/// ### Accounts: |
| 19 | +/// 0. `[writable]` The multisig account to initialize. |
| 20 | +/// 1. `[]` Rent sysvar |
| 21 | +/// 2. ..`2+N`. `[]` The signer accounts, must equal to N where `1 <= N <= |
| 22 | +/// 11`. |
| 23 | +pub struct InitializeMultisig<'a> { |
| 24 | + /// Multisig Account. |
| 25 | + pub multisig: &'a AccountInfo, |
| 26 | + /// Rent sysvar Account. |
| 27 | + pub rent_sysvar: &'a AccountInfo, |
| 28 | + /// Signer Accounts |
| 29 | + pub multisig_signers: Vec<&'a AccountInfo>, |
| 30 | + /// The number of signers (M) required to validate this multisignature |
| 31 | + /// account. |
| 32 | + pub m: u8, |
| 33 | +} |
| 34 | + |
| 35 | +impl InitializeMultisig<'_> { |
| 36 | + #[inline(always)] |
| 37 | + pub fn invoke(&self) -> ProgramResult { |
| 38 | + self.invoke_signed(&[]) |
| 39 | + } |
| 40 | + |
| 41 | + pub fn invoke_signed(&self, signers: &[Signer]) -> ProgramResult { |
| 42 | + // Account metadata |
| 43 | + let mut account_metas = Vec::with_capacity(2 + self.multisig_signers.len()); |
| 44 | + account_metas.push(AccountMeta::writable(self.multisig.key())); |
| 45 | + account_metas.push(AccountMeta::readonly(self.rent_sysvar.key())); |
| 46 | + account_metas.extend( |
| 47 | + self.multisig_signers |
| 48 | + .iter() |
| 49 | + .map(|a| AccountMeta::readonly(a.key())), |
| 50 | + ); |
| 51 | + |
| 52 | + // Instruction data layout: |
| 53 | + // - [0]: instruction discriminator (1 byte, u8) |
| 54 | + // - [1]: m (1 byte, u8) |
| 55 | + let mut instruction_data = [UNINIT_BYTE; 2]; |
| 56 | + |
| 57 | + // Set discriminator as u8 at offset [0] |
| 58 | + write_bytes(&mut instruction_data, &[2]); |
| 59 | + // Set number of signers (m) at offset 1 |
| 60 | + write_bytes(&mut instruction_data[1..2], &[self.m]); |
| 61 | + |
| 62 | + let instruction = Instruction { |
| 63 | + program_id: &crate::ID, |
| 64 | + accounts: account_metas.as_slice(), |
| 65 | + data: unsafe { from_raw_parts(instruction_data.as_ptr() as _, 2) }, |
| 66 | + }; |
| 67 | + |
| 68 | + let mut account_infos = Vec::with_capacity(2 + self.multisig_signers.len()); |
| 69 | + account_infos.push(self.multisig); |
| 70 | + account_infos.push(self.rent_sysvar); |
| 71 | + account_infos.extend_from_slice(self.multisig_signers.as_slice()); |
| 72 | + |
| 73 | + slice_invoke_signed(&instruction, account_infos.as_slice(), signers) |
| 74 | + } |
| 75 | +} |
0 commit comments