Skip to main content

df_hyperliquid_core/client/evm/
records.rs

1//! Receipts, transactions, blocks, logs and fee history as JSON-RPC answers
2//! them. Quantities are exact integers; a block's gas used ratio, the one
3//! float a node writes, is kept as the digits it wrote.
4
5use crate::account::Signature;
6use crate::client::evm::tx::{AccessItem, EIP1559, Eip1559};
7use crate::client::evm::u256::{B256, U256};
8use crate::utils::{Address, Figure};
9use serde::{Deserialize, Deserializer, de};
10
11/// What `eth_getTransactionReceipt` answers once a transaction is mined.
12#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
13#[serde(rename_all = "camelCase")]
14#[non_exhaustive]
15pub struct Receipt {
16    /// The hash of the transaction this receipt is for (`transactionHash`).
17    pub transaction_hash: B256,
18    /// Its position in the block (`transactionIndex`); `None` when the node leaves it out.
19    #[serde(default, deserialize_with = "opt_quantity")]
20    pub transaction_index: Option<u64>,
21    /// The hash of the block it was mined in (`blockHash`); `None` when the node leaves it out.
22    #[serde(default)]
23    pub block_hash: Option<B256>,
24    /// The number of the block it was mined in (`blockNumber`); `None` when the node leaves it out.
25    #[serde(default, deserialize_with = "opt_quantity")]
26    pub block_number: Option<u64>,
27    /// The sender.
28    pub from: Address,
29    /// `None` for a creation.
30    #[serde(default)]
31    pub to: Option<Address>,
32    /// The contract a creation made; `None` for a call.
33    #[serde(default)]
34    pub contract_address: Option<Address>,
35    /// Gas this transaction used (`gasUsed`).
36    #[serde(deserialize_with = "quantity")]
37    pub gas_used: u64,
38    /// Gas used in the block up to and including this transaction (`cumulativeGasUsed`).
39    #[serde(deserialize_with = "quantity")]
40    pub cumulative_gas_used: u64,
41    /// The price paid per unit of gas, in wei (`effectiveGasPrice`); `None` when the node leaves it out.
42    #[serde(default)]
43    pub effective_gas_price: Option<U256>,
44    /// `true` when it succeeded, `false` when it reverted.
45    #[serde(default, deserialize_with = "opt_status")]
46    pub status: Option<bool>,
47    /// The logs it emitted, in order.
48    pub logs: Vec<Log>,
49    /// The transaction type: 2 for EIP-1559.
50    #[serde(default, rename = "type", deserialize_with = "opt_byte")]
51    pub kind: Option<u8>,
52}
53
54impl Receipt {
55    /// Mined and not reverted.
56    #[must_use]
57    pub fn succeeded(&self) -> bool {
58        self.status == Some(true)
59    }
60}
61
62/// What `eth_getTransactionByHash` answers, mined or still pending.
63#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
64#[serde(rename_all = "camelCase")]
65#[non_exhaustive]
66pub struct Transaction {
67    /// The transaction hash: `keccak256` of its signed bytes.
68    pub hash: B256,
69    /// 2 for EIP-1559; 0 for legacy.
70    #[serde(default, rename = "type", deserialize_with = "byte")]
71    pub kind: u8,
72    /// The chain it is signed for (`chainId`); `None` for a legacy transaction without one.
73    #[serde(default, deserialize_with = "opt_quantity")]
74    pub chain_id: Option<u64>,
75    /// The sender's nonce.
76    #[serde(deserialize_with = "quantity")]
77    pub nonce: u64,
78    /// The hash of the block it was mined in (`blockHash`); `None` while pending.
79    #[serde(default)]
80    pub block_hash: Option<B256>,
81    /// The number of the block it was mined in (`blockNumber`); `None` while pending.
82    #[serde(default, deserialize_with = "opt_quantity")]
83    pub block_number: Option<u64>,
84    /// Its position in the block (`transactionIndex`); `None` while pending.
85    #[serde(default, deserialize_with = "opt_quantity")]
86    pub transaction_index: Option<u64>,
87    /// The sender.
88    pub from: Address,
89    /// `None` for a creation.
90    #[serde(default)]
91    pub to: Option<Address>,
92    /// Wei of the chain's coin sent with it.
93    pub value: U256,
94    /// The gas limit.
95    #[serde(deserialize_with = "quantity")]
96    pub gas: u64,
97    /// Wei per unit of gas (`gasPrice`): the legacy price, or for type 2 what the node reports as paid.
98    #[serde(default)]
99    pub gas_price: Option<U256>,
100    /// The fee cap in wei per unit of gas (`maxFeePerGas`); `None` for a legacy transaction.
101    #[serde(default)]
102    pub max_fee_per_gas: Option<U256>,
103    /// The tip cap in wei per unit of gas (`maxPriorityFeePerGas`); `None` for a legacy transaction.
104    #[serde(default)]
105    pub max_priority_fee_per_gas: Option<U256>,
106    /// The contracts and storage slots it declares (`accessList`); empty when the node leaves it out.
107    #[serde(default)]
108    pub access_list: Vec<AccessItem>,
109    /// The calldata, or the init code of a creation.
110    #[serde(deserialize_with = "bytes")]
111    pub input: Vec<u8>,
112    /// The signature's `r`; `None` when the node leaves it out.
113    #[serde(default)]
114    pub r: Option<U256>,
115    /// The signature's `s`; `None` when the node leaves it out.
116    #[serde(default)]
117    pub s: Option<U256>,
118    /// The signature's parity, 0 or 1 (`yParity`); `None` when the node leaves it out.
119    #[serde(default, deserialize_with = "opt_quantity")]
120    pub y_parity: Option<u64>,
121}
122
123impl Transaction {
124    /// The type 2 transaction this record is of: rebuilt, it hashes to
125    /// [`Transaction::hash`] once signed with [`Transaction::signature`].
126    #[must_use]
127    pub fn to_eip1559(&self) -> Option<Eip1559> {
128        if self.kind != EIP1559 {
129            return None;
130        }
131        Some(Eip1559 {
132            chain_id: self.chain_id?,
133            nonce: self.nonce,
134            max_priority_fee: self.max_priority_fee_per_gas?,
135            max_fee: self.max_fee_per_gas?,
136            gas: self.gas,
137            to: self.to,
138            value: self.value,
139            data: self.input.clone(),
140            access_list: self.access_list.clone(),
141        })
142    }
143
144    /// The signature the record carries, `v` as 27 or 28.
145    #[must_use]
146    pub fn signature(&self) -> Option<Signature> {
147        let parity = u8::try_from(self.y_parity?).ok().filter(|parity| *parity <= 1)?;
148        Some(Signature::from_parts(self.r?.to_be_bytes(), self.s?.to_be_bytes(), 27 + parity))
149    }
150}
151
152/// What `eth_getBlockByNumber` answers.
153#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
154#[serde(rename_all = "camelCase")]
155#[non_exhaustive]
156pub struct Block {
157    /// The block number.
158    #[serde(deserialize_with = "quantity")]
159    pub number: u64,
160    /// The block hash.
161    pub hash: B256,
162    /// The hash of the block before it (`parentHash`).
163    pub parent_hash: B256,
164    /// Unix seconds.
165    #[serde(deserialize_with = "quantity")]
166    pub timestamp: u64,
167    #[serde(deserialize_with = "quantity")]
168    /// The most gas the block can hold (`gasLimit`).
169    pub gas_limit: u64,
170    #[serde(deserialize_with = "quantity")]
171    /// Gas its transactions used (`gasUsed`).
172    pub gas_used: u64,
173    #[serde(default)]
174    /// The base fee in wei per unit of gas (`baseFeePerGas`); `None` before EIP-1559.
175    pub base_fee_per_gas: Option<U256>,
176    /// The address that produced the block.
177    pub miner: Address,
178    /// Its transactions, as hashes or whole records.
179    pub transactions: BlockTransactions,
180}
181
182/// A block's transactions: their hashes, or the whole records when asked for.
183#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
184#[serde(untagged)]
185#[non_exhaustive]
186pub enum BlockTransactions {
187    /// Only the hashes, when the block is asked for without full transactions.
188    Hashes(Vec<B256>),
189    /// The whole records, when the block is asked for with full transactions.
190    Full(Vec<Transaction>),
191}
192
193/// One log, from a receipt or `eth_getLogs`.
194#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
195#[serde(rename_all = "camelCase")]
196#[non_exhaustive]
197pub struct Log {
198    /// The contract that emitted it.
199    pub address: Address,
200    /// The indexed topics; the first is the event signature hash unless the event is anonymous.
201    pub topics: Vec<B256>,
202    /// The non-indexed data, ABI encoded.
203    #[serde(deserialize_with = "bytes")]
204    pub data: Vec<u8>,
205    /// The number of the block it is in (`blockNumber`); `None` while pending.
206    #[serde(default, deserialize_with = "opt_quantity")]
207    pub block_number: Option<u64>,
208    /// The hash of the block it is in (`blockHash`); `None` while pending.
209    #[serde(default)]
210    pub block_hash: Option<B256>,
211    /// The hash of the transaction that emitted it (`transactionHash`); `None` while pending.
212    #[serde(default)]
213    pub transaction_hash: Option<B256>,
214    /// That transaction's position in the block (`transactionIndex`); `None` while pending.
215    #[serde(default, deserialize_with = "opt_quantity")]
216    pub transaction_index: Option<u64>,
217    /// Its position among the block's logs (`logIndex`); `None` while pending.
218    #[serde(default, deserialize_with = "opt_quantity")]
219    pub log_index: Option<u64>,
220    /// Dropped by a reorganisation.
221    #[serde(default)]
222    pub removed: bool,
223}
224
225/// What `eth_feeHistory` answers.
226#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
227#[serde(rename_all = "camelCase")]
228#[non_exhaustive]
229pub struct FeeHistory {
230    /// The number of the first block in the answer (`oldestBlock`).
231    #[serde(deserialize_with = "quantity")]
232    pub oldest_block: u64,
233    /// One per block asked for, and one more: the next block's.
234    pub base_fee_per_gas: Vec<U256>,
235    /// Each block's gas used over its limit, as the node wrote it.
236    pub gas_used_ratio: Vec<Figure>,
237    /// Per block, the tip at each percentile asked for.
238    #[serde(default)]
239    pub reward: Vec<Vec<U256>>,
240}
241
242impl FeeHistory {
243    /// The base fee of the block after the newest one asked for.
244    #[must_use]
245    pub fn next_base_fee(&self) -> Option<U256> {
246        self.base_fee_per_gas.last().copied()
247    }
248}
249
250/// A quantity that fits a `u64`: block numbers, nonces, gas.
251pub(crate) fn quantity<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
252    let value = U256::deserialize(deserializer)?;
253    value.to_u64().ok_or_else(|| de::Error::custom(format!("{value} does not fit 64 bits")))
254}
255
256fn opt_quantity<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<u64>, D::Error> {
257    match Option::<U256>::deserialize(deserializer)? {
258        Some(value) => {
259            value.to_u64().map(Some).ok_or_else(|| de::Error::custom(format!("{value} does not fit 64 bits")))
260        }
261        None => Ok(None),
262    }
263}
264
265fn byte<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u8, D::Error> {
266    let value = quantity(deserializer)?;
267    u8::try_from(value).map_err(|_| de::Error::custom(format!("{value} is not a transaction type")))
268}
269
270fn opt_byte<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<u8>, D::Error> {
271    match opt_quantity(deserializer)? {
272        Some(value) => {
273            u8::try_from(value).map(Some).map_err(|_| de::Error::custom(format!("{value} is not a transaction type")))
274        }
275        None => Ok(None),
276    }
277}
278
279fn opt_status<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<bool>, D::Error> {
280    match opt_quantity(deserializer)? {
281        Some(0) => Ok(Some(false)),
282        Some(1) => Ok(Some(true)),
283        Some(other) => Err(de::Error::custom(format!("{other} is not a receipt status"))),
284        None => Ok(None),
285    }
286}
287
288/// `0x` and hex bytes.
289pub(crate) fn bytes<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
290    let text = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
291    let digits = text.strip_prefix("0x").ok_or_else(|| de::Error::custom(format!("`{text}` is not 0x and hex")))?;
292    crate::utils::hex::decode(digits).map_err(de::Error::custom)
293}
294
295#[cfg(test)]
296#[path = "tests/records.rs"]
297mod tests;