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