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