Skip to main content

nautilus_blockchain/rpc/
types.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use alloy::primitives::{Address, B256, Bytes, U256};
17use nautilus_model::defi::{Block, DexType, PoolIdentifier, rpc::RpcLog};
18use serde::Deserialize;
19use serde_json::Value;
20
21use crate::events::{
22    burn::BurnEvent, collect::CollectEvent, fee_protocol_collect::FeeProtocolCollectEvent,
23    fee_protocol_update::FeeProtocolUpdateEvent, flash::FlashEvent, mint::MintEvent,
24    swap::SwapEvent,
25};
26
27/// Represents normalized blockchain messages.
28#[derive(Debug, Clone)]
29pub enum BlockchainMessage {
30    Block(Block),
31    SwapEvent(SwapEvent),
32    MintEvent(MintEvent),
33    BurnEvent(BurnEvent),
34    CollectEvent(CollectEvent),
35    FlashEvent(FlashEvent),
36    FeeProtocolUpdateEvent(FeeProtocolUpdateEvent),
37    FeeProtocolCollectEvent(FeeProtocolCollectEvent),
38    PoolLogRemoved {
39        pool_identifier: PoolIdentifier,
40        transaction_hash: String,
41        log_index: u32,
42    },
43}
44
45/// Represents the types of events that can be subscribed to via the blockchain RPC interface.
46///
47/// This enum defines the various event types that the application can subscribe to using
48/// the WebSocket-based RPC subscription.
49#[derive(Debug, Clone, Copy, Hash, PartialOrd, Ord, PartialEq, Eq)]
50pub enum RpcEventType {
51    NewBlock,
52    PoolSwap(DexType),
53    PoolMint(DexType),
54    PoolBurn(DexType),
55    PoolCollect(DexType),
56    PoolFlash(DexType),
57    PoolFeeProtocolUpdate(DexType),
58    PoolFeeProtocolCollect(DexType),
59}
60
61/// Result of an explicit-height `eth_call` before contract-specific output decoding.
62#[cfg(feature = "hypersync")]
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub(crate) enum RpcCallResult {
65    Success(Bytes),
66    Reverted,
67}
68
69/// Represents the minimal block view required for execution fee derivation.
70#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
71#[serde(rename_all = "camelCase")]
72pub struct RpcBlock {
73    /// The block number.
74    #[serde(deserialize_with = "deserialize_hex_u64")]
75    pub number: u64,
76    /// The canonical hash of the block.
77    pub hash: B256,
78    /// The canonical hash of the parent block.
79    pub parent_hash: B256,
80    /// The block timestamp in seconds since the Unix epoch.
81    #[serde(deserialize_with = "deserialize_hex_u64")]
82    pub timestamp: u64,
83    /// The block base fee per gas in wei (`None` on pre-London chains).
84    #[serde(default, deserialize_with = "deserialize_hex_u128_opt")]
85    pub base_fee_per_gas: Option<u128>,
86    /// Full transactions when requested, otherwise empty.
87    #[serde(skip)]
88    pub transactions: Vec<RpcTransaction>,
89}
90
91#[derive(Debug, Deserialize)]
92pub(crate) struct RpcBlockResponse {
93    #[serde(flatten)]
94    pub block: RpcBlock,
95    #[serde(default)]
96    pub transactions: Vec<Value>,
97}
98
99/// Represents the transaction identity required for signer-nonce reconciliation.
100#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
101#[serde(rename_all = "camelCase")]
102pub struct RpcTransaction {
103    /// The transaction hash.
104    pub hash: B256,
105    /// The signer address.
106    pub from: Address,
107    /// The signer nonce.
108    #[serde(deserialize_with = "deserialize_hex_u64")]
109    pub nonce: u64,
110    /// The chain ID authenticated by the transaction signature.
111    #[serde(default, deserialize_with = "deserialize_hex_u64_opt")]
112    pub chain_id: Option<u64>,
113    /// The EIP-2718 transaction type.
114    #[serde(default, rename = "type", deserialize_with = "deserialize_hex_u8_opt")]
115    pub transaction_type: Option<u8>,
116    /// The destination address, or `None` for contract creation.
117    pub to: Option<Address>,
118    /// The transaction calldata.
119    pub input: Bytes,
120    /// The native value in wei.
121    pub value: U256,
122    /// The transaction gas limit.
123    #[serde(default, deserialize_with = "deserialize_hex_u64_opt")]
124    pub gas: Option<u64>,
125    /// The EIP-1559 maximum fee per gas in wei.
126    pub max_fee_per_gas: Option<U256>,
127    /// The EIP-1559 maximum priority fee per gas in wei.
128    pub max_priority_fee_per_gas: Option<U256>,
129}
130
131/// Represents the minimal transaction receipt view required for inclusion observation.
132#[derive(Debug, Clone, Deserialize)]
133#[serde(rename_all = "camelCase")]
134pub struct RpcTransactionReceipt {
135    /// The transaction hash.
136    pub transaction_hash: B256,
137    /// The canonical block hash reported with the receipt.
138    pub block_hash: B256,
139    /// The block number that included the transaction.
140    #[serde(deserialize_with = "deserialize_hex_u64")]
141    pub block_number: u64,
142    /// The gas used by the transaction.
143    #[serde(deserialize_with = "deserialize_hex_u64")]
144    pub gas_used: u64,
145    /// The effective gas price charged in wei.
146    pub effective_gas_price: U256,
147    /// The transaction index within the block.
148    #[serde(deserialize_with = "deserialize_hex_u64")]
149    pub transaction_index: u64,
150    /// Whether the transaction executed successfully (status `0x1`).
151    #[serde(deserialize_with = "deserialize_hex_bool")]
152    pub status: bool,
153    /// Logs emitted by the transaction.
154    #[serde(default)]
155    pub logs: Vec<RpcLog>,
156}
157
158/// The call operation reported by Geth's `callTracer`.
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
160#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
161pub enum RpcCallType {
162    Call,
163    Callcode,
164    Delegatecall,
165    Staticcall,
166    Create,
167    Create2,
168    Selfdestruct,
169}
170
171/// A normalized frame from Geth's `callTracer`.
172#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
173#[serde(rename_all = "camelCase")]
174pub struct RpcCallTrace {
175    /// The EVM call operation.
176    #[serde(rename = "type")]
177    pub call_type: RpcCallType,
178    /// The frame caller.
179    pub from: Address,
180    /// The frame target, when the operation has one.
181    pub to: Option<Address>,
182    /// The native value supplied to the frame.
183    #[serde(default)]
184    pub value: U256,
185    /// The frame gas allowance.
186    #[serde(deserialize_with = "deserialize_hex_u64")]
187    pub gas: u64,
188    /// The gas consumed by the frame.
189    #[serde(deserialize_with = "deserialize_hex_u64")]
190    pub gas_used: u64,
191    /// The input bytes supplied to the frame.
192    #[serde(default)]
193    pub input: Bytes,
194    /// The output bytes returned by the frame.
195    #[serde(default)]
196    pub output: Bytes,
197    /// Whether the frame reported an execution error.
198    #[serde(default)]
199    pub error: Option<String>,
200    /// Child frames in execution order.
201    #[serde(default)]
202    pub calls: Vec<Self>,
203}
204
205fn deserialize_hex_u64<'de, D>(deserializer: D) -> Result<u64, D::Error>
206where
207    D: serde::Deserializer<'de>,
208{
209    let s = String::deserialize(deserializer)?;
210    let value = parse_hex_quantity(&s).map_err(serde::de::Error::custom)?;
211    u64::try_from(value).map_err(serde::de::Error::custom)
212}
213
214fn deserialize_hex_u64_opt<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
215where
216    D: serde::Deserializer<'de>,
217{
218    let value = Option::<String>::deserialize(deserializer)?
219        .map(|value| parse_hex_quantity(&value))
220        .transpose()
221        .map_err(serde::de::Error::custom)?;
222    value
223        .map(u64::try_from)
224        .transpose()
225        .map_err(serde::de::Error::custom)
226}
227
228fn deserialize_hex_u8_opt<'de, D>(deserializer: D) -> Result<Option<u8>, D::Error>
229where
230    D: serde::Deserializer<'de>,
231{
232    let value = Option::<String>::deserialize(deserializer)?
233        .map(|value| parse_hex_quantity(&value))
234        .transpose()
235        .map_err(serde::de::Error::custom)?;
236    value
237        .map(u8::try_from)
238        .transpose()
239        .map_err(serde::de::Error::custom)
240}
241
242fn deserialize_hex_u128_opt<'de, D>(deserializer: D) -> Result<Option<u128>, D::Error>
243where
244    D: serde::Deserializer<'de>,
245{
246    let s: Option<String> = Option::deserialize(deserializer)?;
247    s.map(|s| parse_hex_quantity(&s).map_err(serde::de::Error::custom))
248        .transpose()
249}
250
251fn deserialize_hex_bool<'de, D>(deserializer: D) -> Result<bool, D::Error>
252where
253    D: serde::Deserializer<'de>,
254{
255    let s = String::deserialize(deserializer)?;
256    match s.as_str() {
257        "0x0" => Ok(false),
258        "0x1" => Ok(true),
259        _ => Err(serde::de::Error::custom(
260            "invalid transaction receipt status; expected 0x0 or 0x1",
261        )),
262    }
263}
264
265fn parse_hex_quantity(s: &str) -> anyhow::Result<u128> {
266    let stripped = s.strip_prefix("0x").unwrap_or(s);
267    u128::from_str_radix(stripped, 16)
268        .map_err(|e| anyhow::anyhow!("Failed to parse hex quantity '{s}': {e}"))
269}