df_hyperliquid_core/utils/json/
msgpack.rs1use crate::utils::json::Json;
5use crate::utils::sign::msgpack::{Map, Value};
6
7#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
9pub enum Unpackable {
10 #[error("{0} is not a whole number; the venue hashes decimals as strings, so write it in quotes")]
12 Fraction(String),
13 #[error("{0} does not fit in 64 bits")]
15 TooWide(String),
16 #[error("an action is an object, and this is {0}")]
18 NotAnObject(&'static str),
19}
20
21impl Json {
22 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 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
51fn 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;