diff --git a/dapptools/src/seth.rs b/dapptools/src/seth.rs index e1f1941abae3..11aff3e05ec9 100644 --- a/dapptools/src/seth.rs +++ b/dapptools/src/seth.rs @@ -25,6 +25,9 @@ async fn main() -> eyre::Result<()> { Subcommands::ToFix { decimals, value } => { println!("{}", SimpleSeth::to_fix(unwrap_or_stdin(decimals)?, unwrap_or_stdin(value)?)); } + Subcommands::ToWei { value, unit } => { + println!("{}", SimpleSeth::to_wei(unwrap_or_stdin(value)?, unit.unwrap_or(String::from("wei")))); + } Subcommands::Block { rpc_url, block, diff --git a/dapptools/src/seth_opts.rs b/dapptools/src/seth_opts.rs index 02b447c459f4..d1357292bd40 100644 --- a/dapptools/src/seth_opts.rs +++ b/dapptools/src/seth_opts.rs @@ -26,6 +26,9 @@ pub enum Subcommands { #[structopt(name = "--to-fix")] #[structopt(about = "convert integers into fixed point with specified decimals")] ToFix { decimals: Option, value: Option }, + #[structopt(name = "--to-wei")] + #[structopt(about = "convert an ETH amount into wei")] + ToWei { value: Option, unit: Option }, #[structopt(name = "block")] #[structopt( about = "Prints information about . If is given, print only the value of that field" diff --git a/seth/src/lib.rs b/seth/src/lib.rs index 65bf4066a95b..fbe8269baa60 100644 --- a/seth/src/lib.rs +++ b/seth/src/lib.rs @@ -202,7 +202,7 @@ where field: String ) -> Result { let block = block.into(); - let base_fee_hex = Seth::block( + let block_field = Seth::block( &self, block, false, @@ -211,7 +211,7 @@ where false ).await?; Ok(U256::from_str_radix( - strip_0x(&base_fee_hex), + strip_0x(&block_field), 16 ).expect("Unable to convert hexadecimal to U256")) } @@ -339,6 +339,25 @@ impl SimpleSeth { format!("{:#x}", u) } + /// Converts an eth amount into wei + /// + /// ``` + /// use seth::SimpleSeth as Seth; + /// + /// assert_eq!(Seth::to_wei(1, "".to_string()), "1"); + /// assert_eq!(Seth::to_wei(100, "gwei".to_string()), "100000000000"); + /// assert_eq!(Seth::to_wei(100, "eth".to_string()), "100000000000000000000"); + /// assert_eq!(Seth::to_wei(1000, "ether".to_string()), "1000000000000000000000"); + /// ``` + pub fn to_wei(value: u128, unit: String) -> String { + let value = value.to_string(); + match &unit[..] { + "gwei" => format!("{:0<1$}", value, 9 + value.len()), + "eth" | "ether" => format!("{:0<1$}", value, 18 + value.len()), + _ => value, + } + } + /// Converts an Ethereum address to its checksum format /// according to [EIP-55](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md) ///