cast/cmd/
interface.rs

1use alloy_json_abi::{ContractObject, JsonAbi};
2use alloy_primitives::Address;
3use clap::Parser;
4use eyre::{Context, Result};
5use forge_fmt::FormatterConfig;
6use foundry_cli::{
7    opts::EtherscanOpts,
8    utils::{LoadConfig, fetch_abi_from_etherscan},
9};
10use foundry_common::{
11    ContractsByArtifact,
12    compile::{PathOrContractInfo, ProjectCompiler},
13    find_target_path, fs, shell,
14};
15use foundry_config::load_config;
16use itertools::Itertools;
17use serde_json::Value;
18use std::{
19    path::{Path, PathBuf},
20    str::FromStr,
21};
22
23/// CLI arguments for `cast interface`.
24#[derive(Clone, Debug, Parser)]
25pub struct InterfaceArgs {
26    /// The target contract, which can be one of:
27    /// - A file path to an ABI JSON file.
28    /// - A contract identifier in the form `<path>:<contractname>` or just `<contractname>`.
29    /// - An Ethereum address, for which the ABI will be fetched from Etherscan.
30    contract: String,
31
32    /// The name to use for the generated interface.
33    ///
34    /// Only relevant when retrieving the ABI from a file.
35    #[arg(long, short)]
36    name: Option<String>,
37
38    /// Solidity pragma version.
39    #[arg(long, short, default_value = "^0.8.4", value_name = "VERSION")]
40    pragma: String,
41
42    /// The path to the output file.
43    ///
44    /// If not specified, the interface will be output to stdout.
45    #[arg(
46        short,
47        long,
48        value_hint = clap::ValueHint::FilePath,
49        value_name = "PATH",
50    )]
51    output: Option<PathBuf>,
52
53    #[command(flatten)]
54    etherscan: EtherscanOpts,
55}
56
57impl InterfaceArgs {
58    pub async fn run(self) -> Result<()> {
59        let Self { contract, name, pragma, output: output_location, etherscan } = self;
60
61        // Determine if the target contract is an ABI file, a local contract or an Ethereum address.
62        let abis = if Path::new(&contract).is_file()
63            && fs::read_to_string(&contract)
64                .ok()
65                .and_then(|content| serde_json::from_str::<Value>(&content).ok())
66                .is_some()
67        {
68            load_abi_from_file(&contract, name)?
69        } else {
70            match Address::from_str(&contract) {
71                Ok(address) => fetch_abi_from_etherscan(address, &etherscan.load_config()?).await?,
72                Err(_) => load_abi_from_artifact(&contract)?,
73            }
74        };
75
76        // Retrieve interfaces from the array of ABIs.
77        let interfaces = get_interfaces(abis)?;
78
79        // Print result or write to file.
80        let res = if shell::is_json() {
81            // Format as JSON.
82            interfaces.iter().map(|iface| &iface.json_abi).format("\n").to_string()
83        } else {
84            // Format as Solidity.
85            format!(
86                "// SPDX-License-Identifier: UNLICENSED\n\
87                 pragma solidity {pragma};\n\n\
88                 {}",
89                interfaces.iter().map(|iface| &iface.source).format("\n")
90            )
91        };
92
93        if let Some(loc) = output_location {
94            if let Some(parent) = loc.parent() {
95                fs::create_dir_all(parent)?;
96            }
97            fs::write(&loc, res)?;
98            sh_println!("Saved interface at {}", loc.display())?;
99        } else {
100            sh_print!("{res}")?;
101        }
102
103        Ok(())
104    }
105}
106
107struct InterfaceSource {
108    json_abi: String,
109    source: String,
110}
111
112/// Load the ABI from a file.
113pub fn load_abi_from_file(path: &str, name: Option<String>) -> Result<Vec<(JsonAbi, String)>> {
114    let file = std::fs::read_to_string(path).wrap_err("unable to read abi file")?;
115    let obj: ContractObject = serde_json::from_str(&file)?;
116    let abi = obj.abi.ok_or_else(|| eyre::eyre!("could not find ABI in file {path}"))?;
117    let name = name.unwrap_or_else(|| "Interface".to_owned());
118    Ok(vec![(abi, name)])
119}
120
121/// Load the ABI from the artifact of a locally compiled contract.
122fn load_abi_from_artifact(path_or_contract: &str) -> Result<Vec<(JsonAbi, String)>> {
123    let config = load_config()?;
124    let project = config.project()?;
125    let compiler = ProjectCompiler::new().quiet(true);
126
127    let contract = PathOrContractInfo::from_str(path_or_contract)?;
128
129    let target_path = find_target_path(&project, &contract)?;
130    let output = compiler.files([target_path.clone()]).compile(&project)?;
131
132    let contracts_by_artifact = ContractsByArtifact::from(output);
133
134    let maybe_abi = contracts_by_artifact
135        .find_abi_by_name_or_src_path(contract.name().unwrap_or(&target_path.to_string_lossy()));
136
137    let (abi, name) =
138        maybe_abi.as_ref().ok_or_else(|| eyre::eyre!("Failed to fetch lossless ABI"))?;
139
140    Ok(vec![(abi.clone(), contract.name().unwrap_or(name).to_string())])
141}
142
143/// Converts a vector of tuples containing the ABI and contract name into a vector of
144/// `InterfaceSource` objects.
145fn get_interfaces(abis: Vec<(JsonAbi, String)>) -> Result<Vec<InterfaceSource>> {
146    abis.into_iter()
147        .map(|(contract_abi, name)| {
148            let source = match forge_fmt::format(
149                &contract_abi.to_sol(&name, None),
150                FormatterConfig::default(),
151            )
152            .into_result()
153            {
154                Ok(generated_source) => generated_source,
155                Err(e) => {
156                    sh_warn!("Failed to format interface for {name}: {e}")?;
157                    contract_abi.to_sol(&name, None)
158                }
159            };
160
161            Ok(InterfaceSource { json_abi: serde_json::to_string_pretty(&contract_abi)?, source })
162        })
163        .collect()
164}