From 425b88425b6d3ddf75f32973184e032d6c44dcfd Mon Sep 17 00:00:00 2001 From: Anish Agnihotri Date: Sun, 19 Sep 2021 17:10:44 -0400 Subject: [PATCH] Seth: --to-fix --- dapptools/src/seth.rs | 3 +++ dapptools/src/seth_opts.rs | 3 +++ seth/src/lib.rs | 25 +++++++++++++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/dapptools/src/seth.rs b/dapptools/src/seth.rs index 8da45e42f2af..6d898c54ea53 100644 --- a/dapptools/src/seth.rs +++ b/dapptools/src/seth.rs @@ -28,6 +28,9 @@ async fn main() -> eyre::Result<()> { Subcommands::ToBytes32 { bytes } => { println!("{}", SimpleSeth::to_bytes32(&bytes)?); } + Subcommands::ToFix { decimals, value } => { + println!("{}", SimpleSeth::to_fix(unwrap_or_stdin(decimals)?, unwrap_or_stdin(value)?)); + } Subcommands::Block { rpc_url, block, diff --git a/dapptools/src/seth_opts.rs b/dapptools/src/seth_opts.rs index c3b6871c6cd9..e897a7b2d051 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-fix")] + #[structopt(about = "convert integers into fixed point with specified decimals")] + ToFix { decimals: Option, value: 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 815220ce8dcd..94a7848bdc5f 100644 --- a/seth/src/lib.rs +++ b/seth/src/lib.rs @@ -211,6 +211,31 @@ impl SimpleSeth { let s: String = s.as_bytes().to_hex(); format!("0x{}", s) } + + /// Converts integers with specified decimals into fixed point numbers + /// + /// ``` + /// use seth::SimpleSeth as Seth; + /// + /// assert_eq!(Seth::to_fix(0, 10), "10."); + /// assert_eq!(Seth::to_fix(1, 10), "1.0"); + /// assert_eq!(Seth::to_fix(2, 10), "0.10"); + /// assert_eq!(Seth::to_fix(3, 10), "0.010"); + /// ``` + pub fn to_fix(decimals: u128, value: u128) -> String { + let mut value: String = value.to_string(); + let decimals = decimals as usize; + + if decimals >= value.len() { + // {0}.{0 * (number_of_decimals - value.len())}{value} + format!("0.{:0>1$}", value, decimals) + } else { + // Insert decimal at -idx (i.e 1 => decimal idx = -1) + value.insert(value.len() - decimals, '.'); + value + } + } + /// Converts decimal input to hex /// /// ```