Skip to main content

df_hyperliquid_core/utils/json/
msgpack.rs

1//! JSON as the msgpack an L1 signature is over: keys in the order written, integers as the venue's
2//! own clients pack them, and never a float.
3
4use crate::utils::json::Json;
5use crate::utils::sign::msgpack::{Map, Value};
6
7/// Why a JSON value has no msgpack form the venue would hash the same way.
8#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
9pub enum Unpackable {
10    /// A number with a point or an exponent; holds its digits.
11    #[error("{0} is not a whole number; the venue hashes decimals as strings, so write it in quotes")]
12    Fraction(String),
13    /// A whole number outside `i64` when negative or `u64` otherwise; holds its digits.
14    #[error("{0} does not fit in 64 bits")]
15    TooWide(String),
16    /// [`Json::to_action`] was given something other than an object; holds its [`Json::kind`].
17    #[error("an action is an object, and this is {0}")]
18    NotAnObject(&'static str),
19}
20
21impl Json {
22    /// The msgpack value this hashes as, keys in the order they were written.
23    pub fn to_msgpack(&self) -> Result<Value, Unpackable> {
24        Ok(match self {
25            Json::Null => Value::Nil,
26            Json::Bool(value) => Value::Bool(*value),
27            Json::Number(digits) => whole(digits)?,
28            Json::String(text) => Value::from(text.clone()),
29            Json::Array(items) => Value::Array(items.iter().map(Json::to_msgpack).collect::<Result<_, _>>()?),
30            Json::Object(entries) => Value::Map(map_of(entries)?),
31        })
32    }
33
34    /// The action map an L1 signature is over. Only an object is one.
35    pub fn to_action(&self) -> Result<Map, Unpackable> {
36        match self {
37            Json::Object(entries) => map_of(entries),
38            other => Err(Unpackable::NotAnObject(other.kind())),
39        }
40    }
41}
42
43fn map_of(entries: &[(String, Json)]) -> Result<Map, Unpackable> {
44    let mut map = Map::new();
45    for (key, value) in entries {
46        map = map.put(key.clone(), value.to_msgpack()?);
47    }
48    Ok(map)
49}
50
51/// An integer as msgpack encodes it: unsigned when it can be, as the venue's
52/// own clients do. A fraction or an exponent would be a float, and a float is
53/// never what an action means.
54fn whole(digits: &str) -> Result<Value, Unpackable> {
55    if digits.contains(['.', 'e', 'E']) {
56        return Err(Unpackable::Fraction(digits.to_owned()));
57    }
58    match digits.strip_prefix('-') {
59        Some(_) => digits.parse::<i64>().map(Value::Int).map_err(|_| Unpackable::TooWide(digits.to_owned())),
60        None => digits.parse::<u64>().map(Value::Uint).map_err(|_| Unpackable::TooWide(digits.to_owned())),
61    }
62}
63
64#[cfg(test)]
65#[path = "tests/msgpack.rs"]
66mod tests;