Skip to main content

df_hyperliquid_core/client/evm/abi/
function.rs

1//! Functions and events by their signature: a [`Function`]'s selector, calldata
2//! and answer, and the topic an event is logged under.
3
4use 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/// A function as Solidity or viem writes it: `transfer(address to, uint256
11/// amount) returns (bool)`, with or without `function` and its modifiers.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Function {
14    /// The function name, such as `transfer`.
15    pub name: String,
16    /// The parameters the call takes, in order.
17    pub inputs: Vec<Param>,
18    /// The values it returns, in order; empty when there is no `returns` clause.
19    pub outputs: Vec<Param>,
20}
21
22impl Function {
23    /// Reads a signature such as `function transfer(address to, uint256 amount) returns (bool)`.
24    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    /// `name(t1,t2)`, what the selector hashes.
40    #[must_use]
41    pub fn signature(&self) -> String {
42        format!("{}{}", self.name, tuple_type(&self.inputs))
43    }
44
45    /// The four bytes that name the function: the start of `keccak256(signature)`.
46    #[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    /// The calldata of a call: the selector, then the arguments.
53    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    /// A call's arguments back out of its calldata.
60    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    /// What the call answered, read against its declared outputs.
72    pub fn decode_output(&self, answer: &[u8]) -> Result<Vec<Token>, AbiError> {
73        decode(&self.outputs, answer)
74    }
75}
76
77/// `name`, what is inside its parentheses, and what follows them.
78fn 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
103/// The selector of a function signature in any spelling the docs use.
104pub fn selector(signature: &str) -> Result<[u8; 4], AbiError> {
105    Function::parse(signature).map(|function| function.selector())
106}
107
108/// The first topic an event is logged under: `keccak256(name(t1,t2))`.
109pub 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(&params(inside)?));
113    Ok(B256(keccak256(canonical.as_bytes())))
114}
115
116#[cfg(test)]
117#[path = "tests/function.rs"]
118mod tests;