Skip to main content

df_hyperliquid_core/client/evm/rpc/
call.rs

1//! [`CallRequest`]: the call object `eth_call` and `eth_estimateGas` take.
2
3use crate::client::evm::rpc::query::quantity;
4use crate::client::evm::tx::Call;
5use crate::client::evm::u256::U256;
6use crate::utils::{Address, Json, hex};
7
8/// The call object `eth_call` and `eth_estimateGas` take. No `to` estimates
9/// or runs a contract creation from `data`.
10#[derive(Debug, Clone, PartialEq, Eq, Default)]
11pub struct CallRequest {
12    /// The sender; `None` lets the node pick.
13    pub from: Option<Address>,
14    /// The contract called; `None` for a creation.
15    pub to: Option<Address>,
16    /// The gas limit; `None` lets the node pick.
17    pub gas: Option<u64>,
18    /// Wei of the chain's coin sent with it; `None` sends none.
19    pub value: Option<U256>,
20    /// The calldata, or the init code of a creation; left out when empty.
21    pub data: Vec<u8>,
22}
23
24impl CallRequest {
25    /// `data` sent to a contract.
26    #[must_use]
27    pub fn to(to: Address, data: Vec<u8>) -> CallRequest {
28        CallRequest { to: Some(to), data, ..CallRequest::default() }
29    }
30
31    /// What `call` does, as sent by `from`: what a transaction's gas is estimated with.
32    #[must_use]
33    pub fn of(from: Option<Address>, call: &Call) -> CallRequest {
34        CallRequest {
35            from,
36            to: call.to,
37            gas: None,
38            value: (!call.value.is_zero()).then_some(call.value),
39            data: call.data.clone(),
40        }
41    }
42
43    pub(super) fn json(&self) -> Json {
44        let mut fields = Vec::new();
45        if let Some(from) = self.from {
46            fields.push(("from".to_owned(), Json::String(from.to_hex())));
47        }
48        if let Some(to) = self.to {
49            fields.push(("to".to_owned(), Json::String(to.to_hex())));
50        }
51        if let Some(gas) = self.gas {
52            fields.push(("gas".to_owned(), quantity(U256::from_u64(gas))));
53        }
54        if let Some(value) = self.value {
55            fields.push(("value".to_owned(), quantity(value)));
56        }
57        if !self.data.is_empty() {
58            fields.push(("data".to_owned(), Json::String(hex::encode_prefixed(&self.data))));
59        }
60        Json::Object(fields)
61    }
62}