1use crate::opts::ChainValueParser;
2use alloy_chains::ChainKind;
3use clap::Parser;
4use eyre::Result;
5use foundry_config::{
6 Chain, Config, FigmentProviders,
7 figment::{
8 self, Figment, Metadata, Profile,
9 value::{Dict, Map},
10 },
11 find_project_root, impl_figment_convert_cast,
12};
13use foundry_wallets::WalletOpts;
14use serde::Serialize;
15use std::borrow::Cow;
16
17const FLASHBOTS_URL: &str = "https://rpc.flashbots.net/fast";
18
19#[derive(Clone, Debug, Default, Parser)]
20#[command(next_help_heading = "Rpc options")]
21pub struct RpcOpts {
22 #[arg(short = 'r', long = "rpc-url", env = "ETH_RPC_URL")]
24 pub url: Option<String>,
25
26 #[arg(short = 'k', long = "insecure", default_value = "false")]
31 pub accept_invalid_certs: bool,
32
33 #[arg(long = "no-proxy", alias = "disable-proxy", default_value = "false")]
39 pub no_proxy: bool,
40
41 #[arg(long)]
47 pub flashbots: bool,
48
49 #[arg(long, env = "ETH_RPC_JWT_SECRET")]
59 pub jwt_secret: Option<String>,
60
61 #[arg(long, env = "ETH_RPC_TIMEOUT")]
67 pub rpc_timeout: Option<u64>,
68
69 #[arg(long, alias = "headers", env = "ETH_RPC_HEADERS", value_delimiter(','))]
71 pub rpc_headers: Option<Vec<String>>,
72
73 #[arg(long)]
75 pub curl: bool,
76}
77
78impl_figment_convert_cast!(RpcOpts);
79
80impl figment::Provider for RpcOpts {
81 fn metadata(&self) -> Metadata {
82 Metadata::named("RpcOpts")
83 }
84
85 fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
86 Ok(Map::from([(Config::selected_profile(), self.dict())]))
87 }
88}
89
90impl RpcOpts {
91 pub fn url<'a>(&'a self, config: Option<&'a Config>) -> Result<Option<Cow<'a, str>>> {
93 let url = match (self.flashbots, self.url.as_deref(), config) {
94 (true, ..) => Some(Cow::Borrowed(FLASHBOTS_URL)),
95 (false, Some(url), _) => Some(Cow::Borrowed(url)),
96 (false, None, Some(config)) => config.get_rpc_url().transpose()?,
97 (false, None, None) => None,
98 };
99 Ok(url)
100 }
101
102 pub fn jwt<'a>(&'a self, config: Option<&'a Config>) -> Result<Option<Cow<'a, str>>> {
104 let jwt = match (self.jwt_secret.as_deref(), config) {
105 (Some(jwt), _) => Some(Cow::Borrowed(jwt)),
106 (None, Some(config)) => config.get_rpc_jwt_secret()?,
107 (None, None) => None,
108 };
109 Ok(jwt)
110 }
111
112 pub fn dict(&self) -> Dict {
113 let mut dict = Dict::new();
114 if let Ok(Some(url)) = self.url(None) {
115 dict.insert("eth_rpc_url".into(), url.into_owned().into());
116 }
117 if let Ok(Some(jwt)) = self.jwt(None) {
118 dict.insert("eth_rpc_jwt".into(), jwt.into_owned().into());
119 }
120 if let Some(rpc_timeout) = self.rpc_timeout {
121 dict.insert("eth_rpc_timeout".into(), rpc_timeout.into());
122 }
123 if let Some(headers) = &self.rpc_headers {
124 dict.insert("eth_rpc_headers".into(), headers.clone().into());
125 }
126 if self.accept_invalid_certs {
127 dict.insert("eth_rpc_accept_invalid_certs".into(), true.into());
128 }
129 if self.no_proxy {
130 dict.insert("eth_rpc_no_proxy".into(), true.into());
131 }
132 dict
133 }
134
135 pub fn into_figment(self, all: bool) -> Figment {
136 let root = find_project_root(None).expect("could not determine project root");
137 Config::with_root(&root)
138 .to_figment(if all { FigmentProviders::All } else { FigmentProviders::Cast })
139 .merge(self)
140 }
141}
142
143#[derive(Clone, Debug, Default, Serialize, Parser)]
144pub struct EtherscanOpts {
145 #[arg(short = 'e', long = "etherscan-api-key", alias = "api-key", env = "ETHERSCAN_API_KEY")]
147 #[serde(rename = "etherscan_api_key", skip_serializing_if = "Option::is_none")]
148 pub key: Option<String>,
149
150 #[arg(
152 short,
153 long,
154 alias = "chain-id",
155 env = "CHAIN",
156 value_parser = ChainValueParser::default(),
157 )]
158 #[serde(rename = "chain_id", skip_serializing_if = "Option::is_none")]
159 pub chain: Option<Chain>,
160}
161
162impl_figment_convert_cast!(EtherscanOpts);
163
164impl figment::Provider for EtherscanOpts {
165 fn metadata(&self) -> Metadata {
166 Metadata::named("EtherscanOpts")
167 }
168
169 fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
170 Ok(Map::from([(Config::selected_profile(), self.dict())]))
171 }
172}
173
174impl EtherscanOpts {
175 pub fn has_key(&self) -> bool {
177 self.key.as_ref().filter(|key| !key.trim().is_empty()).is_some()
178 }
179
180 pub fn key(&self) -> Option<String> {
182 self.key.as_ref().filter(|key| !key.trim().is_empty()).cloned()
183 }
184
185 pub fn dict(&self) -> Dict {
186 let mut dict = Dict::new();
187 if let Some(key) = self.key() {
188 dict.insert("etherscan_api_key".into(), key.into());
189 }
190
191 if let Some(chain) = self.chain {
192 if let ChainKind::Id(id) = chain.kind() {
193 dict.insert("chain_id".into(), (*id).into());
194 } else {
195 dict.insert("chain_id".into(), chain.to_string().into());
196 }
197 }
198 dict
199 }
200}
201
202#[derive(Clone, Debug, Default, Parser)]
203#[command(next_help_heading = "Ethereum options")]
204pub struct EthereumOpts {
205 #[command(flatten)]
206 pub rpc: RpcOpts,
207
208 #[command(flatten)]
209 pub etherscan: EtherscanOpts,
210
211 #[command(flatten)]
212 pub wallet: WalletOpts,
213}
214
215impl_figment_convert_cast!(EthereumOpts);
216
217impl figment::Provider for EthereumOpts {
219 fn metadata(&self) -> Metadata {
220 Metadata::named("Ethereum Opts Provider")
221 }
222
223 fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
224 let mut dict = self.etherscan.dict();
225 dict.extend(self.rpc.dict());
226
227 if let Some(from) = self.wallet.from {
228 dict.insert("sender".to_string(), from.to_string().into());
229 }
230
231 Ok(Map::from([(Config::selected_profile(), dict)]))
232 }
233}
234
235#[cfg(test)]
236mod tests {
237 use super::*;
238
239 #[test]
240 fn parse_etherscan_opts() {
241 let args: EtherscanOpts =
242 EtherscanOpts::parse_from(["foundry-cli", "--etherscan-api-key", "dummykey"]);
243 assert_eq!(args.key(), Some("dummykey".to_string()));
244
245 let args: EtherscanOpts =
246 EtherscanOpts::parse_from(["foundry-cli", "--etherscan-api-key", ""]);
247 assert!(!args.has_key());
248 }
249}