common.rs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. use crate::IxArg;
  2. use heck::CamelCase;
  3. use quote::quote;
  4. // Namespace for calculating instruction sighash signatures for any instruction
  5. // not affecting program state.
  6. pub const SIGHASH_GLOBAL_NAMESPACE: &str = "global";
  7. // We don't technically use sighash, because the input arguments aren't given.
  8. // Rust doesn't have method overloading so no need to use the arguments.
  9. // However, we do namespace methods in the preeimage so that we can use
  10. // different traits with the same method name.
  11. pub fn sighash(namespace: &str, name: &str) -> [u8; 8] {
  12. let preimage = format!("{namespace}:{name}");
  13. let mut sighash = [0u8; 8];
  14. sighash.copy_from_slice(&crate::hash::hash(preimage.as_bytes()).to_bytes()[..8]);
  15. sighash
  16. }
  17. pub fn generate_ix_variant(name: String, args: &[IxArg]) -> proc_macro2::TokenStream {
  18. let ix_arg_names: Vec<&syn::Ident> = args.iter().map(|arg| &arg.name).collect();
  19. let ix_name_camel: proc_macro2::TokenStream = {
  20. let n = name.to_camel_case();
  21. n.parse().unwrap()
  22. };
  23. if args.is_empty() {
  24. quote! {
  25. #ix_name_camel
  26. }
  27. } else {
  28. quote! {
  29. #ix_name_camel {
  30. #(#ix_arg_names),*
  31. }
  32. }
  33. }
  34. }