Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: parse unit logics #6713

Merged
merged 1 commit into from
Jan 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions crates/cast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1242,9 +1242,18 @@ impl SimpleCast {
.as_uint()
.wrap_err("Could not convert to uint")?
.0;
let unit: alloy_primitives::utils::Unit = unit.parse().wrap_err("Could not parse units")?;
let parsed = alloy_primitives::utils::ParseUnits::parse_units(&value.to_string(), unit)?;
Ok(parsed.to_string())
let unit = unit.parse().wrap_err("could not parse units")?;
let mut formatted = ParseUnits::U256(value).format_units(unit);

// Trim empty fractional part.
if let Some(dot) = formatted.find('.') {
let fractional = &formatted[dot + 1..];
if fractional.chars().all(|c: char| c == '0') {
formatted = formatted[..dot].to_string();
}
}

Ok(formatted)
}

/// Converts wei into an eth amount
Expand Down Expand Up @@ -1273,14 +1282,14 @@ impl SimpleCast {
/// ```
/// use cast::SimpleCast as Cast;
///
/// assert_eq!(Cast::to_wei("1", "wei")?, "1");
/// assert_eq!(Cast::to_wei("100", "gwei")?, "100000000000");
/// assert_eq!(Cast::to_wei("100", "eth")?, "100000000000000000000");
/// assert_eq!(Cast::to_wei("1000", "ether")?, "1000000000000000000000");
/// # Ok::<_, eyre::Report>(())
/// ```
pub fn to_wei(value: &str, unit: &str) -> Result<String> {
Ok(ParseUnits::parse_units(value, unit.parse()?)?.to_string())
let unit = unit.parse().wrap_err("could not parse units")?;
Ok(ParseUnits::parse_units(value, unit)?.to_string())
}

/// Decodes rlp encoded list with hex data
Expand Down
Loading