Skip to main content

df_hyperliquid_core/client/evm/rpc/
query.rs

1//! [`Query`], one JSON-RPC method with its params: the request body it writes,
2//! the envelope its answer comes in, and how its `result` is read.
3
4use crate::client::evm::rpc::{BlockTag, NodeError, RpcError};
5use crate::client::evm::u256::{B256, U256};
6use crate::utils::{Address, Json, hex};
7use serde::{Deserialize, Deserializer, de::DeserializeOwned};
8use serde_json::value::RawValue;
9
10/// One JSON-RPC method with its params, and how its `result` is read.
11#[derive(Debug, Clone)]
12pub struct Query<T> {
13    pub(super) method: &'static str,
14    pub(super) params: Vec<Json>,
15    pub(super) read: fn(&str) -> Result<T, String>,
16}
17
18impl<T> Query<T> {
19    /// The JSON-RPC method name, such as `eth_call`.
20    #[must_use]
21    pub const fn method(&self) -> &'static str {
22        self.method
23    }
24
25    /// `{"jsonrpc":"2.0","id":1,"method":...,"params":[...]}`.
26    #[must_use]
27    pub fn body(&self) -> String {
28        Json::Object(vec![
29            ("jsonrpc".to_owned(), Json::String("2.0".to_owned())),
30            ("id".to_owned(), Json::Number("1".to_owned())),
31            ("method".to_owned(), Json::String(self.method.to_owned())),
32            ("params".to_owned(), Json::Array(self.params.clone())),
33        ])
34        .compact()
35    }
36
37    /// The answer's text, read: its `result` as `T`, or its `error`.
38    pub fn answer(&self, text: &str) -> Result<T, RpcError> {
39        let unreadable = |detail: String| RpcError::Unreadable { method: self.method, detail };
40        let envelope: Envelope<'_> = serde_json::from_str(text)
41            .map_err(|error| unreadable(format!("{error} in {}", text.chars().take(300).collect::<String>())))?;
42        if let Some(error) = envelope.error {
43            let data = error
44                .data
45                .map(|data| serde_json::from_str::<String>(data.get()).unwrap_or_else(|_| data.get().to_owned()));
46            return Err(RpcError::Node {
47                method: self.method,
48                error: NodeError { code: error.code, message: error.message, data },
49            });
50        }
51        let result = envelope.result.ok_or_else(|| unreadable("neither a result nor an error".to_owned()))?;
52        (self.read)(result.get()).map_err(|detail| unreadable(format!("{detail} in {}", result.get())))
53    }
54}
55
56#[derive(Deserialize)]
57struct Envelope<'a> {
58    #[serde(default, borrow, deserialize_with = "raw")]
59    result: Option<&'a RawValue>,
60    #[serde(default, borrow)]
61    error: Option<ErrorBody<'a>>,
62}
63
64#[derive(Deserialize)]
65struct ErrorBody<'a> {
66    code: i64,
67    #[serde(default)]
68    message: String,
69    #[serde(default, borrow, deserialize_with = "raw")]
70    data: Option<&'a RawValue>,
71}
72
73/// A value as the text it was written in, `null` included.
74fn raw<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<&'de RawValue>, D::Error> {
75    <&RawValue>::deserialize(deserializer).map(Some)
76}
77
78pub(super) fn json<T: DeserializeOwned>(text: &str) -> Result<T, String> {
79    serde_json::from_str(text).map_err(|error| error.to_string())
80}
81
82pub(super) fn small(text: &str) -> Result<u64, String> {
83    let value: U256 = json(text)?;
84    value.to_u64().ok_or_else(|| format!("{value} does not fit 64 bits"))
85}
86
87/// A quantity that fits a `u64`, or `null`.
88pub(super) fn small_or_null(text: &str) -> Result<Option<u64>, String> {
89    match json::<Option<U256>>(text)? {
90        Some(value) => value.to_u64().map(Some).ok_or_else(|| format!("{value} does not fit 64 bits")),
91        None => Ok(None),
92    }
93}
94
95/// A decimal string, as `net_version` answers: `"999"`.
96pub(super) fn decimal(text: &str) -> Result<u64, String> {
97    let said: String = json(text)?;
98    said.parse().map_err(|_| format!("`{said}` is not a decimal number"))
99}
100
101/// `false`, or an object with the sync's progress, read as `true`.
102pub(super) fn sync_state(text: &str) -> Result<bool, String> {
103    match json::<serde_json::Value>(text)? {
104        serde_json::Value::Bool(syncing) => Ok(syncing),
105        serde_json::Value::Object(_) => Ok(true),
106        other => Err(format!("`{other}` is neither false nor a sync's progress")),
107    }
108}
109
110pub(super) fn data(text: &str) -> Result<Vec<u8>, String> {
111    let said: String = json(text)?;
112    let digits = said.strip_prefix("0x").ok_or_else(|| format!("`{said}` is not 0x and hex"))?;
113    hex::decode(digits).map_err(|error| error.to_string())
114}
115
116pub(super) fn quantity(value: U256) -> Json {
117    Json::String(value.to_quantity())
118}
119
120pub(super) fn tag(block: BlockTag) -> Json {
121    Json::String(block.to_string())
122}
123
124pub(super) fn hash(hash: B256) -> Json {
125    Json::String(hash.to_hex())
126}
127
128pub(super) fn index(index: u64) -> Json {
129    quantity(U256::from_u64(index))
130}
131
132pub(super) fn address(address: Address) -> Json {
133    Json::String(address.to_hex())
134}
135
136#[cfg(test)]
137#[path = "tests/query.rs"]
138mod tests;