Skip to content

Commit

Permalink
Seth: --to-fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Anish-Agnihotri committed Sep 19, 2021
1 parent f9cde71 commit 425b884
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
3 changes: 3 additions & 0 deletions dapptools/src/seth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 3 additions & 0 deletions dapptools/src/seth_opts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u128>, value: Option<u128> },
#[structopt(name = "block")]
#[structopt(
about = "Prints information about <block>. If <field> is given, print only the value of that field"
Expand Down
25 changes: 25 additions & 0 deletions seth/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
///
/// ```
Expand Down

0 comments on commit 425b884

Please sign in to comment.