Skip to main content

foundry_cli/utils/
abi.rs

1use alloy_chains::Chain;
2use alloy_ens::NameOrAddress;
3use alloy_json_abi::Function;
4use alloy_primitives::{Address, hex};
5use alloy_provider::{Network, Provider};
6use eyre::{OptionExt, Result};
7use foundry_common::abi::{
8    encode_function_args, encode_function_args_raw, get_func, get_funcs_etherscan,
9};
10use futures::future::join_all;
11
12pub async fn parse_function_args<N: Network, P: Provider<N>>(
13    sig: &str,
14    args: Vec<String>,
15    to: Option<Address>,
16    chain: Chain,
17    provider: &P,
18    etherscan_api_key: Option<&str>,
19    etherscan_api_url: Option<&str>,
20) -> Result<(Vec<u8>, Option<Function>)> {
21    if sig.trim().is_empty() {
22        eyre::bail!("Function signature or calldata must be provided.");
23    }
24
25    // Try to decode as hex calldata first, otherwise treat as function signature
26    if let Ok(data) = hex::decode(sig) {
27        eyre::ensure!(
28            args.is_empty(),
29            "Arguments cannot be used with raw calldata. Use a function signature to encode arguments, or provide the complete calldata without arguments."
30        );
31        return Ok((data, None));
32    } else if sig.starts_with("0x") || sig.starts_with("0X") {
33        let e = hex::decode(sig).unwrap_err();
34        eyre::bail!("Invalid hex calldata '{}': {e}", sig);
35    }
36
37    let (func, args) = if sig.contains('(') {
38        // a regular function signature with parentheses
39        let func = get_func(sig)?;
40        let args = resolve_name_args(&func, &args, provider).await;
41        (func, args)
42    } else {
43        info!(
44            "function signature does not contain parentheses, fetching function data from Etherscan"
45        );
46        let etherscan_api_key = etherscan_api_key.ok_or_eyre(
47            "Function signature does not contain parentheses. If you wish to fetch function data from Etherscan, please provide an API key.",
48        )?;
49        let to = to.ok_or_eyre("A 'to' address must be provided to fetch function data.")?;
50        let funcs =
51            get_funcs_etherscan(sig, to, chain, etherscan_api_key, etherscan_api_url).await?;
52        let mut found = None;
53        for func in funcs {
54            let resolved = resolve_name_args(&func, &args, provider).await;
55            if encode_function_args(&func, &resolved).is_ok() {
56                found = Some((func, resolved));
57                break;
58            }
59        }
60        found.ok_or_eyre("Function not found in abi")?
61    };
62
63    if to.is_none() {
64        // if this is a CREATE call we must exclude the (constructor) function selector: https://github.com/foundry-rs/foundry/issues/10947
65        Ok((encode_function_args_raw(&func, &args)?, Some(func)))
66    } else {
67        Ok((encode_function_args(&func, &args)?, Some(func)))
68    }
69}
70
71/// Resolves ENS names passed to `address` parameters. Other arguments are kept as typed, so values
72/// such as `1.5ether` or `alice.eth` passed to a `uint256` or `string` are never sent to ENS.
73async fn resolve_name_args<N: Network, P: Provider<N>>(
74    func: &Function,
75    args: &[String],
76    provider: &P,
77) -> Vec<String> {
78    join_all(args.iter().enumerate().map(|(i, arg)| async move {
79        let is_address = func.inputs.get(i).is_some_and(|param| param.ty == "address");
80        if is_address && arg.contains('.') {
81            match NameOrAddress::Name(arg.clone()).resolve(provider).await {
82                Ok(addr) => addr.to_string(),
83                Err(_) => arg.clone(),
84            }
85        } else {
86            arg.clone()
87        }
88    }))
89    .await
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95    use alloy_dyn_abi::{DynSolType, DynSolValue};
96    use alloy_network::AnyNetwork;
97    use alloy_primitives::{Bytes, U256, address};
98    use alloy_provider::ProviderBuilder;
99    use alloy_transport::mock::Asserter;
100
101    #[tokio::test]
102    async fn resolves_ens_names_only_for_address_params() {
103        let attacker = address!("0x0000000000000000000000000000000000895440");
104        // Answers every ENS lookup with `attacker`, as a malicious RPC would.
105        let asserter = Asserter::new();
106        let lookup = DynSolValue::Tuple(vec![
107            DynSolValue::Bytes(DynSolValue::Address(attacker).abi_encode()),
108            DynSolValue::Address(Address::ZERO),
109        ])
110        .abi_encode_params();
111        for _ in 0..3 {
112            asserter.push_success(&Bytes::from(lookup.clone()));
113        }
114        let provider =
115            ProviderBuilder::<_, _, AnyNetwork>::default().connect_mocked_client(asserter);
116
117        let args = vec!["alice.eth".to_string(), "1.5e6".to_string(), "bob.eth".to_string()];
118        let (data, _) = parse_function_args(
119            "f(address,uint256,string)",
120            args,
121            Some(Address::ZERO),
122            Chain::mainnet(),
123            &provider,
124            None,
125            None,
126        )
127        .await
128        .unwrap();
129
130        let ty =
131            DynSolType::Tuple(vec![DynSolType::Address, DynSolType::Uint(256), DynSolType::String]);
132        assert_eq!(
133            ty.abi_decode_params(&data[4..]).unwrap(),
134            DynSolValue::Tuple(vec![
135                DynSolValue::Address(attacker),
136                DynSolValue::Uint(U256::from(1_500_000), 256),
137                DynSolValue::String("bob.eth".to_string()),
138            ])
139        );
140    }
141
142    #[tokio::test]
143    async fn rejects_args_after_hex_calldata() {
144        let provider =
145            ProviderBuilder::<_, _, AnyNetwork>::default().connect_mocked_client(Asserter::new());
146
147        for sig in ["0x12345678", "0X12345678", "12345678", "0x1234567800000000", "0x"] {
148            for to in [Some(Address::ZERO), None] {
149                let err = parse_function_args(
150                    sig,
151                    vec!["1".to_string()],
152                    to,
153                    Chain::mainnet(),
154                    &provider,
155                    None,
156                    None,
157                )
158                .await
159                .unwrap_err();
160
161                assert_eq!(
162                    err.to_string(),
163                    "Arguments cannot be used with raw calldata. Use a function signature to encode arguments, or provide the complete calldata without arguments."
164                );
165
166                let (data, func) = parse_function_args(
167                    sig,
168                    Vec::new(),
169                    to,
170                    Chain::mainnet(),
171                    &provider,
172                    None,
173                    None,
174                )
175                .await
176                .unwrap();
177                assert_eq!(data, hex::decode(sig).unwrap());
178                assert!(func.is_none());
179            }
180        }
181    }
182}