alloy_primitives/utils/
units.rs

1use crate::{ParseSignedError, I256, U256};
2use alloc::string::{String, ToString};
3use core::fmt;
4
5const MAX_U64_EXPONENT: u8 = 19;
6
7/// Converts the input to a U256 and converts from Ether to Wei.
8///
9/// # Examples
10///
11/// ```
12/// use alloy_primitives::{
13///     utils::{parse_ether, Unit},
14///     U256,
15/// };
16///
17/// let eth = Unit::ETHER.wei();
18/// assert_eq!(parse_ether("1").unwrap(), eth);
19/// ```
20pub fn parse_ether(eth: &str) -> Result<U256, UnitsError> {
21    ParseUnits::parse_units(eth, Unit::ETHER).map(Into::into)
22}
23
24/// Parses a decimal number and multiplies it with 10^units.
25///
26/// # Examples
27///
28/// ```
29/// use alloy_primitives::{utils::parse_units, U256};
30///
31/// let amount_in_eth = U256::from_str_radix("15230001000000000000", 10).unwrap();
32/// let amount_in_gwei = U256::from_str_radix("15230001000", 10).unwrap();
33/// let amount_in_wei = U256::from_str_radix("15230001000", 10).unwrap();
34/// assert_eq!(amount_in_eth, parse_units("15.230001000000000000", "ether").unwrap().into());
35/// assert_eq!(amount_in_gwei, parse_units("15.230001000000000000", "gwei").unwrap().into());
36/// assert_eq!(amount_in_wei, parse_units("15230001000", "wei").unwrap().into());
37/// ```
38///
39/// Example of trying to parse decimal WEI, which should fail, as WEI is the smallest
40/// ETH denominator. 1 ETH = 10^18 WEI.
41///
42/// ```should_panic
43/// use alloy_primitives::{utils::parse_units, U256};
44/// let amount_in_wei = U256::from_str_radix("15230001000", 10).unwrap();
45/// assert_eq!(amount_in_wei, parse_units("15.230001000000000000", "wei").unwrap().into());
46/// ```
47pub fn parse_units<K, E>(amount: &str, units: K) -> Result<ParseUnits, UnitsError>
48where
49    K: TryInto<Unit, Error = E>,
50    UnitsError: From<E>,
51{
52    ParseUnits::parse_units(amount, units.try_into()?)
53}
54
55/// Formats the given number of Wei as an Ether amount.
56///
57/// # Examples
58///
59/// ```
60/// use alloy_primitives::{utils::format_ether, U256};
61///
62/// let eth = format_ether(1395633240123456000_u128);
63/// assert_eq!(format_ether(1395633240123456000_u128), "1.395633240123456000");
64/// ```
65pub fn format_ether<T: Into<ParseUnits>>(amount: T) -> String {
66    amount.into().format_units(Unit::ETHER)
67}
68
69/// Formats the given number of Wei as the given unit.
70///
71/// # Examples
72///
73/// ```
74/// use alloy_primitives::{utils::format_units, U256};
75///
76/// let eth = U256::from_str_radix("1395633240123456000", 10).unwrap();
77/// assert_eq!(format_units(eth, "eth").unwrap(), "1.395633240123456000");
78///
79/// assert_eq!(format_units(i64::MIN, "gwei").unwrap(), "-9223372036.854775808");
80///
81/// assert_eq!(format_units(i128::MIN, 36).unwrap(), "-170.141183460469231731687303715884105728");
82/// ```
83pub fn format_units<T, K, E>(amount: T, units: K) -> Result<String, UnitsError>
84where
85    T: Into<ParseUnits>,
86    K: TryInto<Unit, Error = E>,
87    UnitsError: From<E>,
88{
89    units.try_into().map(|units| amount.into().format_units(units)).map_err(UnitsError::from)
90}
91
92/// Error type for [`Unit`]-related operations.
93#[derive(Debug)]
94pub enum UnitsError {
95    /// The provided units are not recognized.
96    InvalidUnit(String),
97    /// Overflow when parsing a signed number.
98    ParseSigned(ParseSignedError),
99}
100
101impl core::error::Error for UnitsError {
102    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
103        match self {
104            Self::InvalidUnit(_) => None,
105            Self::ParseSigned(e) => Some(e),
106        }
107    }
108}
109
110impl fmt::Display for UnitsError {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        match self {
113            Self::InvalidUnit(s) => write!(f, "{s:?} is not a valid unit"),
114            Self::ParseSigned(e) => e.fmt(f),
115        }
116    }
117}
118
119impl From<ruint::ParseError> for UnitsError {
120    fn from(value: ruint::ParseError) -> Self {
121        Self::ParseSigned(value.into())
122    }
123}
124
125impl From<ParseSignedError> for UnitsError {
126    fn from(value: ParseSignedError) -> Self {
127        Self::ParseSigned(value)
128    }
129}
130
131/// This enum holds the numeric types that a possible to be returned by `parse_units` and
132/// that are taken by `format_units`.
133#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
134pub enum ParseUnits {
135    /// Unsigned 256-bit integer.
136    U256(U256),
137    /// Signed 256-bit integer.
138    I256(I256),
139}
140
141impl From<ParseUnits> for U256 {
142    #[inline]
143    fn from(value: ParseUnits) -> Self {
144        value.get_absolute()
145    }
146}
147
148impl From<ParseUnits> for I256 {
149    #[inline]
150    fn from(value: ParseUnits) -> Self {
151        value.get_signed()
152    }
153}
154
155impl fmt::Display for ParseUnits {
156    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157        match self {
158            Self::U256(val) => val.fmt(f),
159            Self::I256(val) => val.fmt(f),
160        }
161    }
162}
163
164macro_rules! impl_from_integers {
165    ($convert:ident($($t:ty),* $(,)?)) => {$(
166        impl From<$t> for ParseUnits {
167            fn from(value: $t) -> Self {
168                Self::$convert($convert::try_from(value).unwrap())
169            }
170        }
171    )*}
172}
173
174impl_from_integers!(U256(u8, u16, u32, u64, u128, usize, U256));
175impl_from_integers!(I256(i8, i16, i32, i64, i128, isize, I256));
176
177macro_rules! impl_try_into_absolute {
178    ($($t:ty),* $(,)?) => { $(
179        impl TryFrom<ParseUnits> for $t {
180            type Error = <$t as TryFrom<U256>>::Error;
181
182            fn try_from(value: ParseUnits) -> Result<Self, Self::Error> {
183                <$t>::try_from(value.get_absolute())
184            }
185        }
186    )* };
187}
188
189impl_try_into_absolute!(u64, u128);
190
191impl ParseUnits {
192    /// Parses a decimal number and multiplies it with 10^units.
193    ///
194    /// See [`parse_units`] for more information.
195    #[allow(clippy::self_named_constructors)]
196    pub fn parse_units(amount: &str, unit: Unit) -> Result<Self, UnitsError> {
197        let exponent = unit.get() as usize;
198
199        let mut amount = amount.to_string();
200        let negative = amount.starts_with('-');
201        let dec_len = if let Some(di) = amount.find('.') {
202            amount.remove(di);
203            amount[di..].len()
204        } else {
205            0
206        };
207        let amount = amount.as_str();
208
209        if dec_len > exponent {
210            // Truncate the decimal part if it is longer than the exponent
211            let amount = &amount[..(amount.len() - (dec_len - exponent))];
212            if negative {
213                // Edge case: We have removed the entire number and only the negative sign is left.
214                //            Return 0 as a I256 given the input was signed.
215                if amount == "-" {
216                    Ok(Self::I256(I256::ZERO))
217                } else {
218                    Ok(Self::I256(I256::from_dec_str(amount)?))
219                }
220            } else {
221                Ok(Self::U256(U256::from_str_radix(amount, 10)?))
222            }
223        } else if negative {
224            // Edge case: Only a negative sign was given, return 0 as a I256 given the input was
225            // signed.
226            if amount == "-" {
227                Ok(Self::I256(I256::ZERO))
228            } else {
229                let mut n = I256::from_dec_str(amount)?;
230                n *= I256::try_from(10u8)
231                    .unwrap()
232                    .checked_pow(U256::from(exponent - dec_len))
233                    .ok_or(UnitsError::ParseSigned(ParseSignedError::IntegerOverflow))?;
234                Ok(Self::I256(n))
235            }
236        } else {
237            let mut a_uint = U256::from_str_radix(amount, 10)?;
238            a_uint *= U256::from(10)
239                .checked_pow(U256::from(exponent - dec_len))
240                .ok_or(UnitsError::ParseSigned(ParseSignedError::IntegerOverflow))?;
241            Ok(Self::U256(a_uint))
242        }
243    }
244
245    /// Formats the given number of Wei as the given unit.
246    ///
247    /// See [`format_units`] for more information.
248    pub fn format_units(&self, mut unit: Unit) -> String {
249        // Edge case: If the number is signed and the unit is the largest possible unit, we need to
250        //            subtract 1 from the unit to avoid overflow.
251        if self.is_signed() && unit == Unit::MAX {
252            unit = Unit::new(Unit::MAX.get() - 1).unwrap();
253        }
254        let units = unit.get() as usize;
255        let exp10 = unit.wei();
256
257        // TODO: `decimals` are formatted twice because U256 does not support alignment
258        // (`:0>width`).
259        match *self {
260            Self::U256(amount) => {
261                let integer = amount / exp10;
262                let decimals = (amount % exp10).to_string();
263                format!("{integer}.{decimals:0>units$}")
264            }
265            Self::I256(amount) => {
266                let exp10 = I256::from_raw(exp10);
267                let sign = if amount.is_negative() { "-" } else { "" };
268                let integer = (amount / exp10).twos_complement();
269                let decimals = ((amount % exp10).twos_complement()).to_string();
270                format!("{sign}{integer}.{decimals:0>units$}")
271            }
272        }
273    }
274
275    /// Returns `true` if the number is signed.
276    #[inline]
277    pub const fn is_signed(&self) -> bool {
278        matches!(self, Self::I256(_))
279    }
280
281    /// Returns `true` if the number is unsigned.
282    #[inline]
283    pub const fn is_unsigned(&self) -> bool {
284        matches!(self, Self::U256(_))
285    }
286
287    /// Returns `true` if the number is negative.
288    #[inline]
289    pub const fn is_negative(&self) -> bool {
290        match self {
291            Self::U256(_) => false,
292            Self::I256(n) => n.is_negative(),
293        }
294    }
295
296    /// Returns `true` if the number is positive.
297    #[inline]
298    pub const fn is_positive(&self) -> bool {
299        match self {
300            Self::U256(_) => true,
301            Self::I256(n) => n.is_positive(),
302        }
303    }
304
305    /// Returns `true` if the number is zero.
306    #[inline]
307    pub fn is_zero(&self) -> bool {
308        match self {
309            Self::U256(n) => n.is_zero(),
310            Self::I256(n) => n.is_zero(),
311        }
312    }
313
314    /// Returns the absolute value of the number.
315    #[inline]
316    pub const fn get_absolute(self) -> U256 {
317        match self {
318            Self::U256(n) => n,
319            Self::I256(n) => n.into_raw(),
320        }
321    }
322
323    /// Returns the signed value of the number.
324    #[inline]
325    pub const fn get_signed(self) -> I256 {
326        match self {
327            Self::U256(n) => I256::from_raw(n),
328            Self::I256(n) => n,
329        }
330    }
331}
332
333/// Ethereum unit. Always less than [`77`](Unit::MAX).
334#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
335pub struct Unit(u8);
336
337impl fmt::Display for Unit {
338    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
339        self.get().fmt(f)
340    }
341}
342
343impl TryFrom<u8> for Unit {
344    type Error = UnitsError;
345
346    fn try_from(value: u8) -> Result<Self, Self::Error> {
347        Self::new(value).ok_or_else(|| UnitsError::InvalidUnit(value.to_string()))
348    }
349}
350
351impl TryFrom<String> for Unit {
352    type Error = UnitsError;
353
354    fn try_from(value: String) -> Result<Self, Self::Error> {
355        value.parse()
356    }
357}
358
359impl<'a> TryFrom<&'a String> for Unit {
360    type Error = UnitsError;
361
362    fn try_from(value: &'a String) -> Result<Self, Self::Error> {
363        value.parse()
364    }
365}
366
367impl TryFrom<&str> for Unit {
368    type Error = UnitsError;
369
370    fn try_from(value: &str) -> Result<Self, Self::Error> {
371        value.parse()
372    }
373}
374
375impl core::str::FromStr for Unit {
376    type Err = UnitsError;
377
378    fn from_str(s: &str) -> Result<Self, Self::Err> {
379        if let Ok(unit) = crate::U8::from_str(s) {
380            return Self::new(unit.to()).ok_or_else(|| UnitsError::InvalidUnit(s.to_string()));
381        }
382
383        Ok(match s.to_ascii_lowercase().as_str() {
384            "eth" | "ether" => Self::ETHER,
385            "pwei" | "milli" | "milliether" | "finney" => Self::PWEI,
386            "twei" | "micro" | "microether" | "szabo" => Self::TWEI,
387            "gwei" | "nano" | "nanoether" | "shannon" => Self::GWEI,
388            "mwei" | "pico" | "picoether" | "lovelace" => Self::MWEI,
389            "kwei" | "femto" | "femtoether" | "babbage" => Self::KWEI,
390            "wei" => Self::WEI,
391            _ => return Err(UnitsError::InvalidUnit(s.to_string())),
392        })
393    }
394}
395
396impl Unit {
397    /// Wei is equivalent to 1 wei.
398    pub const WEI: Self = unsafe { Self::new_unchecked(0) };
399    #[allow(non_upper_case_globals)]
400    #[doc(hidden)]
401    #[deprecated(since = "0.5.0", note = "use `Unit::WEI` instead")]
402    pub const Wei: Self = Self::WEI;
403
404    /// Kwei is equivalent to 1e3 wei.
405    pub const KWEI: Self = unsafe { Self::new_unchecked(3) };
406    #[allow(non_upper_case_globals)]
407    #[doc(hidden)]
408    #[deprecated(since = "0.5.0", note = "use `Unit::KWEI` instead")]
409    pub const Kwei: Self = Self::KWEI;
410
411    /// Mwei is equivalent to 1e6 wei.
412    pub const MWEI: Self = unsafe { Self::new_unchecked(6) };
413    #[allow(non_upper_case_globals)]
414    #[doc(hidden)]
415    #[deprecated(since = "0.5.0", note = "use `Unit::MWEI` instead")]
416    pub const Mwei: Self = Self::MWEI;
417
418    /// Gwei is equivalent to 1e9 wei.
419    pub const GWEI: Self = unsafe { Self::new_unchecked(9) };
420    #[allow(non_upper_case_globals)]
421    #[doc(hidden)]
422    #[deprecated(since = "0.5.0", note = "use `Unit::GWEI` instead")]
423    pub const Gwei: Self = Self::GWEI;
424
425    /// Twei is equivalent to 1e12 wei.
426    pub const TWEI: Self = unsafe { Self::new_unchecked(12) };
427    #[allow(non_upper_case_globals)]
428    #[doc(hidden)]
429    #[deprecated(since = "0.5.0", note = "use `Unit::TWEI` instead")]
430    pub const Twei: Self = Self::TWEI;
431
432    /// Pwei is equivalent to 1e15 wei.
433    pub const PWEI: Self = unsafe { Self::new_unchecked(15) };
434    #[allow(non_upper_case_globals)]
435    #[doc(hidden)]
436    #[deprecated(since = "0.5.0", note = "use `Unit::PWEI` instead")]
437    pub const Pwei: Self = Self::PWEI;
438
439    /// Ether is equivalent to 1e18 wei.
440    pub const ETHER: Self = unsafe { Self::new_unchecked(18) };
441    #[allow(non_upper_case_globals)]
442    #[doc(hidden)]
443    #[deprecated(since = "0.5.0", note = "use `Unit::ETHER` instead")]
444    pub const Ether: Self = Self::ETHER;
445
446    /// The smallest unit.
447    pub const MIN: Self = Self::WEI;
448    /// The largest unit.
449    pub const MAX: Self = unsafe { Self::new_unchecked(77) };
450
451    /// Creates a new `Unit` instance, checking for overflow.
452    #[inline]
453    pub const fn new(units: u8) -> Option<Self> {
454        if units <= Self::MAX.get() {
455            // SAFETY: `units` is contained in the valid range.
456            Some(unsafe { Self::new_unchecked(units) })
457        } else {
458            None
459        }
460    }
461
462    /// Creates a new `Unit` instance.
463    ///
464    /// # Safety
465    ///
466    /// `x` must be less than [`Unit::MAX`].
467    #[inline]
468    pub const unsafe fn new_unchecked(x: u8) -> Self {
469        Self(x)
470    }
471
472    /// Returns `10^self`, which is the number of Wei in this unit.
473    ///
474    /// # Examples
475    ///
476    /// ```
477    /// use alloy_primitives::{utils::Unit, U256};
478    ///
479    /// assert_eq!(U256::from(1u128), Unit::WEI.wei());
480    /// assert_eq!(U256::from(1_000u128), Unit::KWEI.wei());
481    /// assert_eq!(U256::from(1_000_000u128), Unit::MWEI.wei());
482    /// assert_eq!(U256::from(1_000_000_000u128), Unit::GWEI.wei());
483    /// assert_eq!(U256::from(1_000_000_000_000u128), Unit::TWEI.wei());
484    /// assert_eq!(U256::from(1_000_000_000_000_000u128), Unit::PWEI.wei());
485    /// assert_eq!(U256::from(1_000_000_000_000_000_000u128), Unit::ETHER.wei());
486    /// ```
487    #[inline]
488    pub fn wei(self) -> U256 {
489        if self.get() <= MAX_U64_EXPONENT {
490            self.wei_const()
491        } else {
492            U256::from(10u8).pow(U256::from(self.get()))
493        }
494    }
495
496    /// Returns `10^self`, which is the number of Wei in this unit.
497    ///
498    /// # Panics
499    ///
500    /// Panics if `10^self` would overflow a `u64` (`self > 19`). If this can happen, use
501    /// [`wei`](Self::wei) instead.
502    #[inline]
503    pub const fn wei_const(self) -> U256 {
504        if self.get() > MAX_U64_EXPONENT {
505            panic!("overflow")
506        }
507        U256::from_limbs([10u64.pow(self.get() as u32), 0, 0, 0])
508    }
509
510    /// Returns the numeric value of the unit.
511    #[inline]
512    pub const fn get(self) -> u8 {
513        self.0
514    }
515
516    #[doc(hidden)]
517    #[deprecated(since = "0.5.0", note = "use `get` instead")]
518    pub const fn as_num(&self) -> u8 {
519        self.get()
520    }
521}
522
523#[cfg(test)]
524mod tests {
525    use super::*;
526
527    #[test]
528    fn unit_values() {
529        assert_eq!(Unit::WEI.get(), 0);
530        assert_eq!(Unit::KWEI.get(), 3);
531        assert_eq!(Unit::MWEI.get(), 6);
532        assert_eq!(Unit::GWEI.get(), 9);
533        assert_eq!(Unit::TWEI.get(), 12);
534        assert_eq!(Unit::PWEI.get(), 15);
535        assert_eq!(Unit::ETHER.get(), 18);
536        assert_eq!(Unit::new(10).unwrap().get(), 10);
537        assert_eq!(Unit::new(20).unwrap().get(), 20);
538    }
539
540    #[test]
541    fn unit_wei() {
542        let assert = |unit: Unit| {
543            let wei = unit.wei();
544            assert_eq!(wei.to::<u128>(), 10u128.pow(unit.get() as u32));
545            assert_eq!(wei, U256::from(10u8).pow(U256::from(unit.get())));
546        };
547        assert(Unit::WEI);
548        assert(Unit::KWEI);
549        assert(Unit::MWEI);
550        assert(Unit::GWEI);
551        assert(Unit::TWEI);
552        assert(Unit::PWEI);
553        assert(Unit::ETHER);
554        assert(Unit::new(10).unwrap());
555        assert(Unit::new(20).unwrap());
556    }
557
558    #[test]
559    fn parse() {
560        assert_eq!(Unit::try_from("wei").unwrap(), Unit::WEI);
561        assert_eq!(Unit::try_from("kwei").unwrap(), Unit::KWEI);
562        assert_eq!(Unit::try_from("mwei").unwrap(), Unit::MWEI);
563        assert_eq!(Unit::try_from("gwei").unwrap(), Unit::GWEI);
564        assert_eq!(Unit::try_from("twei").unwrap(), Unit::TWEI);
565        assert_eq!(Unit::try_from("pwei").unwrap(), Unit::PWEI);
566        assert_eq!(Unit::try_from("ether").unwrap(), Unit::ETHER);
567    }
568
569    #[test]
570    fn wei_in_ether() {
571        assert_eq!(Unit::ETHER.wei(), U256::from(1e18 as u64));
572    }
573
574    #[test]
575    fn test_format_ether_unsigned() {
576        let eth = format_ether(Unit::ETHER.wei());
577        assert_eq!(eth.parse::<f64>().unwrap() as u64, 1);
578
579        let eth = format_ether(1395633240123456000_u128);
580        assert_eq!(eth.parse::<f64>().unwrap(), 1.395633240123456);
581
582        let eth = format_ether(U256::from_str_radix("1395633240123456000", 10).unwrap());
583        assert_eq!(eth.parse::<f64>().unwrap(), 1.395633240123456);
584
585        let eth = format_ether(U256::from_str_radix("1395633240123456789", 10).unwrap());
586        assert_eq!(eth, "1.395633240123456789");
587
588        let eth = format_ether(U256::from_str_radix("1005633240123456789", 10).unwrap());
589        assert_eq!(eth, "1.005633240123456789");
590
591        let eth = format_ether(u16::MAX);
592        assert_eq!(eth, "0.000000000000065535");
593
594        // Note: This covers usize on 32 bit systems.
595        let eth = format_ether(u32::MAX);
596        assert_eq!(eth, "0.000000004294967295");
597
598        // Note: This covers usize on 64 bit systems.
599        let eth = format_ether(u64::MAX);
600        assert_eq!(eth, "18.446744073709551615");
601    }
602
603    #[test]
604    fn test_format_ether_signed() {
605        let eth = format_ether(I256::from_dec_str("-1395633240123456000").unwrap());
606        assert_eq!(eth.parse::<f64>().unwrap(), -1.395633240123456);
607
608        let eth = format_ether(I256::from_dec_str("-1395633240123456789").unwrap());
609        assert_eq!(eth, "-1.395633240123456789");
610
611        let eth = format_ether(I256::from_dec_str("1005633240123456789").unwrap());
612        assert_eq!(eth, "1.005633240123456789");
613
614        let eth = format_ether(i8::MIN);
615        assert_eq!(eth, "-0.000000000000000128");
616
617        let eth = format_ether(i8::MAX);
618        assert_eq!(eth, "0.000000000000000127");
619
620        let eth = format_ether(i16::MIN);
621        assert_eq!(eth, "-0.000000000000032768");
622
623        // Note: This covers isize on 32 bit systems.
624        let eth = format_ether(i32::MIN);
625        assert_eq!(eth, "-0.000000002147483648");
626
627        // Note: This covers isize on 64 bit systems.
628        let eth = format_ether(i64::MIN);
629        assert_eq!(eth, "-9.223372036854775808");
630    }
631
632    #[test]
633    fn test_format_units_unsigned() {
634        let gwei_in_ether = format_units(Unit::ETHER.wei(), 9).unwrap();
635        assert_eq!(gwei_in_ether.parse::<f64>().unwrap() as u64, 1e9 as u64);
636
637        let eth = format_units(Unit::ETHER.wei(), "ether").unwrap();
638        assert_eq!(eth.parse::<f64>().unwrap() as u64, 1);
639
640        let eth = format_units(1395633240123456000_u128, "ether").unwrap();
641        assert_eq!(eth.parse::<f64>().unwrap(), 1.395633240123456);
642
643        let eth = format_units(U256::from_str_radix("1395633240123456000", 10).unwrap(), "ether")
644            .unwrap();
645        assert_eq!(eth.parse::<f64>().unwrap(), 1.395633240123456);
646
647        let eth = format_units(U256::from_str_radix("1395633240123456789", 10).unwrap(), "ether")
648            .unwrap();
649        assert_eq!(eth, "1.395633240123456789");
650
651        let eth = format_units(U256::from_str_radix("1005633240123456789", 10).unwrap(), "ether")
652            .unwrap();
653        assert_eq!(eth, "1.005633240123456789");
654
655        let eth = format_units(u8::MAX, 4).unwrap();
656        assert_eq!(eth, "0.0255");
657
658        let eth = format_units(u16::MAX, "ether").unwrap();
659        assert_eq!(eth, "0.000000000000065535");
660
661        // Note: This covers usize on 32 bit systems.
662        let eth = format_units(u32::MAX, 18).unwrap();
663        assert_eq!(eth, "0.000000004294967295");
664
665        // Note: This covers usize on 64 bit systems.
666        let eth = format_units(u64::MAX, "gwei").unwrap();
667        assert_eq!(eth, "18446744073.709551615");
668
669        let eth = format_units(u128::MAX, 36).unwrap();
670        assert_eq!(eth, "340.282366920938463463374607431768211455");
671
672        let eth = format_units(U256::MAX, 77).unwrap();
673        assert_eq!(
674            eth,
675            "1.15792089237316195423570985008687907853269984665640564039457584007913129639935"
676        );
677
678        let _err = format_units(U256::MAX, 78).unwrap_err();
679        let _err = format_units(U256::MAX, 79).unwrap_err();
680    }
681
682    #[test]
683    fn test_format_units_signed() {
684        let eth =
685            format_units(I256::from_dec_str("-1395633240123456000").unwrap(), "ether").unwrap();
686        assert_eq!(eth.parse::<f64>().unwrap(), -1.395633240123456);
687
688        let eth =
689            format_units(I256::from_dec_str("-1395633240123456789").unwrap(), "ether").unwrap();
690        assert_eq!(eth, "-1.395633240123456789");
691
692        let eth =
693            format_units(I256::from_dec_str("1005633240123456789").unwrap(), "ether").unwrap();
694        assert_eq!(eth, "1.005633240123456789");
695
696        let eth = format_units(i8::MIN, 4).unwrap();
697        assert_eq!(eth, "-0.0128");
698        assert_eq!(eth.parse::<f64>().unwrap(), -0.0128_f64);
699
700        let eth = format_units(i8::MAX, 4).unwrap();
701        assert_eq!(eth, "0.0127");
702        assert_eq!(eth.parse::<f64>().unwrap(), 0.0127);
703
704        let eth = format_units(i16::MIN, "ether").unwrap();
705        assert_eq!(eth, "-0.000000000000032768");
706
707        // Note: This covers isize on 32 bit systems.
708        let eth = format_units(i32::MIN, 18).unwrap();
709        assert_eq!(eth, "-0.000000002147483648");
710
711        // Note: This covers isize on 64 bit systems.
712        let eth = format_units(i64::MIN, "gwei").unwrap();
713        assert_eq!(eth, "-9223372036.854775808");
714
715        let eth = format_units(i128::MIN, 36).unwrap();
716        assert_eq!(eth, "-170.141183460469231731687303715884105728");
717
718        let eth = format_units(I256::MIN, 76).unwrap();
719        let min = "-5.7896044618658097711785492504343953926634992332820282019728792003956564819968";
720        assert_eq!(eth, min);
721        // doesn't error
722        let eth = format_units(I256::MIN, 77).unwrap();
723        assert_eq!(eth, min);
724
725        let _err = format_units(I256::MIN, 78).unwrap_err();
726        let _err = format_units(I256::MIN, 79).unwrap_err();
727    }
728
729    #[test]
730    fn parse_large_units() {
731        let decimals = 27u8;
732        let val = "10.55";
733
734        let n: U256 = parse_units(val, decimals).unwrap().into();
735        assert_eq!(n.to_string(), "10550000000000000000000000000");
736    }
737
738    #[test]
739    fn test_parse_units() {
740        let gwei: U256 = parse_units("1.5", 9).unwrap().into();
741        assert_eq!(gwei, U256::from(15e8 as u64));
742
743        let token: U256 = parse_units("1163.56926418", 8).unwrap().into();
744        assert_eq!(token, U256::from(116356926418u64));
745
746        let eth_dec_float: U256 = parse_units("1.39563324", "ether").unwrap().into();
747        assert_eq!(eth_dec_float, U256::from_str_radix("1395633240000000000", 10).unwrap());
748
749        let eth_dec_string: U256 = parse_units("1.39563324", "ether").unwrap().into();
750        assert_eq!(eth_dec_string, U256::from_str_radix("1395633240000000000", 10).unwrap());
751
752        let eth: U256 = parse_units("1", "ether").unwrap().into();
753        assert_eq!(eth, Unit::ETHER.wei());
754
755        let val: U256 = parse_units("2.3", "ether").unwrap().into();
756        assert_eq!(val, U256::from_str_radix("2300000000000000000", 10).unwrap());
757
758        let n: U256 = parse_units(".2", 2).unwrap().into();
759        assert_eq!(n, U256::from(20), "leading dot");
760
761        let n: U256 = parse_units("333.21", 2).unwrap().into();
762        assert_eq!(n, U256::from(33321), "trailing dot");
763
764        let n: U256 = parse_units("98766", 16).unwrap().into();
765        assert_eq!(n, U256::from_str_radix("987660000000000000000", 10).unwrap(), "no dot");
766
767        let n: U256 = parse_units("3_3_0", 3).unwrap().into();
768        assert_eq!(n, U256::from(330000), "underscore");
769
770        let n: U256 = parse_units("330", 0).unwrap().into();
771        assert_eq!(n, U256::from(330), "zero decimals");
772
773        let n: U256 = parse_units(".1234", 3).unwrap().into();
774        assert_eq!(n, U256::from(123), "truncate too many decimals");
775
776        assert!(parse_units("1", 80).is_err(), "overflow");
777
778        let two_e30 = U256::from(2) * U256::from_limbs([0x4674edea40000000, 0xc9f2c9cd0, 0x0, 0x0]);
779        let n: U256 = parse_units("2", 30).unwrap().into();
780        assert_eq!(n, two_e30, "2e30");
781
782        let n: U256 = parse_units(".33_319_2", 0).unwrap().into();
783        assert_eq!(n, U256::ZERO, "mix");
784
785        let n: U256 = parse_units("", 3).unwrap().into();
786        assert_eq!(n, U256::ZERO, "empty");
787    }
788
789    #[test]
790    fn test_signed_parse_units() {
791        let gwei: I256 = parse_units("-1.5", 9).unwrap().into();
792        assert_eq!(gwei.as_i64(), -15e8 as i64);
793
794        let token: I256 = parse_units("-1163.56926418", 8).unwrap().into();
795        assert_eq!(token.as_i64(), -116356926418);
796
797        let eth_dec_float: I256 = parse_units("-1.39563324", "ether").unwrap().into();
798        assert_eq!(eth_dec_float, I256::from_dec_str("-1395633240000000000").unwrap());
799
800        let eth_dec_string: I256 = parse_units("-1.39563324", "ether").unwrap().into();
801        assert_eq!(eth_dec_string, I256::from_dec_str("-1395633240000000000").unwrap());
802
803        let eth: I256 = parse_units("-1", "ether").unwrap().into();
804        assert_eq!(eth, I256::from_raw(Unit::ETHER.wei()) * I256::MINUS_ONE);
805
806        let val: I256 = parse_units("-2.3", "ether").unwrap().into();
807        assert_eq!(val, I256::from_dec_str("-2300000000000000000").unwrap());
808
809        let n: I256 = parse_units("-.2", 2).unwrap().into();
810        assert_eq!(n, I256::try_from(-20).unwrap(), "leading dot");
811
812        let n: I256 = parse_units("-333.21", 2).unwrap().into();
813        assert_eq!(n, I256::try_from(-33321).unwrap(), "trailing dot");
814
815        let n: I256 = parse_units("-98766", 16).unwrap().into();
816        assert_eq!(n, I256::from_dec_str("-987660000000000000000").unwrap(), "no dot");
817
818        let n: I256 = parse_units("-3_3_0", 3).unwrap().into();
819        assert_eq!(n, I256::try_from(-330000).unwrap(), "underscore");
820
821        let n: I256 = parse_units("-330", 0).unwrap().into();
822        assert_eq!(n, I256::try_from(-330).unwrap(), "zero decimals");
823
824        let n: I256 = parse_units("-.1234", 3).unwrap().into();
825        assert_eq!(n, I256::try_from(-123).unwrap(), "truncate too many decimals");
826
827        assert!(parse_units("-1", 80).is_err(), "overflow");
828
829        let two_e30 = I256::try_from(-2).unwrap()
830            * I256::from_raw(U256::from_limbs([0x4674edea40000000, 0xc9f2c9cd0, 0x0, 0x0]));
831        let n: I256 = parse_units("-2", 30).unwrap().into();
832        assert_eq!(n, two_e30, "-2e30");
833
834        let n: I256 = parse_units("-.33_319_2", 0).unwrap().into();
835        assert_eq!(n, I256::ZERO, "mix");
836
837        let n: I256 = parse_units("-", 3).unwrap().into();
838        assert_eq!(n, I256::ZERO, "empty");
839    }
840}