Skip to main content

df_hyperliquid_core/utils/
units.rs

1//! Amounts an action carries as whole integers: USDC in millionths
2//! (`vaultTransfer`, `subAccountTransfer`), HYPE in 1e8 (`cDeposit`,
3//! `tokenDelegate`). The integer is what is signed, so it is made here, once.
4
5use crate::utils::dec::{Dec, Round};
6
7/// USDC's decimals on the perp side and on Arbitrum: millionths.
8pub const USDC_DECIMALS: u32 = 6;
9
10/// HYPE on HyperCore counts in 1e8: what `wei` means in staking and delegation.
11pub const HYPE_DECIMALS: u32 = 8;
12
13/// Why an amount has no integer form to sign.
14#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
15#[non_exhaustive]
16pub enum BadUnits {
17    /// Zero or negative, or cut to zero units; holds the amount.
18    #[error("{0} is not a positive amount")]
19    NotPositive(Dec),
20    /// [`exact_units`] was given an amount finer than the places allowed.
21    #[error("{value} has more than {places} decimal places")]
22    TooFine {
23        /// The amount given.
24        value: Dec,
25        /// The most places allowed.
26        places: u32,
27    },
28    /// The count of units does not fit in a `u64`; holds the amount.
29    #[error("{0} is too large")]
30    TooLarge(Dec),
31}
32
33/// `value` as a count of `10^-places`, refused rather than rounded when it is
34/// finer than that: what was typed is what is signed.
35pub fn exact_units(value: Dec, places: u32) -> Result<u64, BadUnits> {
36    if value.places() > places {
37        return Err(BadUnits::TooFine { value, places });
38    }
39    cut_units(value, places)
40}
41
42/// `value` cut toward zero to a count of `10^-places`: for a computed figure
43/// (a whole balance, say), so it never asks for more than there is.
44pub fn cut_units(value: Dec, places: u32) -> Result<u64, BadUnits> {
45    if !value.is_positive() {
46        return Err(BadUnits::NotPositive(value));
47    }
48    let units = value.units_at(places, Round::Down).ok_or(BadUnits::TooLarge(value))?;
49    match u64::try_from(units) {
50        Ok(0) => Err(BadUnits::NotPositive(value)),
51        Ok(units) => Ok(units),
52        Err(_) => Err(BadUnits::TooLarge(value)),
53    }
54}
55
56#[cfg(test)]
57#[path = "tests/units.rs"]
58mod tests;