foundry_cli/opts/
rpc.rs

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    /// The RPC endpoint, default value is http://localhost:8545.
23    #[arg(short = 'r', long = "rpc-url", env = "ETH_RPC_URL")]
24    pub url: Option<String>,
25
26    /// Allow insecure RPC connections (accept invalid HTTPS certificates).
27    ///
28    /// When the provider's inner runtime transport variant is HTTP, this configures the reqwest
29    /// client to accept invalid certificates.
30    #[arg(short = 'k', long = "insecure", default_value = "false")]
31    pub accept_invalid_certs: bool,
32
33    /// Disable automatic proxy detection.
34    ///
35    /// Use this in sandboxed environments (e.g., Cursor IDE sandbox, macOS App Sandbox) where
36    /// system proxy detection causes crashes. When enabled, HTTP_PROXY/HTTPS_PROXY environment
37    /// variables and system proxy settings will be ignored.
38    #[arg(long = "no-proxy", alias = "disable-proxy", default_value = "false")]
39    pub no_proxy: bool,
40
41    /// Use the Flashbots RPC URL with fast mode (<https://rpc.flashbots.net/fast>).
42    ///
43    /// This shares the transaction privately with all registered builders.
44    ///
45    /// See: <https://docs.flashbots.net/flashbots-protect/quick-start#faster-transactions>
46    #[arg(long)]
47    pub flashbots: bool,
48
49    /// JWT Secret for the RPC endpoint.
50    ///
51    /// The JWT secret will be used to create a JWT for a RPC. For example, the following can be
52    /// used to simulate a CL `engine_forkchoiceUpdated` call:
53    ///
54    /// cast rpc --jwt-secret <JWT_SECRET> engine_forkchoiceUpdatedV2
55    /// '["0x6bb38c26db65749ab6e472080a3d20a2f35776494e72016d1e339593f21c59bc",
56    /// "0x6bb38c26db65749ab6e472080a3d20a2f35776494e72016d1e339593f21c59bc",
57    /// "0x6bb38c26db65749ab6e472080a3d20a2f35776494e72016d1e339593f21c59bc"]'
58    #[arg(long, env = "ETH_RPC_JWT_SECRET")]
59    pub jwt_secret: Option<String>,
60
61    /// Timeout for the RPC request in seconds.
62    ///
63    /// The specified timeout will be used to override the default timeout for RPC requests.
64    ///
65    /// Default value: 45
66    #[arg(long, env = "ETH_RPC_TIMEOUT")]
67    pub rpc_timeout: Option<u64>,
68
69    /// Specify custom headers for RPC requests.
70    #[arg(long, alias = "headers", env = "ETH_RPC_HEADERS", value_delimiter(','))]
71    pub rpc_headers: Option<Vec<String>>,
72
73    /// Print the equivalent curl command instead of making the RPC request.
74    #[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    /// Returns the RPC endpoint.
92    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    /// Returns the JWT secret.
103    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    /// The Etherscan (or equivalent) API key.
146    #[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    /// The chain name or EIP-155 chain ID.
151    #[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    /// Returns true if the Etherscan API key is set.
176    pub fn has_key(&self) -> bool {
177        self.key.as_ref().filter(|key| !key.trim().is_empty()).is_some()
178    }
179
180    /// Returns the Etherscan API key.
181    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
217// Make this args a `Figment` so that it can be merged into the `Config`
218impl 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}