1

I have on-chain code to calculate instruction discriminator as :

use anchor_syn::codegen::program::common::{sighash, SIGHASH_GLOBAL_NAMESPACE};
// use anchor_syn::hash::hash;  // module `hash` is private

pub type Discriminator = [u8; 8];

/// Calculates the discriminator for an instruction based on its name,
/// which would be found in an IDL.
pub fn ix_discriminator(name: &str) -> Discriminator {
    sighash(SIGHASH_GLOBAL_NAMESPACE, &name)
}

but it won't pass build, as show bellow:

(anchor) ❱❱❱ anchor build
   Compiling anchor-syn v0.28.0
error[E0599]: no function or associated item named `new_from_array` found for struct `Hash` in the current scope
   --> src/hash.rs:110:15
    |
12  | pub struct Hash(pub [u8; HASH_BYTES]);
    | --------------- function or associated item `new_from_array` not found for this struct
...
110 |         Hash::new_from_array(hash_result)
    |               ^^^^^^^^^^^^^^ function or associated item not found in `Hash`

For more information about this error, try `rustc --explain E0599`.
error: could not compile `anchor-syn` due to previous error

Can anyone show me where I have done wrong? I think it should be very simple, but block me for days.

Thanks.

1 Answer 1

3
/// The function discrminator is constructed from these 8 bytes. Typically, the namespace is
/// "global" or "state"
pub fn get_function_hash(namespace: &str, name: &str) -> [u8; 8] {
    let preimage = format!("{}:{}", namespace, name);
    let mut sighash = [0u8; 8];
    sighash.copy_from_slice(
        &anchor_lang::solana_program::hash::hash(preimage.as_bytes()).to_bytes()[..8],
    );
    sighash
}
1
  • It work. Thanks bro. Commented Mar 24 at 0:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.