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