From 4364e44c318c3deb3ce20d579721d8831288afca Mon Sep 17 00:00:00 2001 From: Anish Agnihotri Date: Mon, 20 Sep 2021 01:04:26 -0400 Subject: [PATCH] Seth: --to-dec --- dapptools/src/seth.rs | 3 +++ dapptools/src/seth_opts.rs | 3 +++ seth/src/lib.rs | 13 +++++++++++++ 3 files changed, 19 insertions(+) diff --git a/dapptools/src/seth.rs b/dapptools/src/seth.rs index 6d847fadbabe..5e318eb9f7b2 100644 --- a/dapptools/src/seth.rs +++ b/dapptools/src/seth.rs @@ -22,6 +22,9 @@ async fn main() -> eyre::Result<()> { Subcommands::ToBytes32 { bytes } => { println!("{}", SimpleSeth::to_bytes32(&bytes)?); } + Subcommands::ToDec { hexvalue } => { + println!("{}", SimpleSeth::to_dec(hexvalue)); + } Subcommands::ToFix { decimals, value } => { println!("{}", SimpleSeth::to_fix(unwrap_or_stdin(decimals)?, unwrap_or_stdin(value)?)); } diff --git a/dapptools/src/seth_opts.rs b/dapptools/src/seth_opts.rs index b542a2cfbe34..0e98e54f5e28 100644 --- a/dapptools/src/seth_opts.rs +++ b/dapptools/src/seth_opts.rs @@ -23,6 +23,9 @@ pub enum Subcommands { #[structopt(name = "--to-bytes32")] #[structopt(about = "left-pads a hex bytes string to 32 bytes)")] ToBytes32 { bytes: String }, + #[structopt(name = "--to-dec")] + #[structopt(about = "convert hex value into a decimal number")] + ToDec { hexvalue: String }, #[structopt(name = "--to-fix")] #[structopt(about = "convert integers into fixed point with specified decimals")] ToFix { decimals: Option, value: Option }, diff --git a/seth/src/lib.rs b/seth/src/lib.rs index 8506f0533678..01a1b06c975a 100644 --- a/seth/src/lib.rs +++ b/seth/src/lib.rs @@ -303,6 +303,19 @@ impl SimpleSeth { format!("0x{}", s) } + /// Converts hex input to decimal + /// + /// ``` + /// use seth::SimpleSeth as Seth; + /// + /// assert_eq!(424242, Seth::to_dec("0x67932")); + /// assert_eq!(1234, Seth::to_dec("0x4d2")); + /// ``` + pub fn to_dec(hex: String) -> u128 { + let hex_trimmed = hex.trim_start_matches("0x"); + u128::from_str_radix(&hex_trimmed, 16).expect("Could not parse hex") + } + /// Converts integers with specified decimals into fixed point numbers /// /// ```