Skip to main content

foundry_common/
abi.rs

1//! ABI related helper functions.
2
3use alloy_chains::Chain;
4use alloy_dyn_abi::{DynSolType, DynSolValue, FunctionExt, JsonAbiExt};
5use alloy_json_abi::{Error, Event, Function, Param};
6use alloy_primitives::{Address, LogData, hex};
7use eyre::{Context, ContextCompat, Result};
8use foundry_block_explorers::{Client, contract::ContractMetadata, errors::EtherscanError};
9use std::pin::Pin;
10
11pub fn encode_args<I, S>(inputs: &[Param], args: I) -> Result<Vec<DynSolValue>>
12where
13    I: IntoIterator<Item = S>,
14    S: AsRef<str>,
15{
16    let args: Vec<S> = args.into_iter().collect();
17
18    if inputs.len() != args.len() {
19        eyre::bail!("encode length mismatch: expected {} types, got {}", inputs.len(), args.len())
20    }
21
22    std::iter::zip(inputs, args)
23        .map(|(input, arg)| coerce_value(&input.selector_type(), arg.as_ref()))
24        .collect()
25}
26
27/// Given a function and a vector of string arguments, it proceeds to convert the args to alloy
28/// [DynSolValue]s and then ABI encode them, prefixes the encoded data with the function selector.
29pub fn encode_function_args<I, S>(func: &Function, args: I) -> Result<Vec<u8>>
30where
31    I: IntoIterator<Item = S>,
32    S: AsRef<str>,
33{
34    Ok(func.abi_encode_input(&encode_args(&func.inputs, args)?)?)
35}
36
37/// Given a function and a vector of string arguments, it proceeds to convert the args to alloy
38/// [DynSolValue]s and then ABI encode them. Doesn't prefix the function selector.
39pub fn encode_function_args_raw<I, S>(func: &Function, args: I) -> Result<Vec<u8>>
40where
41    I: IntoIterator<Item = S>,
42    S: AsRef<str>,
43{
44    Ok(func.abi_encode_input_raw(&encode_args(&func.inputs, args)?)?)
45}
46
47/// Given a function and a vector of string arguments, it proceeds to convert the args to alloy
48/// [DynSolValue]s and encode them using the packed encoding.
49pub fn encode_function_args_packed<I, S>(func: &Function, args: I) -> Result<Vec<u8>>
50where
51    I: IntoIterator<Item = S>,
52    S: AsRef<str>,
53{
54    let args: Vec<S> = args.into_iter().collect();
55
56    if func.inputs.len() != args.len() {
57        eyre::bail!(
58            "encode length mismatch: expected {} types, got {}",
59            func.inputs.len(),
60            args.len(),
61        );
62    }
63
64    let params: Vec<Vec<u8>> = std::iter::zip(&func.inputs, args)
65        .map(|(input, arg)| coerce_value(&input.selector_type(), arg.as_ref()))
66        .collect::<Result<Vec<_>>>()?
67        .into_iter()
68        .map(|v| v.abi_encode_packed())
69        .collect();
70
71    Ok(params.concat())
72}
73
74/// Decodes the calldata of the function
75pub fn abi_decode_calldata(
76    sig: &str,
77    calldata: &str,
78    input: bool,
79    fn_selector: bool,
80) -> Result<Vec<DynSolValue>> {
81    let func = get_func(sig)?;
82    let calldata = hex::decode(calldata)?;
83
84    let mut calldata = calldata.as_slice();
85    // If function selector is prefixed in "calldata", remove it (first 4 bytes)
86    if input && fn_selector && calldata.len() >= 4 {
87        calldata = &calldata[4..];
88    }
89
90    let res =
91        if input { func.abi_decode_input(calldata) } else { func.abi_decode_output(calldata) }?;
92
93    // in case the decoding worked but nothing was decoded
94    if res.is_empty() {
95        eyre::bail!("no data was decoded")
96    }
97
98    Ok(res)
99}
100
101/// Given a function signature string, it tries to parse it as a `Function`
102pub fn get_func(sig: &str) -> Result<Function> {
103    Function::parse(sig).wrap_err("could not parse function signature")
104}
105
106/// Given an event signature string, it tries to parse it as a `Event`
107pub fn get_event(sig: &str) -> Result<Event> {
108    Event::parse(sig).wrap_err("could not parse event signature")
109}
110
111/// Given an error signature string, it tries to parse it as a `Error`
112pub fn get_error(sig: &str) -> Result<Error> {
113    Error::parse(sig).wrap_err("could not parse error signature")
114}
115
116/// Given an event without indexed parameters and a rawlog, it tries to return the event with the
117/// proper indexed parameters. Otherwise, it returns the original event.
118pub fn get_indexed_event(mut event: Event, raw_log: &LogData) -> Event {
119    if !event.anonymous && raw_log.topics().len() > 1 {
120        let indexed_params = raw_log.topics().len() - 1;
121        let num_inputs = event.inputs.len();
122        let num_address_params = event.inputs.iter().filter(|p| p.ty == "address").count();
123
124        event.inputs.iter_mut().enumerate().for_each(|(index, param)| {
125            if param.name.is_empty() {
126                param.name = format!("param{index}");
127            }
128            if num_inputs == indexed_params
129                || (num_address_params == indexed_params && param.ty == "address")
130            {
131                param.indexed = true;
132            }
133        })
134    }
135    event
136}
137
138/// Given a function name, address, and args, tries to parse it as a `Function` by fetching the
139/// abi from etherscan. If the address is a proxy, fetches the ABI of the implementation contract.
140pub async fn get_func_etherscan(
141    function_name: &str,
142    contract: Address,
143    args: &[String],
144    chain: Chain,
145    etherscan_api_key: &str,
146    etherscan_api_url: Option<&str>,
147) -> Result<Function> {
148    let client = if let Some(api_url) = etherscan_api_url {
149        Client::builder().with_api_key(etherscan_api_key).with_api_url(api_url)?.build()?
150    } else {
151        Client::new(chain, etherscan_api_key)?
152    };
153    let source = find_source(client, contract).await?;
154    let metadata = source.items.first().wrap_err("etherscan returned empty metadata")?;
155
156    let mut abi = metadata.abi()?;
157    let funcs = abi.functions.remove(function_name).unwrap_or_default();
158
159    for func in funcs {
160        let res = encode_function_args(&func, args);
161        if res.is_ok() {
162            return Ok(func);
163        }
164    }
165
166    Err(eyre::eyre!("Function not found in abi"))
167}
168
169/// If the code at `address` is a proxy, recurse until we find the implementation.
170pub fn find_source(
171    client: Client,
172    address: Address,
173) -> Pin<Box<dyn Future<Output = Result<ContractMetadata>>>> {
174    Box::pin(async move {
175        trace!(%address, "find Etherscan source");
176        let source = client.contract_source_code(address).await?;
177        let metadata = source.items.first().wrap_err("Etherscan returned no data")?;
178        if metadata.proxy == 0 {
179            Ok(source)
180        } else {
181            let implementation = metadata.implementation.unwrap();
182            sh_println!(
183                "Contract at {address} is a proxy, trying to fetch source at {implementation}..."
184            )?;
185            match find_source(client, implementation).await {
186                impl_source @ Ok(_) => impl_source,
187                Err(e) => {
188                    let err = EtherscanError::ContractCodeNotVerified(address).to_string();
189                    if e.to_string() == err {
190                        error!(%err);
191                        Ok(source)
192                    } else {
193                        Err(e)
194                    }
195                }
196            }
197        }
198    })
199}
200
201/// Helper function to coerce a value to a [DynSolValue] given a type string
202pub fn coerce_value(ty: &str, arg: &str) -> Result<DynSolValue> {
203    let ty = DynSolType::parse(ty)?;
204    Ok(DynSolType::coerce_str(&ty, arg)?)
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use alloy_dyn_abi::EventExt;
211    use alloy_primitives::{B256, U256};
212
213    #[test]
214    fn test_get_func() {
215        let func = get_func("function foo(uint256 a, uint256 b) returns (uint256)");
216        assert!(func.is_ok());
217        let func = func.unwrap();
218        assert_eq!(func.name, "foo");
219        assert_eq!(func.inputs.len(), 2);
220        assert_eq!(func.inputs[0].ty, "uint256");
221        assert_eq!(func.inputs[1].ty, "uint256");
222
223        // Stripped down function, which [Function] can parse.
224        let func = get_func("foo(bytes4 a, uint8 b)(bytes4)");
225        assert!(func.is_ok());
226        let func = func.unwrap();
227        assert_eq!(func.name, "foo");
228        assert_eq!(func.inputs.len(), 2);
229        assert_eq!(func.inputs[0].ty, "bytes4");
230        assert_eq!(func.inputs[1].ty, "uint8");
231        assert_eq!(func.outputs[0].ty, "bytes4");
232    }
233
234    #[test]
235    fn test_indexed_only_address() {
236        let event = get_event("event Ev(address,uint256,address)").unwrap();
237
238        let param0 = B256::random();
239        let param1 = vec![3; 32];
240        let param2 = B256::random();
241        let log = LogData::new_unchecked(vec![event.selector(), param0, param2], param1.into());
242        let event = get_indexed_event(event, &log);
243
244        assert_eq!(event.inputs.len(), 3);
245
246        // Only the address fields get indexed since total_params > num_indexed_params
247        let parsed = event.decode_log(&log).unwrap();
248
249        assert_eq!(event.inputs.iter().filter(|param| param.indexed).count(), 2);
250        assert_eq!(parsed.indexed[0], DynSolValue::Address(Address::from_word(param0)));
251        assert_eq!(parsed.body[0], DynSolValue::Uint(U256::from_be_bytes([3; 32]), 256));
252        assert_eq!(parsed.indexed[1], DynSolValue::Address(Address::from_word(param2)));
253    }
254
255    #[test]
256    fn test_indexed_all() {
257        let event = get_event("event Ev(address,uint256,address)").unwrap();
258
259        let param0 = B256::random();
260        let param1 = vec![3; 32];
261        let param2 = B256::random();
262        let log = LogData::new_unchecked(
263            vec![event.selector(), param0, B256::from_slice(&param1), param2],
264            vec![].into(),
265        );
266        let event = get_indexed_event(event, &log);
267
268        assert_eq!(event.inputs.len(), 3);
269
270        // All parameters get indexed since num_indexed_params == total_params
271        assert_eq!(event.inputs.iter().filter(|param| param.indexed).count(), 3);
272        let parsed = event.decode_log(&log).unwrap();
273
274        assert_eq!(parsed.indexed[0], DynSolValue::Address(Address::from_word(param0)));
275        assert_eq!(parsed.indexed[1], DynSolValue::Uint(U256::from_be_bytes([3; 32]), 256));
276        assert_eq!(parsed.indexed[2], DynSolValue::Address(Address::from_word(param2)));
277    }
278
279    #[test]
280    fn test_encode_args_length_validation() {
281        use alloy_json_abi::Param;
282
283        let params = vec![
284            Param {
285                name: "a".to_string(),
286                ty: "uint256".to_string(),
287                internal_type: None,
288                components: vec![],
289            },
290            Param {
291                name: "b".to_string(),
292                ty: "address".to_string(),
293                internal_type: None,
294                components: vec![],
295            },
296        ];
297
298        // Less arguments than parameters
299        let args = vec!["1"];
300        let res = encode_args(&params, &args);
301        assert!(res.is_err());
302        assert!(format!("{}", res.unwrap_err()).contains("encode length mismatch"));
303
304        // Exact number of arguments and parameters
305        let args = vec!["1", "0x0000000000000000000000000000000000000001"];
306        let res = encode_args(&params, &args);
307        assert!(res.is_ok());
308        let values = res.unwrap();
309        assert_eq!(values.len(), 2);
310
311        // More arguments than parameters
312        let args = vec!["1", "0x0000000000000000000000000000000000000001", "extra"];
313        let res = encode_args(&params, &args);
314        assert!(res.is_err());
315        assert!(format!("{}", res.unwrap_err()).contains("encode length mismatch"));
316    }
317}