Skip to content

Commit 268dcb2

Browse files
committed
feat(cast): add --cost to cast estimate the eth cost at current gas price
1 parent 41c6653 commit 268dcb2

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

crates/cast/bin/cmd/estimate.rs

+15-2
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ pub struct EstimateArgs {
3131
#[arg(long, short = 'B')]
3232
block: Option<BlockId>,
3333

34+
/// Calculate the cost of a transaction using the network gas price.
35+
///
36+
/// If not specified the amount of gas will be estimated.
37+
#[arg(long)]
38+
cost: bool,
39+
3440
#[command(subcommand)]
3541
command: Option<EstimateSubcommands>,
3642

@@ -67,7 +73,7 @@ pub enum EstimateSubcommands {
6773

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

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

102108
let gas = provider.estimate_gas(&tx).block(block.unwrap_or_default()).await?;
103-
sh_println!("{gas}")?;
109+
if cost {
110+
let gas_price_wei = provider.get_gas_price().await?;
111+
let cost = gas_price_wei * gas as u128;
112+
let cost_eth = cost as f64 / 1e18;
113+
sh_println!("{cost_eth}")?;
114+
} else {
115+
sh_println!("{gas}")?;
116+
}
104117
Ok(())
105118
}
106119
}

crates/cast/tests/cli/main.rs

+25
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,31 @@ casttest!(estimate_function_gas, |_prj, cmd| {
522522
assert!(output.ge(&0));
523523
});
524524

525+
// tests that `cast estimate --cost` is working correctly.
526+
casttest!(estimate_function_cost, |_prj, cmd| {
527+
let eth_rpc_url = next_http_rpc_endpoint();
528+
529+
// ensure we get a positive non-error value for cost estimate
530+
let output: f64 = cmd
531+
.args([
532+
"estimate",
533+
"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", // vitalik.eth
534+
"--value",
535+
"100",
536+
"deposit()",
537+
"--rpc-url",
538+
eth_rpc_url.as_str(),
539+
"--cost",
540+
])
541+
.assert_success()
542+
.get_output()
543+
.stdout_lossy()
544+
.trim()
545+
.parse()
546+
.unwrap();
547+
assert!(output.ge(&0.0));
548+
});
549+
525550
// tests that `cast estimate --create` is working correctly.
526551
casttest!(estimate_contract_deploy_gas, |_prj, cmd| {
527552
let eth_rpc_url = next_http_rpc_endpoint();

0 commit comments

Comments
 (0)