df_hyperliquid_core/client/evm/abi/
function.rs1use crate::client::evm::abi::kind::is_name;
5use crate::client::evm::abi::{AbiError, Param, Token, decode, encode, params, tuple_type};
6use crate::client::evm::u256::B256;
7use crate::utils::hex;
8use crate::utils::sign::keccak256;
9
10#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Function {
14 pub name: String,
16 pub inputs: Vec<Param>,
18 pub outputs: Vec<Param>,
20}
21
22impl Function {
23 pub fn parse(text: &str) -> Result<Function, AbiError> {
25 let bad = || AbiError::Signature(text.trim().to_owned());
26 let (name, inside, rest) = signature_parts(text, "function").ok_or_else(bad)?;
27 let inputs = params(inside)?;
28 let outputs = match rest.find("returns") {
29 Some(at) => {
30 let after = rest[at + "returns".len()..].trim();
31 let inner = after.strip_prefix('(').and_then(|after| after.strip_suffix(')')).ok_or_else(bad)?;
32 params(inner)?
33 }
34 None => Vec::new(),
35 };
36 Ok(Function { name: name.to_owned(), inputs, outputs })
37 }
38
39 #[must_use]
41 pub fn signature(&self) -> String {
42 format!("{}{}", self.name, tuple_type(&self.inputs))
43 }
44
45 #[must_use]
47 pub fn selector(&self) -> [u8; 4] {
48 let hash = keccak256(self.signature().as_bytes());
49 [hash[0], hash[1], hash[2], hash[3]]
50 }
51
52 pub fn encode(&self, args: &[Token]) -> Result<Vec<u8>, AbiError> {
54 let mut out = self.selector().to_vec();
55 out.extend(encode(&self.inputs, args)?);
56 Ok(out)
57 }
58
59 pub fn decode_input(&self, calldata: &[u8]) -> Result<Vec<Token>, AbiError> {
61 let found = calldata.get(..4).ok_or(AbiError::Short(calldata.len()))?;
62 if found != self.selector() {
63 return Err(AbiError::Selector {
64 wants: hex::encode_prefixed(&self.selector()),
65 found: hex::encode_prefixed(found),
66 });
67 }
68 decode(&self.inputs, &calldata[4..])
69 }
70
71 pub fn decode_output(&self, answer: &[u8]) -> Result<Vec<Token>, AbiError> {
73 decode(&self.outputs, answer)
74 }
75}
76
77fn signature_parts<'a>(text: &'a str, keyword: &str) -> Option<(&'a str, &'a str, &'a str)> {
79 let text = text.trim();
80 let text = text.strip_prefix(keyword).filter(|rest| rest.starts_with(char::is_whitespace)).unwrap_or(text).trim();
81 let open = text.find('(')?;
82 let name = text[..open].trim();
83 if name.is_empty() || !is_name(name) {
84 return None;
85 }
86 let mut depth = 0i32;
87 for (at, letter) in text[open..].char_indices() {
88 match letter {
89 '(' => depth += 1,
90 ')' => {
91 depth -= 1;
92 if depth == 0 {
93 let close = open + at;
94 return Some((name, &text[open + 1..close], &text[close + 1..]));
95 }
96 }
97 _ => {}
98 }
99 }
100 None
101}
102
103pub fn selector(signature: &str) -> Result<[u8; 4], AbiError> {
105 Function::parse(signature).map(|function| function.selector())
106}
107
108pub fn event_topic(signature: &str) -> Result<B256, AbiError> {
110 let (name, inside, _) =
111 signature_parts(signature, "event").ok_or_else(|| AbiError::Signature(signature.trim().to_owned()))?;
112 let canonical = format!("{name}{}", tuple_type(¶ms(inside)?));
113 Ok(B256(keccak256(canonical.as_bytes())))
114}
115
116#[cfg(test)]
117#[path = "tests/function.rs"]
118mod tests;