Skip to main content

df_hyperliquid_core/transfer/send/
amount.rs

1//! Amounts the venue is asked to move: plain decimals, at most eight places, never zero, in the
2//! normal form that is hashed (`"12.50"` is `"12.5"`, `"007"` is `"7"`).
3
4use std::fmt;
5
6use crate::utils::{Dec, Round};
7
8/// The most places an amount the venue takes may have.
9pub const MAX_DECIMALS: u32 = 8;
10
11/// Why an amount is refused.
12#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
13pub enum BadAmount {
14    /// Nothing, or only spaces, was given.
15    #[error("no amount given")]
16    Empty,
17    /// Not digits with at most one point and digits before it: `1,000`, `1e5`, `.5`, `+5`.
18    #[error("`{0}` is not a plain decimal amount")]
19    NotDecimal(String),
20    /// More than [`MAX_DECIMALS`] places.
21    #[error("`{0}` has more than {MAX_DECIMALS} decimal places")]
22    TooFine(String),
23    /// Zero, or a computed figure that cuts to zero.
24    #[error("the amount is zero")]
25    Zero,
26    /// Below zero.
27    #[error("`{0}` is below zero")]
28    Negative(String),
29    /// Too large for a [`Dec`].
30    #[error("`{0}` is too large")]
31    TooLarge(String),
32}
33
34/// A validated amount: its wire string and the same value as a [`Dec`].
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct Amount {
37    wire: String,
38    value: Dec,
39}
40
41impl Amount {
42    /// What a person typed, checked by [`clean_amount`].
43    pub fn parse(text: &str) -> Result<Amount, BadAmount> {
44        let wire = clean_amount(text)?;
45        let value = Dec::parse(&wire).map_err(|_| BadAmount::TooLarge(wire.clone()))?;
46        Ok(Amount { wire, value })
47    }
48
49    /// A computed figure cut toward zero to `places` (at most eight), so it never asks for more
50    /// than is there.
51    pub fn cut(value: Dec, places: u32) -> Result<Amount, BadAmount> {
52        if value.is_negative() {
53            return Err(BadAmount::Negative(value.to_wire()));
54        }
55        let value = value.round(places.min(MAX_DECIMALS), Round::Down);
56        if value.is_zero() {
57            return Err(BadAmount::Zero);
58        }
59        Ok(Amount { wire: value.to_wire(), value })
60    }
61
62    /// The string that is posted and hashed.
63    #[must_use]
64    pub fn as_str(&self) -> &str {
65        &self.wire
66    }
67
68    /// The amount as a [`Dec`].
69    #[must_use]
70    pub const fn value(&self) -> Dec {
71        self.value
72    }
73}
74
75impl fmt::Display for Amount {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        f.write_str(&self.wire)
78    }
79}
80
81/// Checks a typed amount: digits, at most one point with digits before it, at most eight places,
82/// not zero. Returns the normal form; a place finer than eight is refused, never rounded.
83pub fn clean_amount(text: &str) -> Result<String, BadAmount> {
84    let text = text.trim();
85    if text.is_empty() {
86        return Err(BadAmount::Empty);
87    }
88    if let Some(rest) = text.strip_prefix('-')
89        && !rest.is_empty()
90        && rest.bytes().all(|b| b.is_ascii_digit() || b == b'.')
91    {
92        return Err(BadAmount::Negative(text.to_owned()));
93    }
94    let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
95    if whole.is_empty() || !whole.bytes().all(|b| b.is_ascii_digit()) || !fraction.bytes().all(|b| b.is_ascii_digit()) {
96        return Err(BadAmount::NotDecimal(text.to_owned()));
97    }
98    if fraction.trim_end_matches('0').len() > MAX_DECIMALS as usize {
99        return Err(BadAmount::TooFine(text.to_owned()));
100    }
101    let value = Dec::parse(text).map_err(|_| BadAmount::TooLarge(text.to_owned()))?;
102    if value.is_zero() {
103        return Err(BadAmount::Zero);
104    }
105    Ok(value.to_wire())
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    fn dec(text: &str) -> Dec {
113        Dec::parse(text).unwrap()
114    }
115
116    #[test]
117    fn an_amount_is_checked_before_anything_is_signed() {
118        assert_eq!(clean_amount(" 100.5 ").unwrap(), "100.5");
119        assert_eq!(clean_amount("0.00000001").unwrap(), "0.00000001");
120        for (bad, why) in [
121            ("", BadAmount::Empty),
122            ("0", BadAmount::Zero),
123            ("0.00", BadAmount::Zero),
124            ("-5", BadAmount::Negative("-5".to_owned())),
125            ("1,000", BadAmount::NotDecimal("1,000".to_owned())),
126            ("1e5", BadAmount::NotDecimal("1e5".to_owned())),
127            ("abc", BadAmount::NotDecimal("abc".to_owned())),
128            ("1.000000001", BadAmount::TooFine("1.000000001".to_owned())),
129            (".", BadAmount::NotDecimal(".".to_owned())),
130            (".5", BadAmount::NotDecimal(".5".to_owned())),
131            ("+5", BadAmount::NotDecimal("+5".to_owned())),
132            ("1.2.3", BadAmount::NotDecimal("1.2.3".to_owned())),
133        ] {
134            assert_eq!(clean_amount(bad), Err(why), "`{bad}` should not be signable");
135        }
136    }
137
138    /// The SDK's `formatDecimalString`: the hashed string is the normal one.
139    #[test]
140    fn an_amount_comes_back_in_the_form_the_sdk_hashes() {
141        for (typed, wire) in [
142            ("100", "100"),
143            ("100.0", "100"),
144            ("12.50", "12.5"),
145            ("000.5", "0.5"),
146            ("007", "7"),
147            ("1.", "1"),
148            ("1.000000000", "1"),
149            ("2550.12345678", "2550.12345678"),
150        ] {
151            assert_eq!(clean_amount(typed).unwrap(), wire, "{typed}");
152            assert_eq!(Amount::parse(typed).unwrap().as_str(), wire, "{typed}");
153        }
154        assert_eq!(Amount::parse("12.50").unwrap().value(), dec("12.5"));
155    }
156
157    #[test]
158    fn a_computed_figure_is_cut_toward_zero_never_rounded_up() {
159        assert_eq!(Amount::cut(dec("41085515.0539499968"), 6).unwrap().as_str(), "41085515.053949");
160        assert_eq!(Amount::cut(dec("0.123456789"), 12).unwrap().as_str(), "0.12345678", "eight places at most");
161        assert_eq!(Amount::cut(dec("0.0000009"), 6), Err(BadAmount::Zero), "dust cuts to nothing");
162        assert_eq!(Amount::cut(dec("-1"), 6), Err(BadAmount::Negative("-1".to_owned())));
163    }
164}