Skip to content

Commit

Permalink
Seth: --to-wei
Browse files Browse the repository at this point in the history
  • Loading branch information
Anish-Agnihotri committed Sep 20, 2021
1 parent b6b5953 commit 3314129
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
3 changes: 3 additions & 0 deletions dapptools/src/seth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
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 @@ -26,6 +26,9 @@ pub enum Subcommands {
#[structopt(name = "--to-fix")]
#[structopt(about = "convert integers into fixed point with specified decimals")]
ToFix { decimals: Option<u128>, value: Option<u128> },
#[structopt(name = "--to-wei")]
#[structopt(about = "convert an ETH amount into wei")]
ToWei { value: Option<u128>, unit: Option<String> },
#[structopt(name = "block")]
#[structopt(
about = "Prints information about <block>. If <field> is given, print only the value of that field"
Expand Down
23 changes: 21 additions & 2 deletions seth/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ where
field: String
) -> Result<U256> {
let block = block.into();
let base_fee_hex = Seth::block(
let block_field = Seth::block(
&self,
block,
false,
Expand All @@ -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"))
}
Expand Down Expand Up @@ -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)
///
Expand Down

0 comments on commit 3314129

Please sign in to comment.