Skip to main content

foundry_cli/opts/
rpc.rs

1use crate::opts::{ChainValueParser, RpcCommonOpts};
2use clap::Parser;
3use eyre::Result;
4use foundry_config::{
5    Chain, Config, FigmentProviders,
6    figment::{
7        self, Figment, Metadata, Profile,
8        value::{Dict, Map},
9    },
10    impl_figment_convert_cast,
11};
12use foundry_wallets::WalletOpts;
13use serde::Serialize;
14use std::borrow::Cow;
15
16const FLASHBOTS_URL: &str = "https://rpc.flashbots.net/fast";
17
18#[derive(Clone, Debug, Default, Parser)]
19#[command(next_help_heading = "Rpc options")]
20pub struct RpcOpts {
21    /// Common RPC options (URL, timeout, rate limiting, etc.).
22    #[command(flatten)]
23    pub common: RpcCommonOpts,
24
25    /// Use the Flashbots RPC URL with fast mode (<https://rpc.flashbots.net/fast>).
26    ///
27    /// This shares the transaction privately with all registered builders.
28    ///
29    /// See: <https://docs.flashbots.net/flashbots-protect/quick-start#faster-transactions>
30    #[arg(long)]
31    pub flashbots: bool,
32
33    /// JWT Secret for the RPC endpoint.
34    ///
35    /// The JWT secret will be used to create a JWT for an RPC. For example, the following can be
36    /// used to simulate a CL `engine_forkchoiceUpdated` call:
37    ///
38    /// cast rpc --jwt-secret <JWT_SECRET> engine_forkchoiceUpdatedV2
39    /// '["0x6bb38c26db65749ab6e472080a3d20a2f35776494e72016d1e339593f21c59bc",
40    /// "0x6bb38c26db65749ab6e472080a3d20a2f35776494e72016d1e339593f21c59bc",
41    /// "0x6bb38c26db65749ab6e472080a3d20a2f35776494e72016d1e339593f21c59bc"]'
42    #[arg(long, env = "ETH_RPC_JWT_SECRET")]
43    pub jwt_secret: Option<String>,
44
45    /// Specify custom headers for RPC requests.
46    #[arg(long, alias = "headers", env = "ETH_RPC_HEADERS", value_delimiter(','))]
47    pub rpc_headers: Option<Vec<String>>,
48
49    /// Print the equivalent curl command instead of making the RPC request.
50    #[arg(long)]
51    pub curl: bool,
52}
53
54impl_figment_convert_cast!(RpcOpts);
55
56impl figment::Provider for RpcOpts {
57    fn metadata(&self) -> Metadata {
58        Metadata::named("RpcOpts")
59    }
60
61    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
62        Ok(Map::from([(Config::selected_profile(), self.dict())]))
63    }
64}
65
66impl RpcOpts {
67    /// Returns the RPC endpoint.
68    pub fn url<'a>(&'a self, config: Option<&'a Config>) -> Result<Option<Cow<'a, str>>> {
69        self.url_with_env(config, std::env::var("ETH_RPC_URL").ok())
70    }
71
72    fn url_with_env<'a>(
73        &'a self,
74        config: Option<&'a Config>,
75        env_url: Option<String>,
76    ) -> Result<Option<Cow<'a, str>>> {
77        if self.flashbots {
78            Ok(Some(Cow::Borrowed(FLASHBOTS_URL)))
79        } else if let Some(url) = self.common.rpc_url.as_deref() {
80            Ok(Some(Cow::Borrowed(url)))
81        } else if let Some(url) = env_url {
82            Ok(Some(Cow::Owned(url)))
83        } else {
84            self.common.url(config)
85        }
86    }
87
88    /// Returns the JWT secret.
89    pub fn jwt<'a>(&'a self, config: Option<&'a Config>) -> Result<Option<Cow<'a, str>>> {
90        let jwt = match (self.jwt_secret.as_deref(), config) {
91            (Some(jwt), _) => Some(Cow::Borrowed(jwt)),
92            (None, Some(config)) => config.get_rpc_jwt_secret()?,
93            (None, None) => None,
94        };
95        Ok(jwt)
96    }
97
98    pub fn dict(&self) -> Dict {
99        let mut dict = self.common.dict();
100        // `self.url(None)` already accounts for `flashbots` and the `ETH_RPC_URL` env var,
101        // so a single insert here covers both.
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(headers) = &self.rpc_headers {
109            dict.insert("eth_rpc_headers".into(), headers.clone().into());
110        }
111        if self.curl {
112            dict.insert("eth_rpc_curl".into(), true.into());
113        }
114        dict
115    }
116
117    pub fn into_figment(self, all: bool) -> Figment {
118        Config::current_project_figment(if all {
119            FigmentProviders::All
120        } else {
121            FigmentProviders::Cast
122        })
123        .merge(self)
124    }
125}
126
127#[derive(Clone, Debug, Default, Serialize, Parser)]
128pub struct EtherscanOpts {
129    /// The Etherscan (or equivalent) API key.
130    #[arg(short = 'e', long = "etherscan-api-key", alias = "api-key", env = "ETHERSCAN_API_KEY")]
131    #[serde(rename = "etherscan_api_key", skip_serializing_if = "Option::is_none")]
132    pub key: Option<String>,
133
134    /// The chain name or EIP-155 chain ID.
135    #[arg(
136        short,
137        long,
138        alias = "chain-id",
139        env = "CHAIN",
140        value_parser = ChainValueParser::default(),
141    )]
142    #[serde(rename = "chain_id", skip_serializing_if = "Option::is_none")]
143    pub chain: Option<Chain>,
144}
145
146impl_figment_convert_cast!(EtherscanOpts);
147
148impl figment::Provider for EtherscanOpts {
149    fn metadata(&self) -> Metadata {
150        Metadata::named("EtherscanOpts")
151    }
152
153    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
154        Ok(Map::from([(Config::selected_profile(), self.dict())]))
155    }
156}
157
158impl EtherscanOpts {
159    /// Returns true if the Etherscan API key is set.
160    pub fn has_key(&self) -> bool {
161        self.key.as_ref().is_some_and(|key| !key.trim().is_empty())
162    }
163
164    /// Returns the Etherscan API key.
165    pub fn key(&self) -> Option<String> {
166        self.key.as_ref().filter(|key| !key.trim().is_empty()).cloned()
167    }
168
169    pub fn dict(&self) -> Dict {
170        let mut dict = Dict::new();
171        if let Some(key) = self.key() {
172            dict.insert("etherscan_api_key".into(), key.into());
173        }
174
175        if let Some(chain) = self.chain {
176            dict.insert("chain_id".into(), chain.id().into());
177        }
178        dict
179    }
180}
181
182#[derive(Clone, Debug, Default, Parser)]
183#[command(next_help_heading = "Ethereum options")]
184pub struct EthereumOpts {
185    #[command(flatten)]
186    pub rpc: RpcOpts,
187
188    #[command(flatten)]
189    pub etherscan: EtherscanOpts,
190
191    #[command(flatten)]
192    pub wallet: WalletOpts,
193}
194
195impl_figment_convert_cast!(EthereumOpts);
196
197// Make this args a `Figment` so that it can be merged into the `Config`
198impl figment::Provider for EthereumOpts {
199    fn metadata(&self) -> Metadata {
200        Metadata::named("Ethereum Opts Provider")
201    }
202
203    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
204        let mut dict = self.etherscan.dict();
205        dict.extend(self.rpc.dict());
206
207        if let Some(from) = self.wallet.from {
208            dict.insert("sender".to_string(), from.to_string().into());
209        }
210
211        Ok(Map::from([(Config::selected_profile(), dict)]))
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use clap::CommandFactory;
219
220    #[test]
221    fn parse_etherscan_opts() {
222        let args: EtherscanOpts =
223            EtherscanOpts::parse_from(["foundry-cli", "--etherscan-api-key", "dummykey"]);
224        assert_eq!(args.key(), Some("dummykey".to_string()));
225
226        let args: EtherscanOpts =
227            EtherscanOpts::parse_from(["foundry-cli", "--etherscan-api-key", ""]);
228        assert!(!args.has_key());
229    }
230
231    // <https://github.com/foundry-rs/foundry/issues/14314>
232    #[test]
233    fn named_chain_dict_inserts_numeric_id() {
234        // Chain 9745 is recognized as NamedChain::Plasma by alloy-chains.
235        // Previously, dict() would insert chain_id as the string "plasma",
236        // causing deserialization failure when EvmOpts expects u64.
237        let args = EtherscanOpts::parse_from(["foundry-cli", "--chain", "9745"]);
238        let dict = args.dict();
239        let chain_id = dict.get("chain_id").expect("chain_id should be present");
240        let id: u64 = chain_id.deserialize().expect("chain_id should deserialize as u64");
241        assert_eq!(id, 9745);
242    }
243
244    #[test]
245    fn rpc_url_arg_does_not_read_eth_rpc_url_env() {
246        let command = RpcOpts::command();
247        let rpc_url =
248            command.get_arguments().find(|arg| arg.get_id() == "rpc_url").expect("rpc_url arg");
249
250        assert!(rpc_url.get_env().is_none());
251    }
252
253    #[test]
254    fn rpc_url_resolves_eth_rpc_url_env() {
255        let args = RpcOpts::default();
256        let url = args
257            .url_with_env(None, Some("http://127.0.0.1:8545".to_string()))
258            .expect("url")
259            .expect("url");
260
261        assert_eq!(url.as_ref(), "http://127.0.0.1:8545");
262    }
263
264    #[test]
265    fn explicit_rpc_url_takes_precedence_over_eth_rpc_url_env() {
266        let args = RpcOpts {
267            common: RpcCommonOpts {
268                rpc_url: Some("http://127.0.0.1:8546".to_string()),
269                ..Default::default()
270            },
271            ..Default::default()
272        };
273        let url = args
274            .url_with_env(None, Some("http://127.0.0.1:8545".to_string()))
275            .expect("url")
276            .expect("url");
277
278        assert_eq!(url.as_ref(), "http://127.0.0.1:8546");
279    }
280}