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)]
39 pub flashbots: bool,
40
41 #[arg(long, env = "ETH_RPC_JWT_SECRET")]
51 pub jwt_secret: Option<String>,
52
53 #[arg(long, env = "ETH_RPC_TIMEOUT")]
59 pub rpc_timeout: Option<u64>,
60
61 #[arg(long, alias = "headers", env = "ETH_RPC_HEADERS", value_delimiter(','))]
63 pub rpc_headers: Option<Vec<String>>,
64}
65
66impl_figment_convert_cast!(RpcOpts);
67
68impl figment::Provider for RpcOpts {
69 fn metadata(&self) -> Metadata {
70 Metadata::named("RpcOpts")
71 }
72
73 fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
74 Ok(Map::from([(Config::selected_profile(), self.dict())]))
75 }
76}
77
78impl RpcOpts {
79 pub fn url<'a>(&'a self, config: Option<&'a Config>) -> Result<Option<Cow<'a, str>>> {
81 let url = match (self.flashbots, self.url.as_deref(), config) {
82 (true, ..) => Some(Cow::Borrowed(FLASHBOTS_URL)),
83 (false, Some(url), _) => Some(Cow::Borrowed(url)),
84 (false, None, Some(config)) => config.get_rpc_url().transpose()?,
85 (false, None, None) => None,
86 };
87 Ok(url)
88 }
89
90 pub fn jwt<'a>(&'a self, config: Option<&'a Config>) -> Result<Option<Cow<'a, str>>> {
92 let jwt = match (self.jwt_secret.as_deref(), config) {
93 (Some(jwt), _) => Some(Cow::Borrowed(jwt)),
94 (None, Some(config)) => config.get_rpc_jwt_secret()?,
95 (None, None) => None,
96 };
97 Ok(jwt)
98 }
99
100 pub fn dict(&self) -> Dict {
101 let mut dict = Dict::new();
102 if let Ok(Some(url)) = self.url(None) {
103 dict.insert("eth_rpc_url".into(), url.into_owned().into());
104 }
105 if let Ok(Some(jwt)) = self.jwt(None) {
106 dict.insert("eth_rpc_jwt".into(), jwt.into_owned().into());
107 }
108 if let Some(rpc_timeout) = self.rpc_timeout {
109 dict.insert("eth_rpc_timeout".into(), rpc_timeout.into());
110 }
111 if let Some(headers) = &self.rpc_headers {
112 dict.insert("eth_rpc_headers".into(), headers.clone().into());
113 }
114 if self.accept_invalid_certs {
115 dict.insert("eth_rpc_accept_invalid_certs".into(), true.into());
116 }
117 dict
118 }
119
120 pub fn into_figment(self, all: bool) -> Figment {
121 let root = find_project_root(None).expect("could not determine project root");
122 Config::with_root(&root)
123 .to_figment(if all { FigmentProviders::All } else { FigmentProviders::Cast })
124 .merge(self)
125 }
126}
127
128#[derive(Clone, Debug, Default, Serialize, Parser)]
129pub struct EtherscanOpts {
130 #[arg(short = 'e', long = "etherscan-api-key", alias = "api-key", env = "ETHERSCAN_API_KEY")]
132 #[serde(rename = "etherscan_api_key", skip_serializing_if = "Option::is_none")]
133 pub key: Option<String>,
134
135 #[arg(
137 short,
138 long,
139 alias = "chain-id",
140 env = "CHAIN",
141 value_parser = ChainValueParser::default(),
142 )]
143 #[serde(rename = "chain_id", skip_serializing_if = "Option::is_none")]
144 pub chain: Option<Chain>,
145}
146
147impl_figment_convert_cast!(EtherscanOpts);
148
149impl figment::Provider for EtherscanOpts {
150 fn metadata(&self) -> Metadata {
151 Metadata::named("EtherscanOpts")
152 }
153
154 fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
155 Ok(Map::from([(Config::selected_profile(), self.dict())]))
156 }
157}
158
159impl EtherscanOpts {
160 pub fn has_key(&self) -> bool {
162 self.key.as_ref().filter(|key| !key.trim().is_empty()).is_some()
163 }
164
165 pub fn key(&self) -> Option<String> {
167 self.key.as_ref().filter(|key| !key.trim().is_empty()).cloned()
168 }
169
170 pub fn dict(&self) -> Dict {
171 let mut dict = Dict::new();
172 if let Some(key) = self.key() {
173 dict.insert("etherscan_api_key".into(), key.into());
174 }
175
176 if let Some(chain) = self.chain {
177 if let ChainKind::Id(id) = chain.kind() {
178 dict.insert("chain_id".into(), (*id).into());
179 } else {
180 dict.insert("chain_id".into(), chain.to_string().into());
181 }
182 }
183 dict
184 }
185}
186
187#[derive(Clone, Debug, Default, Parser)]
188#[command(next_help_heading = "Ethereum options")]
189pub struct EthereumOpts {
190 #[command(flatten)]
191 pub rpc: RpcOpts,
192
193 #[command(flatten)]
194 pub etherscan: EtherscanOpts,
195
196 #[command(flatten)]
197 pub wallet: WalletOpts,
198}
199
200impl_figment_convert_cast!(EthereumOpts);
201
202impl figment::Provider for EthereumOpts {
204 fn metadata(&self) -> Metadata {
205 Metadata::named("Ethereum Opts Provider")
206 }
207
208 fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
209 let mut dict = self.etherscan.dict();
210 dict.extend(self.rpc.dict());
211
212 if let Some(from) = self.wallet.from {
213 dict.insert("sender".to_string(), from.to_string().into());
214 }
215
216 Ok(Map::from([(Config::selected_profile(), dict)]))
217 }
218}
219
220#[cfg(test)]
221mod tests {
222 use super::*;
223
224 #[test]
225 fn parse_etherscan_opts() {
226 let args: EtherscanOpts =
227 EtherscanOpts::parse_from(["foundry-cli", "--etherscan-api-key", "dummykey"]);
228 assert_eq!(args.key(), Some("dummykey".to_string()));
229
230 let args: EtherscanOpts =
231 EtherscanOpts::parse_from(["foundry-cli", "--etherscan-api-key", ""]);
232 assert!(!args.has_key());
233 }
234}