Skip to content

Commit

Permalink
lang: Add Discriminator impl for instructions
Browse files Browse the repository at this point in the history
  • Loading branch information
cyphersnake committed Jun 27, 2022
1 parent 55e0c5d commit 34eff4d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 17 deletions.
8 changes: 6 additions & 2 deletions lang/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,12 @@ pub trait ZeroCopy: Discriminator + Copy + Clone + Zeroable + Pod {}
/// `Sha256(<namespace>::<method_name>)[..8] || BorshSerialize(args)`.
/// `args` is a borsh serialized struct of named fields for each argument given
/// to an instruction.
pub trait InstructionData: AnchorSerialize {
fn data(&self) -> Vec<u8>;
pub trait InstructionData: Discriminator + AnchorSerialize {
fn data(&self) -> Vec<u8> {
let mut d = Self::discriminator().to_vec();
d.append(&mut self.try_to_vec().expect("Should always serialize"));
d
}
}

/// An event that can be emitted via a Solana log. See [`emit!`](crate::prelude::emit) for an example.
Expand Down
27 changes: 12 additions & 15 deletions lang/syn/src/codegen/program/instruction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,12 @@ pub fn generate(program: &Program) -> proc_macro2::TokenStream {
/// constructor.
#strct

impl anchor_lang::InstructionData for New {
fn data(&self) -> Vec<u8> {
let mut d = #sighash_tts.to_vec();
d.append(&mut self.try_to_vec().expect("Should always serialize"));
d
impl anchor_lang::Discriminator for New {
fn discriminator() -> [u8; 8] {
#sighash_tts
}
}
impl anchor_lang::InstructionData for $ix_name_camel {}
}
}
};
Expand Down Expand Up @@ -82,13 +81,12 @@ pub fn generate(program: &Program) -> proc_macro2::TokenStream {
let sighash_tts: proc_macro2::TokenStream =
format!("{:?}", sighash_arr).parse().unwrap();
quote! {
impl anchor_lang::InstructionData for #ix_name_camel {
fn data(&self) -> Vec<u8> {
let mut d = #sighash_tts.to_vec();
d.append(&mut self.try_to_vec().expect("Should always serialize"));
d
impl anchor_lang::Discriminator for #ix_name_camel {
fn discriminator() -> [u8; 8] {
#sighash_tts
}
}
impl anchor_lang::InstructionData for $ix_name_camel {}
}
};

Expand Down Expand Up @@ -138,13 +136,12 @@ pub fn generate(program: &Program) -> proc_macro2::TokenStream {
let sighash_tts: proc_macro2::TokenStream =
format!("{:?}", sighash_arr).parse().unwrap();
quote! {
impl anchor_lang::InstructionData for #ix_name_camel {
fn data(&self) -> Vec<u8> {
let mut d = #sighash_tts.to_vec();
d.append(&mut self.try_to_vec().expect("Should always serialize"));
d
impl anchor_lang::Discriminator for #ix_name_camel {
fn discriminator() -> [u8; 8] {
#sighash_tts
}
}
impl anchor_lang::InstructionData for $ix_name_camel {}
}
};
// If no args, output a "unit" variant instead of a struct variant.
Expand Down

0 comments on commit 34eff4d

Please sign in to comment.