Skip to main content

cast/cmd/
estimate.rs

1use super::{auth::confirm_and_build, print_result_line};
2use crate::{
3    tempo,
4    tx::{CastTxBuilder, SenderKind, read_only_sender},
5};
6use alloy_ens::NameOrAddress;
7use alloy_network::{Ethereum, Network};
8use alloy_primitives::U256;
9use alloy_provider::Provider;
10use alloy_rpc_types::BlockId;
11use clap::Parser;
12use eyre::Result;
13use foundry_cli::{
14    opts::{RpcOpts, TransactionOpts},
15    utils::{LoadConfig, parse_ether_value},
16};
17use foundry_common::{
18    FoundryTransactionBuilder, provider::ProviderBuilder,
19    tempo::configurable_account::prepare_request,
20};
21use foundry_config::Config;
22use foundry_wallets::{BrowserWalletOpts, WalletOpts};
23use std::{str::FromStr, sync::Arc};
24use tempo_alloy::TempoNetwork;
25
26#[cfg(feature = "base")]
27use base_common_network::Base;
28
29/// CLI arguments for `cast estimate`.
30#[derive(Debug, Parser)]
31pub struct EstimateArgs {
32    /// The destination of the transaction.
33    #[arg(value_parser = NameOrAddress::from_str)]
34    to: Option<NameOrAddress>,
35
36    /// The signature of the function to call.
37    sig: Option<String>,
38
39    /// The arguments of the function to call.
40    #[arg(allow_negative_numbers = true)]
41    args: Vec<String>,
42
43    /// The block height to query at.
44    ///
45    /// Can also be the tags earliest, finalized, safe, latest, or pending.
46    #[arg(long, short = 'B')]
47    block: Option<BlockId>,
48
49    /// Calculate the cost of a transaction using the network gas price.
50    ///
51    /// If not specified the amount of gas will be estimated.
52    #[arg(long)]
53    cost: bool,
54
55    #[command(flatten)]
56    wallet: WalletOpts,
57
58    #[command(flatten)]
59    browser: BrowserWalletOpts,
60
61    #[command(subcommand)]
62    command: Option<EstimateSubcommands>,
63
64    #[command(flatten)]
65    tx: TransactionOpts,
66
67    /// Skip the EIP-7702 authorization disclosure confirmation.
68    #[arg(long)]
69    force: bool,
70
71    #[command(flatten)]
72    rpc: RpcOpts,
73}
74
75#[derive(Debug, Parser)]
76pub enum EstimateSubcommands {
77    /// Estimate gas cost to deploy a smart contract
78    #[command(name = "--create")]
79    Create {
80        /// The bytecode of contract
81        code: String,
82
83        /// The signature of the constructor
84        sig: Option<String>,
85
86        /// Constructor arguments
87        #[arg(allow_negative_numbers = true)]
88        args: Vec<String>,
89
90        /// Ether to send in the transaction
91        ///
92        /// Either specified in wei, or as a string with a unit type:
93        ///
94        /// Examples: 1ether, 10gwei, 0.01ether
95        #[arg(long, value_parser = parse_ether_value)]
96        value: Option<U256>,
97    },
98}
99
100impl EstimateArgs {
101    pub async fn run(self) -> Result<()> {
102        let config = self.rpc.load_config()?;
103        let requires_tempo = self.tx.tempo.is_tempo() || self.tx.tempo.session_id()?.is_some();
104        let network = super::resolve_transaction_network(&config, requires_tempo).await?;
105        if network.is_tempo() {
106            return self.run_with_network::<TempoNetwork>(config).await;
107        }
108        #[cfg(feature = "base")]
109        if network.is_base() {
110            super::validate_base_transaction_options(&self.tx)?;
111            return self.run_with_network::<Base>(config).await;
112        }
113        self.run_with_network::<Ethereum>(config).await
114    }
115
116    async fn run_with_network<N: Network>(self, config: Config) -> Result<()>
117    where
118        N::TransactionRequest: FoundryTransactionBuilder<N>,
119    {
120        let Self {
121            to,
122            mut sig,
123            mut args,
124            mut tx,
125            block,
126            cost,
127            wallet,
128            browser,
129            force,
130            rpc: _,
131            command,
132        } = self;
133
134        let provider = ProviderBuilder::<N>::from_config(&config)?.build()?;
135        let chain_id = match config.chain {
136            Some(chain) => chain.id(),
137            None => provider.get_chain_id().await?,
138        };
139        // `cast send` rejects the same conflict.
140        if let (Some(account), Some(from)) = (tx.tempo.configurable_account, wallet.from) {
141            eyre::ensure!(
142                account == from,
143                "--tempo.configurable-account {account} does not match the sender {from}"
144            );
145        }
146        let as_access_key = tx.tempo.configurable_access_key.is_some();
147        let simulation_wallet = wallet.clone();
148        let (sender, is_browser) = read_only_sender::<N>(&browser, wallet, &tx, chain_id).await?;
149        // Share the resolved signer with the configurable account lookup.
150        let (sender, signer) = match sender {
151            SenderKind::OwnedSigner(signer) => (None, Some(Arc::new(*signer))),
152            sender => (Some(sender), None),
153        };
154        let mut sender = match (tx.tempo.configurable_account, sender) {
155            (Some(account), _) if !is_browser => account.into(),
156            (_, Some(sender)) => sender,
157            (_, None) => SenderKind::Signer(signer.as_deref().expect("an owned signer")),
158        };
159        // A configurable account sender is estimated with its owners' approvals.
160        let simulation = if is_browser || sender.address().is_zero() {
161            None
162        } else {
163            tempo::configurable_account_simulation::<N>(
164                &tx.tempo,
165                &config,
166                &simulation_wallet,
167                sender.address(),
168                signer.clone(),
169                block.unwrap_or_default(),
170            )
171            .await?
172        };
173
174        let code = if let Some(EstimateSubcommands::Create {
175            code,
176            sig: create_sig,
177            args: create_args,
178            value,
179        }) = command
180        {
181            sig = create_sig;
182            args = create_args;
183            if let Some(value) = value {
184                tx.value = Some(value);
185            }
186            Some(code)
187        } else {
188            None
189        };
190
191        let mut builder = CastTxBuilder::new(&provider, tx, &config)
192            .await?
193            .with_to(to)
194            .await?
195            .with_code_sig_and_args(code, sig, args)
196            .await?
197            .raw();
198        if let Some((account, simulation)) = simulation {
199            // A configurable access key signs for the sender as its `keyId`.
200            let from = if as_access_key {
201                builder.tx_mut().set_key_id(account);
202                sender.address()
203            } else {
204                sender = account.into();
205                account
206            };
207            prepare_request::<N>(builder.tx_mut(), from, simulation);
208        }
209        let Some(tx) = confirm_and_build(builder, sender, force, None, true).await? else {
210            return Ok(());
211        };
212
213        let tx = if is_browser { tx.browser_wallet_gas_estimation_request() } else { tx };
214        let gas = provider.estimate_gas(tx).block(block.unwrap_or_default()).await?;
215        if cost {
216            let cost = provider.get_gas_price().await? * gas as u128;
217            print_result_line(cost as f64 / 1e18)
218        } else {
219            print_result_line(gas)
220        }
221    }
222}