sol_dev_utils/
lib.rs

1extern crate sha2;
2use std::convert::TryInto;
3
4use sha2::Digest;
5
6/// Calculates the discriminant for a function using SHA-256 hash.
7///
8/// The discriminant is defined as the first 8 bytes of the SHA-256 hash of the function name.
9///
10/// NOTE: Functions require a namespace prefix, e.g. `global:initialize`.
11/// The default namespace is `global`.
12///
13/// # Arguments
14///
15/// * `input` - A string slice that holds the function name.
16///
17/// # Returns
18///
19/// An array of 8 bytes representing the discriminant.
20///
21/// # Examples
22///
23/// ```
24/// let discriminant = sol_dev_utils::anchor_discriminant("global:initialize");
25/// assert_eq!(discriminant, [175, 175, 109, 31, 13, 152, 155, 237]);
26/// ```
27pub fn anchor_discriminant(input: &str) -> [u8; 8] {
28    let mut hasher = sha2::Sha256::new();
29    hasher.update(input);
30    let result = hasher.finalize();
31    result[..8].try_into().unwrap()
32}