Skip to main content

df_hyperliquid_core/client/evm/precompiles/
read.rs

1//! A typed [`Read`]: where the call goes, its calldata and how its answer reads,
2//! and the [`Rpc`] method that makes one.
3
4use crate::client::Http;
5use crate::client::evm::abi::AbiError;
6use crate::client::evm::precompiles::table::address;
7use crate::client::evm::rpc::{BlockTag, CallRequest, Rpc, RpcError};
8use crate::client::evm::u256::{B256, U256};
9use crate::utils::Address;
10
11/// A typed read: where the call goes, its calldata, and how its answer reads.
12#[derive(Debug, Clone)]
13pub struct Read<T> {
14    /// The precompile's address, `0x...0800` through `0x...0814`.
15    pub at: Address,
16    /// The calldata: the ABI-encoded arguments with no selector.
17    pub data: Vec<u8>,
18    decode: fn(&[u8]) -> Result<T, AbiError>,
19}
20
21impl<T> Read<T> {
22    /// The `eth_call` that makes the read.
23    #[must_use]
24    pub fn request(&self) -> CallRequest {
25        CallRequest::to(self.at, self.data.clone())
26    }
27
28    /// The answer's bytes, read against the declared struct.
29    pub fn decode(&self, answer: &[u8]) -> Result<T, AbiError> {
30        (self.decode)(answer)
31    }
32}
33
34/// Why a precompile read failed.
35#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
36pub enum ReadError {
37    #[error(transparent)]
38    /// The `eth_call` failed.
39    Rpc(#[from] RpcError),
40    #[error("the precompile's answer does not fit its struct: {0}")]
41    /// The answer does not decode as the precompile's declared return struct.
42    Abi(#[from] AbiError),
43}
44
45impl<H: Http> Rpc<H> {
46    /// One read precompile, at the latest block: the only one HyperEVM serves.
47    pub async fn read<T>(&self, read: &Read<T>) -> Result<T, ReadError> {
48        let answer = self.call(&read.request(), BlockTag::Latest).await?;
49        Ok(read.decode(&answer)?)
50    }
51}
52
53/// One argument word: every precompile argument is a static type, so the
54/// calldata is the words one after another, as `abi.encode` writes them.
55pub(super) enum Arg {
56    Address(Address),
57    Uint(u64),
58}
59
60pub(super) fn read<T>(at: u16, args: &[Arg], decode: fn(&[u8]) -> Result<T, AbiError>) -> Read<T> {
61    let mut data = Vec::with_capacity(args.len() * 32);
62    for arg in args {
63        let word = match arg {
64            Arg::Address(address) => B256::from_address(*address).0,
65            Arg::Uint(value) => U256::from_u64(*value).to_be_bytes(),
66        };
67        data.extend_from_slice(&word);
68    }
69    Read { at: address(at), data, decode }
70}