Skip to main content

reth_rpc_api/
trace.rs

1use alloy_eips::BlockId;
2use alloy_primitives::{map::HashSet, Bytes, B256};
3use alloy_rpc_types_eth::{state::StateOverride, BlockOverrides};
4use alloy_rpc_types_trace::{
5    filter::TraceFilter,
6    opcode::{BlockOpcodeGas, TransactionOpcodeGas},
7    parity::*,
8};
9use jsonrpsee::{core::RpcResult, proc_macros::rpc};
10use reth_rpc_eth_api::BoundedCallMany;
11use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
12
13/// Ethereum trace API
14#[rpc(server, namespace = "trace")]
15pub trait TraceApi<TxReq> {
16    /// Executes the given call and returns a number of possible traces for it.
17    #[method(name = "call")]
18    async fn trace_call(
19        &self,
20        call: TxReq,
21        trace_types: HashSet<TraceType>,
22        block_id: Option<BlockId>,
23        state_overrides: Option<StateOverride>,
24        block_overrides: Option<Box<BlockOverrides>>,
25    ) -> RpcResult<TraceResults>;
26
27    /// Performs multiple call traces on top of the same block, defaulting to latest when no block
28    /// is specified. Each call is executed with the preceding calls applied first, allowing
29    /// dependent transactions to be traced.
30    ///
31    /// State and block overrides apply once, before the first call, and the block override holds
32    /// for every call.
33    #[method(name = "callMany")]
34    async fn trace_call_many(
35        &self,
36        calls: BoundedCallMany<Vec<(TxReq, HashSet<TraceType>)>>,
37        block_id: Option<BlockId>,
38        state_overrides: Option<StateOverride>,
39        block_overrides: Option<Box<BlockOverrides>>,
40    ) -> RpcResult<Vec<TraceResults>>;
41
42    /// Traces a call to `eth_sendRawTransaction` without making the call, returning the traces.
43    ///
44    /// Expects a raw transaction data
45    #[method(name = "rawTransaction")]
46    async fn trace_raw_transaction(
47        &self,
48        data: Bytes,
49        trace_types: HashSet<TraceType>,
50        block_id: Option<BlockId>,
51    ) -> RpcResult<TraceResults>;
52
53    /// Replays all transactions in a block returning the requested traces for each transaction.
54    #[method(name = "replayBlockTransactions")]
55    async fn replay_block_transactions(
56        &self,
57        block_id: BlockId,
58        trace_types: HashSet<TraceType>,
59    ) -> RpcResult<Option<Vec<TraceResultsWithTransactionHash>>>;
60
61    /// Replays a transaction, returning the traces or `None` if the transaction does not exist.
62    #[method(name = "replayTransaction")]
63    async fn replay_transaction(
64        &self,
65        transaction: B256,
66        trace_types: HashSet<TraceType>,
67    ) -> RpcResult<Option<TraceResultsWithTransactionHash>>;
68
69    /// Returns traces created at given block.
70    #[method(name = "block")]
71    async fn trace_block(
72        &self,
73        block_id: BlockId,
74    ) -> RpcResult<Option<Vec<LocalizedTransactionTrace>>>;
75
76    /// Returns traces matching given filter.
77    ///
78    /// This is similar to `eth_getLogs` but for traces. Omitted range bounds default to latest.
79    #[method(name = "filter")]
80    async fn trace_filter(&self, filter: TraceFilter) -> RpcResult<Vec<LocalizedTransactionTrace>>;
81
82    /// Returns the transaction trace at the given `traceAddress` path.
83    ///
84    /// An empty path selects the root, `["0x0"]` selects its first child, and `["0x0", "0x1"]`
85    /// selects that child's second child. Path entries are hex quantities. Returns `None` if the
86    /// transaction or path does not exist.
87    /// Callers requiring a flat index can index the result of `trace_transaction` instead.
88    #[method(name = "get")]
89    async fn trace_get(
90        &self,
91        hash: B256,
92        indices: Vec<TraceAddressIndex>,
93    ) -> RpcResult<Option<LocalizedTransactionTrace>>;
94
95    /// Returns all traces of given transaction.
96    #[method(name = "transaction")]
97    async fn trace_transaction(
98        &self,
99        hash: B256,
100    ) -> RpcResult<Option<Vec<LocalizedTransactionTrace>>>;
101
102    /// Returns all opcodes with their count and combined gas usage for the given transaction in no
103    /// particular order.
104    #[method(name = "transactionOpcodeGas")]
105    async fn trace_transaction_opcode_gas(
106        &self,
107        tx_hash: B256,
108    ) -> RpcResult<Option<TransactionOpcodeGas>>;
109
110    /// Returns the opcodes of all transactions in the given block.
111    ///
112    /// This is the same as `trace_transactionOpcodeGas` but for all transactions in a block.
113    #[method(name = "blockOpcodeGas")]
114    async fn trace_block_opcode_gas(&self, block_id: BlockId) -> RpcResult<Option<BlockOpcodeGas>>;
115}
116
117/// An index into a `traceAddress` path, encoded as a hex quantity such as `"0x1"`.
118///
119/// Unlike [`alloy_rpc_types_eth::Index`], JSON numbers, decimal strings and hex strings with
120/// leading zeros or uppercase digits are rejected, so `traceAddress` entries taken from a trace
121/// must be converted to hex quantities.
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123pub struct TraceAddressIndex(pub usize);
124
125impl From<TraceAddressIndex> for usize {
126    fn from(index: TraceAddressIndex) -> Self {
127        index.0
128    }
129}
130
131impl Serialize for TraceAddressIndex {
132    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
133        serializer.collect_str(&format_args!("{:#x}", self.0))
134    }
135}
136
137impl<'de> Deserialize<'de> for TraceAddressIndex {
138    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
139        let value = String::deserialize(deserializer)?;
140        let digits = value
141            .strip_prefix("0x")
142            .filter(|digits| {
143                matches!(digits.as_bytes(), [b'0'] | [b'1'..=b'9' | b'a'..=b'f', ..]) &&
144                    digits.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
145            })
146            .ok_or_else(|| {
147                de::Error::invalid_value(de::Unexpected::Str(&value), &"a hex quantity")
148            })?;
149        usize::from_str_radix(digits, 16).map(Self).map_err(de::Error::custom)
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156    use serde_json::json;
157
158    #[test]
159    fn trace_address_index_accepts_hex_quantities() {
160        for (value, expected) in [("0x0", 0), ("0x6", 6), ("0xa0", 160)] {
161            let index = serde_json::from_value::<TraceAddressIndex>(json!(value)).unwrap();
162            assert_eq!(index, TraceAddressIndex(expected));
163            assert_eq!(serde_json::to_value(index).unwrap(), json!(value));
164        }
165        let max = format!("{:#x}", usize::MAX);
166        let index = serde_json::from_value::<TraceAddressIndex>(json!(max)).unwrap();
167        assert_eq!(index, TraceAddressIndex(usize::MAX));
168        assert_eq!(serde_json::to_value(index).unwrap(), json!(max));
169    }
170
171    #[test]
172    fn trace_address_index_rejects_other_encodings() {
173        assert_eq!(
174            serde_json::from_value::<TraceAddressIndex>(json!(6)).unwrap_err().to_string(),
175            "invalid type: integer `6`, expected a string"
176        );
177        for value in ["6", "0x", "0x00", "0x06", "0xA", "0x1A", "0x+1"] {
178            assert_eq!(
179                serde_json::from_value::<TraceAddressIndex>(json!(value)).unwrap_err().to_string(),
180                format!("invalid value: string {value:?}, expected a hex quantity")
181            );
182        }
183        let overflow = format!("{:#x}0", usize::MAX);
184        assert_eq!(
185            serde_json::from_value::<TraceAddressIndex>(json!(overflow)).unwrap_err().to_string(),
186            "number too large to fit in target type"
187        );
188    }
189}