Skip to content

Commit

Permalink
feat(cast): add --cost to cast estimate the eth cost at current gas p…
Browse files Browse the repository at this point in the history
…rice
  • Loading branch information
0xvv committed Jan 15, 2025
1 parent 41c6653 commit d81f453
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
17 changes: 15 additions & 2 deletions crates/cast/bin/cmd/estimate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ pub struct EstimateArgs {
#[arg(long, short = 'B')]
block: Option<BlockId>,

/// Calculate the cost of a transaction using the network gas price.
///
/// If not specified the amount of gas will be estimated.
#[arg(long)]
cost: bool,

#[command(subcommand)]
command: Option<EstimateSubcommands>,

Expand Down Expand Up @@ -67,7 +73,7 @@ pub enum EstimateSubcommands {

impl EstimateArgs {
pub async fn run(self) -> Result<()> {
let Self { to, mut sig, mut args, mut tx, block, eth, command } = self;
let Self { to, mut sig, mut args, mut tx, block, cost, eth, command } = self;

let config = Config::from(&eth);
let provider = utils::get_provider(&config)?;
Expand Down Expand Up @@ -100,7 +106,14 @@ impl EstimateArgs {
.await?;

let gas = provider.estimate_gas(&tx).block(block.unwrap_or_default()).await?;
sh_println!("{gas}")?;
if cost {
let gas_price_wei = provider.get_gas_price().await?;
let cost = gas_price_wei * gas as u128;
let cost_eth = cost as f64 / 1e18;
sh_println!("{cost_eth}")?;
} else {
sh_println!("{gas}")?;
}
Ok(())
}
}
Expand Down
24 changes: 24 additions & 0 deletions crates/cast/tests/cli/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,30 @@ casttest!(estimate_function_gas, |_prj, cmd| {
assert!(output.ge(&0));
});

// tests that `cast estimate --cost` is working correctly.
casttest!(estimate_function_cost, |_prj, cmd| {
let eth_rpc_url = next_http_rpc_endpoint();

// ensure we get a positive non-error value for cost estimate
let output: f64 = cmd
.args([
"estimate",
"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", // vitalik.eth
"--value",
"100",
"deposit()",
"--rpc-url",
eth_rpc_url.as_str()
])
.assert_success()
.get_output()
.stdout_lossy()
.trim()
.parse()
.unwrap();
assert!(output.ge(&0.0));
});

// tests that `cast estimate --create` is working correctly.
casttest!(estimate_contract_deploy_gas, |_prj, cmd| {
let eth_rpc_url = next_http_rpc_endpoint();
Expand Down

0 comments on commit d81f453

Please sign in to comment.