Skip to main content

cast/cmd/
mod.rs

1//! `cast` subcommands.
2//!
3//! All subcommands should respect the `foundry_config::Config`.
4//! If a subcommand accepts values that are supported by the `Config`, then the subcommand should
5//! implement `figment::Provider` which allows the subcommand to override the config's defaults, see
6//! [`foundry_config::Config`].
7
8use alloy_network::Network;
9use alloy_primitives::{Address, Bytes, map::AddressHashMap};
10use alloy_provider::Provider;
11use alloy_rpc_types::BlockId;
12use eyre::Result;
13use foundry_cli::{
14    json::print_scalar,
15    opts::RpcOpts,
16    utils::{LoadConfig, get_provider, load_config_from_provider},
17};
18use foundry_common::{provider::RetryProvider, shell};
19use foundry_config::{Config, figment::Figment};
20use foundry_evm::{core::bytecode::InstIter, opts::EvmOpts};
21use foundry_evm_networks::NetworkVariant;
22use futures::StreamExt;
23use serde::Serialize;
24use serde_json::Value;
25use std::fmt::{Display, Write};
26
27const MAX_CONCURRENT_RPC_REQUESTS: usize = 5;
28
29/// Loads Cast's config and applies its normalized network to the EVM options.
30pub(crate) fn load_cast_config_and_evm_opts(figment: Figment) -> Result<(Box<Config>, EvmOpts)> {
31    let config = Box::new(load_config_from_provider(figment.clone())?);
32    let mut evm_opts = figment.extract::<EvmOpts>()?;
33    evm_opts.networks = config.networks;
34    Ok((config, evm_opts))
35}
36
37/// Loads the config for `rpc` and builds the default provider from it.
38pub(crate) fn rpc_provider(rpc: &RpcOpts) -> Result<RetryProvider> {
39    get_provider(&rpc.load_config()?)
40}
41
42/// Asks whether to continue after a warning, printing `Aborted.` when the user declines.
43pub(crate) fn confirm_continue() -> Result<bool> {
44    let response: String = foundry_common::prompt!("\nContinue anyway? [y/N] ")?;
45    if matches!(response.trim(), "y" | "Y") {
46        return Ok(true);
47    }
48    sh_status!("Aborted.")?;
49    Ok(false)
50}
51
52/// Prints `json` pretty-printed (un-enveloped) in JSON mode, `plain` otherwise.
53pub(crate) fn print_json_or(json: Value, plain: impl Display) -> Result<()> {
54    if shell::is_json() {
55        sh_println!("{}", serde_json::to_string_pretty(&json)?)?;
56    } else {
57        sh_println!("{plain}")?;
58    }
59    Ok(())
60}
61
62/// Prints the primary result of a command: a JSON envelope in `--json` mode, otherwise a raw line
63/// that bypasses the shell verbosity layer so `--quiet` does not suppress it.
64pub(crate) fn print_result_line(value: impl Serialize + Display) -> Result<()> {
65    if shell::is_json() {
66        return print_scalar(value);
67    }
68    print_raw_line(value)
69}
70
71/// Prints a raw line to stdout, bypassing the shell verbosity layer so `--quiet` does not
72/// suppress it.
73pub(crate) fn print_raw_line(value: impl Display) -> Result<()> {
74    let mut shell = shell::Shell::get();
75    let out = shell.out();
76    writeln!(out, "{value}")?;
77    out.flush()?;
78    Ok(())
79}
80
81/// Fetches the non-empty code of `addresses` at `block` with bounded concurrency, warning about
82/// addresses whose code cannot be fetched.
83pub(crate) async fn fetch_code_via_rpc<N: Network, P: Provider<N>>(
84    provider: &P,
85    addresses: impl IntoIterator<Item = Address>,
86    block: BlockId,
87) -> AddressHashMap<Bytes> {
88    let mut code_by_address = AddressHashMap::default();
89    let mut requests = futures::stream::iter(addresses)
90        .map(
91            |address| async move { (address, provider.get_code_at(address).block_id(block).await) },
92        )
93        .buffer_unordered(MAX_CONCURRENT_RPC_REQUESTS);
94    while let Some((address, code)) = requests.next().await {
95        match code {
96            Ok(code) if !code.is_empty() => {
97                code_by_address.insert(address, code);
98            }
99            Ok(_) => {}
100            Err(err) => {
101                let _ = sh_warn!("Failed to fetch code for {address}: {err}");
102            }
103        }
104    }
105    code_by_address
106}
107
108pub mod access_list;
109pub mod artifact;
110mod auth;
111pub mod b2e_payload;
112pub mod bal;
113pub mod batch_mktx;
114pub mod batch_send;
115pub mod bind;
116pub mod call;
117pub mod call_overrides;
118pub mod configurable_key_auth;
119pub mod constructor_args;
120pub mod create2;
121pub mod creation_code;
122#[cfg(any(feature = "base", feature = "optimism"))]
123pub mod da_estimate;
124pub mod erc20;
125pub mod erc4626;
126pub mod estimate;
127pub mod events;
128pub mod find_block;
129pub mod interface;
130pub mod keychain;
131pub mod logs;
132pub(crate) mod miner;
133pub mod mktx;
134pub mod receive_policy;
135pub mod rpc;
136pub mod run;
137pub mod safe;
138pub mod send;
139pub mod storage;
140pub mod storage_credits;
141pub mod tempo;
142pub(crate) mod tempo_policy_args;
143pub mod tip20;
144pub mod tip403;
145pub mod trace;
146pub mod txpool;
147pub mod vaddr;
148pub mod wallet;
149
150/// Validates a Tempo transaction requirement against an explicit execution family.
151pub(crate) fn validate_tempo_network(config: &Config, requires_tempo: bool) -> Result<()> {
152    if requires_tempo && config.networks.has_network_selection() {
153        let network = config.networks.execution_network();
154        eyre::ensure!(
155            network.is_tempo(),
156            "Tempo transaction options conflict with configured network `{}`",
157            config.networks.execution_profile_name()
158        );
159    }
160    Ok(())
161}
162
163/// Resolves the RPC request family before typed transaction construction.
164pub(crate) async fn resolve_transaction_network(
165    config: &Config,
166    requires_tempo: bool,
167) -> Result<NetworkVariant> {
168    validate_tempo_network(config, requires_tempo)?;
169    if requires_tempo {
170        return Ok(NetworkVariant::Tempo);
171    }
172    if config.networks.has_network_selection() {
173        return Ok(config.networks.execution_network());
174    }
175    if let Some(chain) = config.chain {
176        return Ok(chain.id().into());
177    }
178    if config.eth_rpc_curl {
179        return Ok(NetworkVariant::Ethereum);
180    }
181
182    let provider = get_provider(config)?;
183    Ok(provider.get_chain_id().await?.into())
184}
185
186pub(crate) fn disassemble(code: &[u8]) -> Result<String> {
187    let mut output = String::new();
188    for (pc, inst) in InstIter::new(code).with_pc() {
189        writeln!(output, "{pc:08x}: {inst}")?;
190    }
191    Ok(output)
192}
193
194/// Rejects blob options before Base's transaction builder can discard them.
195#[cfg(feature = "base")]
196pub(crate) fn validate_base_transaction_options(
197    tx: &foundry_cli::opts::TransactionOpts,
198) -> eyre::Result<()> {
199    eyre::ensure!(
200        !tx.blob && !tx.eip4844 && tx.blob_gas_price.is_none(),
201        "Base does not support blob transactions; remove --blob, --eip4844, and --blob-gas-price"
202    );
203    Ok(())
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    #[cfg(feature = "base")]
211    use foundry_config::Chain;
212
213    #[tokio::test]
214    async fn transaction_network_respects_explicit_selection() {
215        for network in [NetworkVariant::Ethereum, NetworkVariant::Tempo] {
216            let config =
217                Config { networks: network.into(), eth_rpc_curl: true, ..Default::default() };
218            assert_eq!(resolve_transaction_network(&config, false).await.unwrap(), network);
219            assert_eq!(
220                resolve_transaction_network(&config, true).await.is_ok(),
221                network.is_tempo()
222            );
223        }
224        let config = Config { eth_rpc_curl: true, ..Default::default() };
225        assert_eq!(
226            resolve_transaction_network(&config, true).await.unwrap(),
227            NetworkVariant::Tempo
228        );
229        assert_eq!(
230            resolve_transaction_network(&config, false).await.unwrap(),
231            NetworkVariant::Ethereum
232        );
233
234        let config = Config {
235            networks: foundry_evm_networks::NetworkConfigs::with_celo(),
236            eth_rpc_curl: true,
237            ..Default::default()
238        };
239        assert_eq!(
240            resolve_transaction_network(&config, false).await.unwrap(),
241            NetworkVariant::Ethereum
242        );
243        assert_eq!(
244            resolve_transaction_network(&config, true).await.unwrap_err().to_string(),
245            "Tempo transaction options conflict with configured network `celo`"
246        );
247    }
248
249    #[cfg(feature = "monad")]
250    #[test]
251    fn normalized_hardfork_network_is_applied_to_evm_opts() {
252        let figment = Config::figment().merge(("hardfork", "monad:MonadNine"));
253        let (config, evm_opts) = load_cast_config_and_evm_opts(figment).unwrap();
254
255        assert!(config.networks.is_monad());
256        assert!(evm_opts.networks.is_monad());
257    }
258
259    #[cfg(feature = "base")]
260    #[tokio::test]
261    async fn resolve_network_preserves_explicit_base() {
262        let config = Config { networks: NetworkVariant::Base.into(), ..Default::default() };
263        assert_eq!(
264            resolve_transaction_network(&config, false).await.unwrap(),
265            NetworkVariant::Base
266        );
267        assert_eq!(
268            resolve_transaction_network(&config, true).await.unwrap_err().to_string(),
269            "Tempo transaction options conflict with configured network `base`"
270        );
271    }
272
273    #[cfg(feature = "base")]
274    #[tokio::test]
275    async fn resolve_network_infers_base_from_chain_id() {
276        let config = Config { chain: Some(Chain::base_mainnet()), ..Default::default() };
277        assert_eq!(
278            resolve_transaction_network(&config, false).await.unwrap(),
279            NetworkVariant::Base
280        );
281    }
282
283    #[cfg(all(any(feature = "base", feature = "optimism"), not(feature = "monad")))]
284    #[tokio::test]
285    async fn resolve_network_allows_rpc_without_local_evm() {
286        let config = Config {
287            chain: Some(foundry_config::Chain::from_named(alloy_chains::NamedChain::Monad)),
288            ..Default::default()
289        };
290        assert_eq!(
291            resolve_transaction_network(&config, false).await.unwrap(),
292            NetworkVariant::Ethereum
293        );
294    }
295
296    #[cfg(feature = "base")]
297    #[tokio::test]
298    async fn resolve_network_preserves_config_over_chain_in_curl_mode() {
299        let config = Config {
300            networks: NetworkVariant::Base.into(),
301            chain: Some(foundry_config::Chain::from_id(31337)),
302            eth_rpc_curl: true,
303            ..Default::default()
304        };
305        assert_eq!(
306            resolve_transaction_network(&config, false).await.unwrap(),
307            NetworkVariant::Base
308        );
309        let config = Config {
310            networks: NetworkVariant::Ethereum.into(),
311            chain: Some(foundry_config::Chain::from_id(8453)),
312            ..config
313        };
314        assert_eq!(
315            resolve_transaction_network(&config, false).await.unwrap(),
316            NetworkVariant::Ethereum
317        );
318    }
319
320    #[cfg(all(feature = "base", not(feature = "optimism")))]
321    #[tokio::test]
322    async fn resolve_network_allows_rpc_without_optimism() {
323        let config =
324            Config { chain: Some(foundry_config::Chain::from_id(10)), ..Default::default() };
325        assert_eq!(
326            resolve_transaction_network(&config, false).await.unwrap(),
327            NetworkVariant::Ethereum
328        );
329    }
330
331    #[cfg(any(feature = "base", feature = "optimism"))]
332    #[tokio::test]
333    async fn resolve_network_still_defaults_unknown_chain_ids_to_ethereum() {
334        let config =
335            Config { chain: Some(foundry_config::Chain::from_id(u64::MAX)), ..Default::default() };
336        assert_eq!(
337            resolve_transaction_network(&config, false).await.unwrap(),
338            NetworkVariant::Ethereum
339        );
340    }
341}