zabi/
selector.rs

1//! Zink ABI utils
2#![cfg(feature = "selector")]
3
4use crate::Abi;
5use tiny_keccak::{Hasher, Keccak};
6
7/// Generate a keccak hash of the input (sha3)
8pub fn keccak256(input: &[u8]) -> [u8; 32] {
9    let mut hasher = Keccak::v256();
10    let mut output = [0; 32];
11    hasher.update(input);
12    hasher.finalize(&mut output);
13    output
14}
15
16/// Parse selector from bytes.
17pub fn parse(bytes: &[u8]) -> [u8; 4] {
18    let mut selector = [0u8; 4];
19    selector.copy_from_slice(&keccak256(bytes)[..4]);
20    selector
21}
22
23impl Abi {
24    /// Get function signature.
25    pub fn signature(&self) -> String {
26        self.name.clone()
27            + "("
28            + &self
29                .inputs
30                .iter()
31                .map(|i| i.ty.as_ref())
32                .collect::<Vec<_>>()
33                .join(",")
34            + ")"
35    }
36
37    /// Get function selector.
38    pub fn selector(&self) -> [u8; 4] {
39        parse(self.signature().as_bytes())
40    }
41}