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)]
9#[non_exhaustive]
10pub enum Unpackable {
11 #[error("{0} is not a whole number; the venue hashes decimals as strings, so write it in quotes")]
13 Fraction(String),
14 #[error("{0} does not fit in 64 bits")]
16 TooWide(String),
17 #[error("an action is an object, and this is {0}")]
19 NotAnObject(&'static str),
20}
21
22impl Json {
23 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 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
52fn 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;