1use alloy_json_abi::{ContractObject, JsonAbi, ToSolConfig};
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#[derive(Clone, Debug, Parser)]
25pub struct InterfaceArgs {
26 contract: String,
31
32 #[arg(long, short)]
36 name: Option<String>,
37
38 #[arg(long, short, default_value = "^0.8.4", value_name = "VERSION")]
40 pragma: String,
41
42 #[arg(
46 short,
47 long,
48 value_hint = clap::ValueHint::FilePath,
49 value_name = "PATH",
50 )]
51 output: Option<PathBuf>,
52
53 #[arg(long)]
57 flatten: bool,
58
59 #[command(flatten)]
60 etherscan: EtherscanOpts,
61}
62
63impl InterfaceArgs {
64 pub async fn run(self) -> Result<()> {
65 let Self { contract, name, pragma, output: output_location, flatten, etherscan } = self;
66
67 let abis = if Path::new(&contract).is_file()
69 && fs::read_to_string(&contract)
70 .ok()
71 .and_then(|content| serde_json::from_str::<Value>(&content).ok())
72 .is_some()
73 {
74 load_abi_from_file(&contract, name)?
75 } else {
76 match Address::from_str(&contract) {
77 Ok(address) => fetch_abi_from_etherscan(address, ðerscan.load_config()?).await?,
78 Err(_) => load_abi_from_artifact(&contract)?,
79 }
80 };
81
82 let config = if flatten { Some(ToSolConfig::new().one_contract(true)) } else { None };
84
85 let interfaces = get_interfaces(abis, config)?;
87
88 let res = if shell::is_json() {
90 interfaces.iter().map(|iface| &iface.json_abi).format("\n").to_string()
92 } else {
93 format!(
95 "// SPDX-License-Identifier: UNLICENSED\n\
96 pragma solidity {pragma};\n\n\
97 {}",
98 interfaces.iter().map(|iface| &iface.source).format("\n")
99 )
100 };
101
102 if let Some(loc) = output_location {
103 if let Some(parent) = loc.parent() {
104 fs::create_dir_all(parent)?;
105 }
106 fs::write(&loc, res)?;
107 sh_println!("Saved interface at {}", loc.display())?;
108 } else {
109 sh_print!("{res}")?;
110 }
111
112 Ok(())
113 }
114}
115
116struct InterfaceSource {
117 json_abi: String,
118 source: String,
119}
120
121pub fn load_abi_from_file(path: &str, name: Option<String>) -> Result<Vec<(JsonAbi, String)>> {
123 let file = std::fs::read_to_string(path).wrap_err("unable to read abi file")?;
124 let obj: ContractObject = serde_json::from_str(&file)?;
125 let abi = obj.abi.ok_or_else(|| eyre::eyre!("could not find ABI in file {path}"))?;
126 let name = name.unwrap_or_else(|| "Interface".to_owned());
127 Ok(vec![(abi, name)])
128}
129
130fn load_abi_from_artifact(path_or_contract: &str) -> Result<Vec<(JsonAbi, String)>> {
132 let config = load_config()?;
133 let project = config.project()?;
134 let compiler = ProjectCompiler::new().quiet(true);
135
136 let contract = PathOrContractInfo::from_str(path_or_contract)?;
137
138 let target_path = find_target_path(&project, &contract)?;
139 let output = compiler.files([target_path.clone()]).compile(&project)?;
140
141 let contracts_by_artifact = ContractsByArtifact::from(output);
142
143 let maybe_abi = contracts_by_artifact
144 .find_abi_by_name_or_src_path(contract.name().unwrap_or(&target_path.to_string_lossy()));
145
146 let (abi, name) =
147 maybe_abi.as_ref().ok_or_else(|| eyre::eyre!("Failed to fetch lossless ABI"))?;
148
149 Ok(vec![(abi.clone(), contract.name().unwrap_or(name).to_string())])
150}
151
152fn get_interfaces(
155 abis: Vec<(JsonAbi, String)>,
156 config: Option<ToSolConfig>,
157) -> Result<Vec<InterfaceSource>> {
158 abis.into_iter()
159 .map(|(contract_abi, name)| {
160 let source = match forge_fmt::format(
161 &contract_abi.to_sol(&name, config.clone()),
162 FormatterConfig::default(),
163 )
164 .into_result()
165 {
166 Ok(generated_source) => generated_source,
167 Err(e) => {
168 sh_warn!("Failed to format interface for {name}: {e}")?;
169 contract_abi.to_sol(&name, config.clone())
170 }
171 };
172
173 Ok(InterfaceSource { json_abi: serde_json::to_string_pretty(&contract_abi)?, source })
174 })
175 .collect()
176}