Skip to content

Commit

Permalink
fix: port to_unit impl from master
Browse files Browse the repository at this point in the history
  • Loading branch information
Evalir committed Jan 5, 2024
1 parent ec829e7 commit bc4c1b3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
30 changes: 26 additions & 4 deletions crates/cast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1241,11 +1241,33 @@ impl SimpleCast {
pub fn to_unit(value: &str, unit: &str) -> Result<String> {
let value = DynSolType::coerce_str(&DynSolType::Uint(256), value)?
.as_uint()
.wrap_err("could not convert to 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())

Ok(match unit {
"eth" | "ether" => foundry_common::units::format_units(value, 18)?
.trim_end_matches(".000000000000000000")
.to_string(),
"milli" | "milliether" => foundry_common::units::format_units(value, 15)?
.trim_end_matches(".000000000000000")
.to_string(),
"micro" | "microether" => foundry_common::units::format_units(value, 12)?
.trim_end_matches(".000000000000")
.to_string(),
"gwei" | "nano" | "nanoether" => foundry_common::units::format_units(value, 9)?
.trim_end_matches(".000000000")
.to_string(),
"mwei" | "mega" | "megaether" => foundry_common::units::format_units(value, 6)?
.trim_end_matches(".000000")
.to_string(),
"kwei" | "kilo" | "kiloether" => {
foundry_common::units::format_units(value, 3)?.trim_end_matches(".000").to_string()
}
"wei" => {
foundry_common::units::format_units(value, 0)?.trim_end_matches(".0").to_string()
}
_ => eyre::bail!("invalid unit: \"{}\"", unit),
})
}

/// Converts wei into an eth amount
Expand Down
1 change: 1 addition & 0 deletions crates/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub mod term;
pub mod traits;
pub mod transactions;
pub mod types;
pub mod units;

pub use constants::*;
pub use contracts::*;
Expand Down

0 comments on commit bc4c1b3

Please sign in to comment.