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) -> Result<Function> {
147    let client = Client::new(chain, etherscan_api_key)?;
148    let source = find_source(client, contract).await?;
149    let metadata = source.items.first().wrap_err("etherscan returned empty metadata")?;
150
151    let mut abi = metadata.abi()?;
152    let funcs = abi.functions.remove(function_name).unwrap_or_default();
153
154    for func in funcs {
155        let res = encode_function_args(&func, args);
156        if res.is_ok() {
157            return Ok(func);
158        }
159    }
160
161    Err(eyre::eyre!("Function not found in abi"))
162}
163
164/// If the code at `address` is a proxy, recurse until we find the implementation.
165pub fn find_source(
166    client: Client,
167    address: Address,
168) -> Pin<Box<dyn Future<Output = Result<ContractMetadata>>>> {
169    Box::pin(async move {
170        trace!(%address, "find Etherscan source");
171        let source = client.contract_source_code(address).await?;
172        let metadata = source.items.first().wrap_err("Etherscan returned no data")?;
173        if metadata.proxy == 0 {
174            Ok(source)
175        } else {
176            let implementation = metadata.implementation.unwrap();
177            sh_println!(
178                "Contract at {address} is a proxy, trying to fetch source at {implementation}..."
179            )?;
180            match find_source(client, implementation).await {
181                impl_source @ Ok(_) => impl_source,
182                Err(e) => {
183                    let err = EtherscanError::ContractCodeNotVerified(address).to_string();
184                    if e.to_string() == err {
185                        error!(%err);
186                        Ok(source)
187                    } else {
188                        Err(e)
189                    }
190                }
191            }
192        }
193    })
194}
195
196/// Helper function to coerce a value to a [DynSolValue] given a type string
197pub fn coerce_value(ty: &str, arg: &str) -> Result<DynSolValue> {
198    let ty = DynSolType::parse(ty)?;
199    Ok(DynSolType::coerce_str(&ty, arg)?)
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205    use alloy_dyn_abi::EventExt;
206    use alloy_primitives::{B256, U256};
207
208    #[test]
209    fn test_get_func() {
210        let func = get_func("function foo(uint256 a, uint256 b) returns (uint256)");
211        assert!(func.is_ok());
212        let func = func.unwrap();
213        assert_eq!(func.name, "foo");
214        assert_eq!(func.inputs.len(), 2);
215        assert_eq!(func.inputs[0].ty, "uint256");
216        assert_eq!(func.inputs[1].ty, "uint256");
217
218        // Stripped down function, which [Function] can parse.
219        let func = get_func("foo(bytes4 a, uint8 b)(bytes4)");
220        assert!(func.is_ok());
221        let func = func.unwrap();
222        assert_eq!(func.name, "foo");
223        assert_eq!(func.inputs.len(), 2);
224        assert_eq!(func.inputs[0].ty, "bytes4");
225        assert_eq!(func.inputs[1].ty, "uint8");
226        assert_eq!(func.outputs[0].ty, "bytes4");
227    }
228
229    #[test]
230    fn test_indexed_only_address() {
231        let event = get_event("event Ev(address,uint256,address)").unwrap();
232
233        let param0 = B256::random();
234        let param1 = vec![3; 32];
235        let param2 = B256::random();
236        let log = LogData::new_unchecked(vec![event.selector(), param0, param2], param1.into());
237        let event = get_indexed_event(event, &log);
238
239        assert_eq!(event.inputs.len(), 3);
240
241        // Only the address fields get indexed since total_params > num_indexed_params
242        let parsed = event.decode_log(&log).unwrap();
243
244        assert_eq!(event.inputs.iter().filter(|param| param.indexed).count(), 2);
245        assert_eq!(parsed.indexed[0], DynSolValue::Address(Address::from_word(param0)));
246        assert_eq!(parsed.body[0], DynSolValue::Uint(U256::from_be_bytes([3; 32]), 256));
247        assert_eq!(parsed.indexed[1], DynSolValue::Address(Address::from_word(param2)));
248    }
249
250    #[test]
251    fn test_indexed_all() {
252        let event = get_event("event Ev(address,uint256,address)").unwrap();
253
254        let param0 = B256::random();
255        let param1 = vec![3; 32];
256        let param2 = B256::random();
257        let log = LogData::new_unchecked(
258            vec![event.selector(), param0, B256::from_slice(&param1), param2],
259            vec![].into(),
260        );
261        let event = get_indexed_event(event, &log);
262
263        assert_eq!(event.inputs.len(), 3);
264
265        // All parameters get indexed since num_indexed_params == total_params
266        assert_eq!(event.inputs.iter().filter(|param| param.indexed).count(), 3);
267        let parsed = event.decode_log(&log).unwrap();
268
269        assert_eq!(parsed.indexed[0], DynSolValue::Address(Address::from_word(param0)));
270        assert_eq!(parsed.indexed[1], DynSolValue::Uint(U256::from_be_bytes([3; 32]), 256));
271        assert_eq!(parsed.indexed[2], DynSolValue::Address(Address::from_word(param2)));
272    }
273
274    #[test]
275    fn test_encode_args_length_validation() {
276        use alloy_json_abi::Param;
277
278        let params = vec![
279            Param {
280                name: "a".to_string(),
281                ty: "uint256".to_string(),
282                internal_type: None,
283                components: vec![],
284            },
285            Param {
286                name: "b".to_string(),
287                ty: "address".to_string(),
288                internal_type: None,
289                components: vec![],
290            },
291        ];
292
293        // Less arguments than parameters
294        let args = vec!["1"];
295        let res = encode_args(&params, &args);
296        assert!(res.is_err());
297        assert!(format!("{}", res.unwrap_err()).contains("encode length mismatch"));
298
299        // Exact number of arguments and parameters
300        let args = vec!["1", "0x0000000000000000000000000000000000000001"];
301        let res = encode_args(&params, &args);
302        assert!(res.is_ok());
303        let values = res.unwrap();
304        assert_eq!(values.len(), 2);
305
306        // More arguments than parameters
307        let args = vec!["1", "0x0000000000000000000000000000000000000001", "extra"];
308        let res = encode_args(&params, &args);
309        assert!(res.is_err());
310        assert!(format!("{}", res.unwrap_err()).contains("encode length mismatch"));
311    }
312}