cast::revm::interpreter::primitives::alloy_primitives::utils

Function parse_units

pub fn parse_units<K, E>(
    amount: &str,
    units: K,
) -> Result<ParseUnits, UnitsError>
where K: TryInto<Unit, Error = E>, UnitsError: From<E>,
Expand description

Parses a decimal number and multiplies it with 10^units.

§Examples

use alloy_primitives::{utils::parse_units, U256};

let amount_in_eth = U256::from_str_radix("15230001000000000000", 10).unwrap();
let amount_in_gwei = U256::from_str_radix("15230001000", 10).unwrap();
let amount_in_wei = U256::from_str_radix("15230001000", 10).unwrap();
assert_eq!(amount_in_eth, parse_units("15.230001000000000000", "ether").unwrap().into());
assert_eq!(amount_in_gwei, parse_units("15.230001000000000000", "gwei").unwrap().into());
assert_eq!(amount_in_wei, parse_units("15230001000", "wei").unwrap().into());

Example of trying to parse decimal WEI, which should fail, as WEI is the smallest ETH denominator. 1 ETH = 10^18 WEI.

use alloy_primitives::{utils::parse_units, U256};
let amount_in_wei = U256::from_str_radix("15230001000", 10).unwrap();
assert_eq!(amount_in_wei, parse_units("15.230001000000000000", "wei").unwrap().into());