Skip to main content

foundry_common/
abi.rs

1//! ABI related helper functions.
2
3use alloy_chains::Chain;
4use alloy_dyn_abi::{DecodedEvent, DynSolType, DynSolValue, FunctionExt, JsonAbiExt, Specifier};
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/// ABI-decodes the non-indexed parameters (the log data) of an event.
112///
113/// Indexed parameters are stored in the log topics rather than in the data, so they are skipped.
114/// This allows decoding the data of a log without knowing its topics.
115pub fn abi_decode_event_data(event: &Event, data: &[u8]) -> Result<Vec<DynSolValue>> {
116    let body = DynSolType::Tuple(
117        event
118            .inputs
119            .iter()
120            .filter(|input| !input.indexed)
121            .map(|input| input.resolve())
122            .collect::<Result<_, _>>()?,
123    );
124    Ok(match body.abi_decode_sequence(data)? {
125        DynSolValue::Tuple(values) => values,
126        _ => unreachable!("body is a tuple"),
127    })
128}
129
130/// Given an error signature string, it tries to parse it as a `Error`
131pub fn get_error(sig: &str) -> Result<Error> {
132    Error::parse(sig).wrap_err("could not parse error signature")
133}
134
135/// Given an event without indexed parameters and a rawlog, it tries to return the event with the
136/// proper indexed parameters. Otherwise, it returns the original event.
137pub fn get_indexed_event(mut event: Event, raw_log: &LogData) -> Event {
138    if !event.anonymous && raw_log.topics().len() > 1 {
139        let indexed_params = raw_log.topics().len() - 1;
140        let num_inputs = event.inputs.len();
141        let num_address_params = event.inputs.iter().filter(|p| p.ty == "address").count();
142
143        event.inputs.iter_mut().enumerate().for_each(|(index, param)| {
144            if param.name.is_empty() {
145                param.name = format!("param{index}");
146            }
147            if num_inputs == indexed_params
148                || (num_address_params == indexed_params && param.ty == "address")
149            {
150                param.indexed = true;
151            }
152        })
153    }
154    event
155}
156
157/// Restore the order of the params of a decoded event,
158/// as Alloy returns the indexed and unindexed params separately.
159pub fn reconstruct_event_params(event: &Event, decoded: &DecodedEvent) -> Vec<DynSolValue> {
160    let mut indexed = 0;
161    let mut unindexed = 0;
162    let mut inputs = vec![];
163    for input in &event.inputs {
164        // Prevent panic of event `Transfer(from, to)` decoded with a signature
165        // `Transfer(address indexed from, address indexed to, uint256 indexed tokenId)` by making
166        // sure the event inputs is not higher than decoded indexed / un-indexed values.
167        if input.indexed && indexed < decoded.indexed.len() {
168            inputs.push(decoded.indexed[indexed].clone());
169            indexed += 1;
170        } else if unindexed < decoded.body.len() {
171            inputs.push(decoded.body[unindexed].clone());
172            unindexed += 1;
173        }
174    }
175
176    inputs
177}
178
179/// Fetches the overloads of `function_name` from the contract's Etherscan ABI. If the address is a
180/// proxy, fetches the ABI of the implementation contract.
181pub async fn get_funcs_etherscan(
182    function_name: &str,
183    contract: Address,
184    chain: Chain,
185    etherscan_api_key: &str,
186    etherscan_api_url: Option<&str>,
187) -> Result<Vec<Function>> {
188    let client = if let Some(api_url) = etherscan_api_url {
189        Client::builder()
190            .with_api_key(etherscan_api_key)
191            .with_api_url(api_url)?
192            .with_url(api_url)?
193            .build()?
194    } else {
195        Client::new(chain, etherscan_api_key)?
196    };
197    let source = find_source(client, contract).await?;
198    let metadata = source.items.first().wrap_err("etherscan returned empty metadata")?;
199
200    let mut abi = metadata.abi()?;
201    Ok(abi.functions.remove(function_name).unwrap_or_default())
202}
203
204/// If the code at `address` is a proxy, recurse until we find the implementation.
205pub fn find_source(
206    client: Client,
207    address: Address,
208) -> Pin<Box<dyn Future<Output = Result<ContractMetadata>>>> {
209    Box::pin(async move {
210        trace!(%address, "find Etherscan source");
211        let source = client.contract_source_code(address).await?;
212        let metadata = source.items.first().wrap_err("Etherscan returned no data")?;
213        // `Proxy: 1` can still come with an empty `Implementation` (unresolved/unverified);
214        // treat that like "not a proxy" instead of panicking on `.unwrap()`.
215        let implementation = if metadata.proxy == 0 { None } else { metadata.implementation };
216        if let Some(implementation) = implementation {
217            sh_println!(
218                "Contract at {address} is a proxy, trying to fetch source at {implementation}..."
219            )?;
220            match find_source(client, implementation).await {
221                impl_source @ Ok(_) => impl_source,
222                Err(e)
223                    if matches!(
224                        e.downcast_ref::<EtherscanError>(),
225                        Some(EtherscanError::ContractCodeNotVerified(address)) if *address == implementation
226                    ) =>
227                {
228                    error!(%e);
229                    Ok(source)
230                }
231                Err(e) => Err(e),
232            }
233        } else {
234            if metadata.proxy != 0 {
235                error!(%address, "Etherscan reports this contract as a proxy but returned no implementation address");
236            }
237            Ok(source)
238        }
239    })
240}
241
242/// Helper function to coerce a value to a [DynSolValue] given a type string
243pub fn coerce_value(ty: &str, arg: &str) -> Result<DynSolValue> {
244    let ty = DynSolType::parse(ty)?;
245    Ok(DynSolType::coerce_str(&ty, arg)?)
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251    use alloy_dyn_abi::EventExt;
252    use alloy_primitives::{B256, U256, address};
253    use foundry_block_explorers::contract::Metadata;
254
255    /// `Proxy: 1` with an empty `Implementation` used to panic on `.unwrap()`
256    /// (real-world shape, see `foundry_block_explorers`' own `can_deserialize_address_opt` test).
257    #[test]
258    fn test_proxy_without_implementation_does_not_panic() {
259        let json = serde_json::json!({
260            "SourceCode": "// dummy",
261            "ABI": "[]",
262            "ContractName": "Dummy",
263            "CompilerVersion": "v0.8.0+commit.c7dfd78e",
264            "OptimizationUsed": "0",
265            "Runs": "200",
266            "ConstructorArguments": "",
267            "EVMVersion": "Default",
268            "Library": "",
269            "LicenseType": "None",
270            "Proxy": "1",
271            "Implementation": "",
272            "SwarmSource": ""
273        });
274
275        let metadata: Metadata =
276            serde_json::from_value(json).expect("realistic Etherscan payload must deserialize");
277
278        // This is exactly the combination that used to reach `.unwrap()` on `None`.
279        assert_eq!(metadata.proxy, 1, "Proxy: 1 must deserialize to a nonzero proxy flag");
280        assert_eq!(
281            metadata.implementation, None,
282            "an empty Implementation string must deserialize to None, not a parsed address"
283        );
284
285        // Must not panic: this is the exact decision `find_source` makes.
286        let implementation = if metadata.proxy == 0 { None } else { metadata.implementation };
287        assert_eq!(implementation, None);
288    }
289
290    #[test]
291    fn proxy_implementation_decision_follows_real_implementation() {
292        let json = serde_json::json!({
293            "SourceCode": "// dummy",
294            "ABI": "[]",
295            "ContractName": "Dummy",
296            "CompilerVersion": "v0.8.0+commit.c7dfd78e",
297            "OptimizationUsed": "0",
298            "Runs": "200",
299            "ConstructorArguments": "",
300            "EVMVersion": "Default",
301            "Library": "",
302            "LicenseType": "None",
303            "Proxy": "1",
304            "Implementation": "0x1F98431c8aD98523631AE4a59f267346ea31F984",
305            "SwarmSource": ""
306        });
307        let metadata: Metadata = serde_json::from_value(json).unwrap();
308
309        let implementation = if metadata.proxy == 0 { None } else { metadata.implementation };
310        assert_eq!(implementation, Some(address!("0x1F98431c8aD98523631AE4a59f267346ea31F984")));
311    }
312
313    #[test]
314    fn test_get_func() {
315        let func = get_func("function foo(uint256 a, uint256 b) returns (uint256)");
316        assert!(func.is_ok());
317        let func = func.unwrap();
318        assert_eq!(func.name, "foo");
319        assert_eq!(func.inputs.len(), 2);
320        assert_eq!(func.inputs[0].ty, "uint256");
321        assert_eq!(func.inputs[1].ty, "uint256");
322
323        // Stripped down function, which [Function] can parse.
324        let func = get_func("foo(bytes4 a, uint8 b)(bytes4)");
325        assert!(func.is_ok());
326        let func = func.unwrap();
327        assert_eq!(func.name, "foo");
328        assert_eq!(func.inputs.len(), 2);
329        assert_eq!(func.inputs[0].ty, "bytes4");
330        assert_eq!(func.inputs[1].ty, "uint8");
331        assert_eq!(func.outputs[0].ty, "bytes4");
332    }
333
334    #[test]
335    fn test_indexed_only_address() {
336        let event = get_event("event Ev(address,uint256,address)").unwrap();
337
338        let param0 = B256::random();
339        let param1 = vec![3; 32];
340        let param2 = B256::random();
341        let log = LogData::new_unchecked(vec![event.selector(), param0, param2], param1.into());
342        let event = get_indexed_event(event, &log);
343
344        assert_eq!(event.inputs.len(), 3);
345
346        // Only the address fields get indexed since total_params > num_indexed_params
347        let parsed = event.decode_log(&log).unwrap();
348
349        assert_eq!(event.inputs.iter().filter(|param| param.indexed).count(), 2);
350        assert_eq!(parsed.indexed[0], DynSolValue::Address(Address::from_word(param0)));
351        assert_eq!(parsed.body[0], DynSolValue::Uint(U256::from_be_bytes([3; 32]), 256));
352        assert_eq!(parsed.indexed[1], DynSolValue::Address(Address::from_word(param2)));
353    }
354
355    #[test]
356    fn test_indexed_all() {
357        let event = get_event("event Ev(address,uint256,address)").unwrap();
358
359        let param0 = B256::random();
360        let param1 = vec![3; 32];
361        let param2 = B256::random();
362        let log = LogData::new_unchecked(
363            vec![event.selector(), param0, B256::from_slice(&param1), param2],
364            vec![].into(),
365        );
366        let event = get_indexed_event(event, &log);
367
368        assert_eq!(event.inputs.len(), 3);
369
370        // All parameters get indexed since num_indexed_params == total_params
371        assert_eq!(event.inputs.iter().filter(|param| param.indexed).count(), 3);
372        let parsed = event.decode_log(&log).unwrap();
373
374        assert_eq!(parsed.indexed[0], DynSolValue::Address(Address::from_word(param0)));
375        assert_eq!(parsed.indexed[1], DynSolValue::Uint(U256::from_be_bytes([3; 32]), 256));
376        assert_eq!(parsed.indexed[2], DynSolValue::Address(Address::from_word(param2)));
377    }
378
379    #[test]
380    fn test_abi_decode_event_data_ignores_indexed() {
381        let event =
382            get_event("event Ev(uint256 indexed a, string b, address indexed c, uint256 d)")
383                .unwrap();
384        let data = DynSolValue::Tuple(vec![
385            DynSolValue::String("hello".into()),
386            DynSolValue::Uint(U256::from(42), 256),
387        ])
388        .abi_encode_params();
389
390        let decoded = abi_decode_event_data(&event, &data).unwrap();
391        assert_eq!(
392            decoded,
393            vec![DynSolValue::String("hello".into()), DynSolValue::Uint(U256::from(42), 256)]
394        );
395    }
396
397    #[test]
398    fn test_abi_decode_event_data_without_indexed() {
399        let event = get_event("event Ev(uint256 a, address b)").unwrap();
400        let addr = Address::random();
401        let data =
402            DynSolValue::Tuple(vec![DynSolValue::Uint(U256::ONE, 256), DynSolValue::Address(addr)])
403                .abi_encode_params();
404
405        let decoded = abi_decode_event_data(&event, &data).unwrap();
406        assert_eq!(decoded, vec![DynSolValue::Uint(U256::ONE, 256), DynSolValue::Address(addr)]);
407    }
408
409    #[test]
410    fn test_encode_args_length_validation() {
411        let params = vec![
412            Param {
413                name: "a".to_string(),
414                ty: "uint256".to_string(),
415                internal_type: None,
416                components: vec![],
417            },
418            Param {
419                name: "b".to_string(),
420                ty: "address".to_string(),
421                internal_type: None,
422                components: vec![],
423            },
424        ];
425
426        // Less arguments than parameters
427        let args = vec!["1"];
428        let res = encode_args(&params, &args);
429        assert!(res.is_err());
430        assert!(format!("{}", res.unwrap_err()).contains("encode length mismatch"));
431
432        // Exact number of arguments and parameters
433        let args = vec!["1", "0x0000000000000000000000000000000000000001"];
434        let res = encode_args(&params, &args);
435        assert!(res.is_ok());
436        let values = res.unwrap();
437        assert_eq!(values.len(), 2);
438
439        // More arguments than parameters
440        let args = vec!["1", "0x0000000000000000000000000000000000000001", "extra"];
441        let res = encode_args(&params, &args);
442        assert!(res.is_err());
443        assert!(format!("{}", res.unwrap_err()).contains("encode length mismatch"));
444    }
445}