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)]
15pub enum BadUnits {
16    /// Zero or negative, or cut to zero units; holds the amount.
17    #[error("{0} is not a positive amount")]
18    NotPositive(Dec),
19    /// [`exact_units`] was given an amount finer than the places allowed.
20    #[error("{value} has more than {places} decimal places")]
21    TooFine {
22        /// The amount given.
23        value: Dec,
24        /// The most places allowed.
25        places: u32,
26    },
27    /// The count of units does not fit in a `u64`; holds the amount.
28    #[error("{0} is too large")]
29    TooLarge(Dec),
30}
31
32/// `value` as a count of `10^-places`, refused rather than rounded when it is
33/// finer than that: what was typed is what is signed.
34pub fn exact_units(value: Dec, places: u32) -> Result<u64, BadUnits> {
35    if value.places() > places {
36        return Err(BadUnits::TooFine { value, places });
37    }
38    cut_units(value, places)
39}
40
41/// `value` cut toward zero to a count of `10^-places`: for a computed figure
42/// (a whole balance, say), so it never asks for more than there is.
43pub fn cut_units(value: Dec, places: u32) -> Result<u64, BadUnits> {
44    if !value.is_positive() {
45        return Err(BadUnits::NotPositive(value));
46    }
47    let units = value.units_at(places, Round::Down).ok_or(BadUnits::TooLarge(value))?;
48    match u64::try_from(units) {
49        Ok(0) => Err(BadUnits::NotPositive(value)),
50        Ok(units) => Ok(units),
51        Err(_) => Err(BadUnits::TooLarge(value)),
52    }
53}
54
55#[cfg(test)]
56#[path = "tests/units.rs"]
57mod tests;