poseidon_client/transactions/
instruction.rs

1use crate::{AccountMeta, BorrowedBase58PublicKey, PoseidonResult, PublicKey, Utilities};
2use borsh::{BorshDeserialize, BorshSerialize};
3use core::fmt;
4use itertools::Itertools;
5use serde::Serialize;
6
7#[derive(PartialEq, Clone, BorshSerialize, BorshDeserialize, Serialize)]
8pub struct Instruction {
9    /// Pubkey of the program that executes this instruction.
10    pub program_id: PublicKey,
11    /// Metadata describing accounts that should be passed to the program.
12    pub accounts: Vec<AccountMeta>,
13    /// Opaque data passed to the program for its own interpretation.
14    pub data: Vec<u8>,
15}
16
17impl Default for Instruction {
18    fn default() -> Self {
19        Instruction::new()
20    }
21}
22
23impl Instruction {
24    pub fn new() -> Self {
25        Self {
26            program_id: [0_u8; 32],
27            accounts: Vec::default(),
28            data: Vec::default(),
29        }
30    }
31
32    pub fn add_program_id(&mut self, program_id: PublicKey) -> &mut Self {
33        self.program_id = program_id;
34
35        self
36    }
37
38    pub fn add_base58_program_id(
39        &mut self,
40        program_id: BorrowedBase58PublicKey,
41    ) -> PoseidonResult<&mut Self> {
42        let program_id = Utilities::base58_to_u32_array(&program_id)?;
43
44        self.program_id = program_id;
45
46        Ok(self)
47    }
48
49    pub fn add_account(&mut self, account_meta: AccountMeta) -> &mut Self {
50        self.accounts.push(account_meta);
51
52        self
53    }
54
55    pub fn add_data(&mut self, instruction_data: &[u8]) -> &mut Self {
56        self.data = instruction_data.to_owned();
57
58        self
59    }
60
61    pub fn build(&mut self) -> &mut Self {
62        let unique_accounts = self.accounts.clone().into_iter().unique().collect_vec();
63
64        self.accounts = unique_accounts;
65
66        self
67    }
68
69    pub fn borrow(&self) -> &Self {
70        self
71    }
72
73    pub fn take(self) -> Self {
74        self
75    }
76}
77
78impl fmt::Debug for Instruction {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        f.debug_struct("Instruction")
81            .field("program_id", &bs58::encode(&self.program_id).into_string())
82            .field("accounts", &self.accounts)
83            .field("data", &hex::encode(&self.data))
84            .finish()
85    }
86}