reth_rpc_api_testing_util/
debug.rs

1//! Helpers for testing debug trace calls.
2
3use std::{
4    future::Future,
5    pin::Pin,
6    task::{Context, Poll},
7};
8
9use alloy_eips::BlockId;
10use alloy_primitives::{TxHash, B256};
11use alloy_rpc_types_eth::{transaction::TransactionRequest, Block, Header, Transaction};
12use alloy_rpc_types_trace::{
13    common::TraceResult,
14    geth::{GethDebugTracerType, GethDebugTracingOptions, GethTrace},
15};
16use futures::{Stream, StreamExt};
17use jsonrpsee::core::client::Error as RpcError;
18use reth_ethereum_primitives::Receipt;
19use reth_rpc_api::{clients::DebugApiClient, EthApiClient};
20
21const NOOP_TRACER: &str = include_str!("../assets/noop-tracer.js");
22const JS_TRACER_TEMPLATE: &str = include_str!("../assets/tracer-template.js");
23
24/// A result type for the `debug_trace_transaction` method that also captures the requested hash.
25pub type TraceTransactionResult = Result<(serde_json::Value, TxHash), (RpcError, TxHash)>;
26
27/// A result type for the `debug_trace_block` method that also captures the requested block.
28pub type DebugTraceBlockResult =
29    Result<(Vec<TraceResult<GethTrace, String>>, BlockId), (RpcError, BlockId)>;
30
31/// An extension trait for the Trace API.
32pub trait DebugApiExt {
33    /// The provider type that is used to make the requests.
34    type Provider;
35
36    /// Same as [`DebugApiClient::debug_trace_transaction`] but returns the result as json.
37    fn debug_trace_transaction_json(
38        &self,
39        hash: B256,
40        opts: GethDebugTracingOptions,
41    ) -> impl Future<Output = Result<serde_json::Value, RpcError>> + Send;
42
43    /// Trace all transactions in a block individually with the given tracing opts.
44    fn debug_trace_transactions_in_block<B>(
45        &self,
46        block: B,
47        opts: GethDebugTracingOptions,
48    ) -> impl Future<Output = Result<DebugTraceTransactionsStream<'_>, RpcError>> + Send
49    where
50        B: Into<BlockId> + Send;
51
52    /// Trace all given blocks with the given tracing opts, returning a stream.
53    fn debug_trace_block_buffered_unordered<I, B>(
54        &self,
55        params: I,
56        opts: Option<GethDebugTracingOptions>,
57        n: usize,
58    ) -> DebugTraceBlockStream<'_>
59    where
60        I: IntoIterator<Item = B>,
61        B: Into<BlockId> + Send;
62
63    ///  method  for `debug_traceCall`
64    fn debug_trace_call_json(
65        &self,
66        request: TransactionRequest,
67        opts: GethDebugTracingOptions,
68    ) -> impl Future<Output = Result<serde_json::Value, RpcError>> + Send;
69
70    ///  method for `debug_traceCall` using raw JSON strings for the request and options.
71    fn debug_trace_call_raw_json(
72        &self,
73        request_json: String,
74        opts_json: String,
75    ) -> impl Future<Output = Result<serde_json::Value, RpcError>> + Send;
76}
77
78impl<T> DebugApiExt for T
79where
80    T: EthApiClient<TransactionRequest, Transaction, Block, Receipt, Header>
81        + DebugApiClient<TransactionRequest>
82        + Sync,
83{
84    type Provider = T;
85
86    async fn debug_trace_transaction_json(
87        &self,
88        hash: B256,
89        opts: GethDebugTracingOptions,
90    ) -> Result<serde_json::Value, RpcError> {
91        let mut params = jsonrpsee::core::params::ArrayParams::new();
92        params.insert(hash).unwrap();
93        params.insert(opts).unwrap();
94        self.request("debug_traceTransaction", params).await
95    }
96
97    async fn debug_trace_transactions_in_block<B>(
98        &self,
99        block: B,
100        opts: GethDebugTracingOptions,
101    ) -> Result<DebugTraceTransactionsStream<'_>, RpcError>
102    where
103        B: Into<BlockId> + Send,
104    {
105        let block = match block.into() {
106            BlockId::Hash(hash) => self.block_by_hash(hash.block_hash, false).await,
107            BlockId::Number(tag) => self.block_by_number(tag, false).await,
108        }?
109        .ok_or_else(|| RpcError::Custom("block not found".to_string()))?;
110        let hashes = block.transactions.hashes().map(|tx| (tx, opts.clone())).collect::<Vec<_>>();
111        let stream = futures::stream::iter(hashes.into_iter().map(move |(tx, opts)| async move {
112            match self.debug_trace_transaction_json(tx, opts).await {
113                Ok(result) => Ok((result, tx)),
114                Err(err) => Err((err, tx)),
115            }
116        }))
117        .buffered(10);
118
119        Ok(DebugTraceTransactionsStream { stream: Box::pin(stream) })
120    }
121
122    fn debug_trace_block_buffered_unordered<I, B>(
123        &self,
124        params: I,
125        opts: Option<GethDebugTracingOptions>,
126        n: usize,
127    ) -> DebugTraceBlockStream<'_>
128    where
129        I: IntoIterator<Item = B>,
130        B: Into<BlockId> + Send,
131    {
132        let blocks =
133            params.into_iter().map(|block| (block.into(), opts.clone())).collect::<Vec<_>>();
134        let stream =
135            futures::stream::iter(blocks.into_iter().map(move |(block, opts)| async move {
136                let trace_future = match block {
137                    BlockId::Hash(hash) => {
138                        self.debug_trace_block_by_hash(hash.block_hash, opts).await
139                    }
140                    BlockId::Number(tag) => self.debug_trace_block_by_number(tag, opts).await,
141                };
142
143                match trace_future {
144                    Ok(result) => Ok((result, block)),
145                    Err(err) => Err((err, block)),
146                }
147            }))
148            .buffer_unordered(n);
149        DebugTraceBlockStream { stream: Box::pin(stream) }
150    }
151
152    async fn debug_trace_call_json(
153        &self,
154        request: TransactionRequest,
155        opts: GethDebugTracingOptions,
156    ) -> Result<serde_json::Value, RpcError> {
157        let mut params = jsonrpsee::core::params::ArrayParams::new();
158        params.insert(request).unwrap();
159        params.insert(opts).unwrap();
160        self.request("debug_traceCall", params).await
161    }
162
163    async fn debug_trace_call_raw_json(
164        &self,
165        request_json: String,
166        opts_json: String,
167    ) -> Result<serde_json::Value, RpcError> {
168        let request = serde_json::from_str::<TransactionRequest>(&request_json)
169            .map_err(|e| RpcError::Custom(e.to_string()))?;
170        let opts = serde_json::from_str::<GethDebugTracingOptions>(&opts_json)
171            .map_err(|e| RpcError::Custom(e.to_string()))?;
172
173        self.debug_trace_call_json(request, opts).await
174    }
175}
176
177/// A helper type that can be used to build a javascript tracer.
178#[derive(Debug, Clone, Default)]
179pub struct JsTracerBuilder {
180    /// `setup_body` is invoked once at the beginning, during the construction of a given
181    /// transaction.
182    setup_body: Option<String>,
183
184    /// `fault_body` is invoked when an error happens during the execution of an opcode which
185    /// wasn't reported in step.
186    fault_body: Option<String>,
187
188    /// `result_body` returns a JSON-serializable value to the RPC caller.
189    result_body: Option<String>,
190
191    /// `enter_body` is invoked on stepping in of an internal call.
192    enter_body: Option<String>,
193
194    /// `step_body` is called for each step of the EVM, or when an error occurs, as the specified
195    /// transaction is traced.
196    step_body: Option<String>,
197
198    /// `exit_body` is invoked on stepping out of an internal call.
199    exit_body: Option<String>,
200}
201
202impl JsTracerBuilder {
203    /// Sets the body of the fault function
204    ///
205    /// The body code has access to the `log` and `db` variables.
206    pub fn fault_body(mut self, body: impl Into<String>) -> Self {
207        self.fault_body = Some(body.into());
208        self
209    }
210
211    /// Sets the body of the setup function
212    ///
213    /// This body includes the `cfg` object variable
214    pub fn setup_body(mut self, body: impl Into<String>) -> Self {
215        self.setup_body = Some(body.into());
216        self
217    }
218
219    /// Sets the body of the result function
220    ///
221    /// The body code has access to the `ctx` and `db` variables.
222    ///
223    /// ```
224    /// use reth_rpc_api_testing_util::debug::JsTracerBuilder;
225    /// let code = JsTracerBuilder::default().result_body("return {};").code();
226    /// ```
227    pub fn result_body(mut self, body: impl Into<String>) -> Self {
228        self.result_body = Some(body.into());
229        self
230    }
231
232    /// Sets the body of the enter function
233    ///
234    /// The body code has access to the `frame` variable.
235    pub fn enter_body(mut self, body: impl Into<String>) -> Self {
236        self.enter_body = Some(body.into());
237        self
238    }
239
240    /// Sets the body of the step function
241    ///
242    /// The body code has access to the `log` and `db` variables.
243    pub fn step_body(mut self, body: impl Into<String>) -> Self {
244        self.step_body = Some(body.into());
245        self
246    }
247
248    /// Sets the body of the exit function
249    ///
250    /// The body code has access to the `res` variable.
251    pub fn exit_body(mut self, body: impl Into<String>) -> Self {
252        self.exit_body = Some(body.into());
253        self
254    }
255
256    /// Returns the tracers JS code
257    pub fn code(self) -> String {
258        let mut template = JS_TRACER_TEMPLATE.to_string();
259        template = template.replace("//<setup>", self.setup_body.as_deref().unwrap_or_default());
260        template = template.replace("//<fault>", self.fault_body.as_deref().unwrap_or_default());
261        template =
262            template.replace("//<result>", self.result_body.as_deref().unwrap_or("return {};"));
263        template = template.replace("//<step>", self.step_body.as_deref().unwrap_or_default());
264        template = template.replace("//<enter>", self.enter_body.as_deref().unwrap_or_default());
265        template = template.replace("//<exit>", self.exit_body.as_deref().unwrap_or_default());
266        template
267    }
268}
269
270impl std::fmt::Display for JsTracerBuilder {
271    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
272        write!(f, "{}", self.clone().code())
273    }
274}
275
276impl From<JsTracerBuilder> for GethDebugTracingOptions {
277    fn from(b: JsTracerBuilder) -> Self {
278        Self {
279            tracer: Some(GethDebugTracerType::JsTracer(b.code())),
280            tracer_config: serde_json::Value::Object(Default::default()).into(),
281            ..Default::default()
282        }
283    }
284}
285impl From<JsTracerBuilder> for Option<GethDebugTracingOptions> {
286    fn from(b: JsTracerBuilder) -> Self {
287        Some(b.into())
288    }
289}
290
291/// A stream that yields the traces for the requested blocks.
292#[must_use = "streams do nothing unless polled"]
293pub struct DebugTraceTransactionsStream<'a> {
294    stream: Pin<Box<dyn Stream<Item = TraceTransactionResult> + 'a>>,
295}
296
297impl DebugTraceTransactionsStream<'_> {
298    /// Returns the next error result of the stream.
299    pub async fn next_err(&mut self) -> Option<(RpcError, TxHash)> {
300        loop {
301            match self.next().await? {
302                Ok(_) => {}
303                Err(err) => return Some(err),
304            }
305        }
306    }
307}
308
309impl Stream for DebugTraceTransactionsStream<'_> {
310    type Item = TraceTransactionResult;
311
312    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
313        self.stream.as_mut().poll_next(cx)
314    }
315}
316
317impl std::fmt::Debug for DebugTraceTransactionsStream<'_> {
318    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
319        f.debug_struct("DebugTraceTransactionsStream").finish_non_exhaustive()
320    }
321}
322
323/// A stream that yields the `debug_` traces for the requested blocks.
324#[must_use = "streams do nothing unless polled"]
325pub struct DebugTraceBlockStream<'a> {
326    stream: Pin<Box<dyn Stream<Item = DebugTraceBlockResult> + 'a>>,
327}
328
329impl DebugTraceBlockStream<'_> {
330    /// Returns the next error result of the stream.
331    pub async fn next_err(&mut self) -> Option<(RpcError, BlockId)> {
332        loop {
333            match self.next().await? {
334                Ok(_) => {}
335                Err(err) => return Some(err),
336            }
337        }
338    }
339}
340
341impl Stream for DebugTraceBlockStream<'_> {
342    type Item = DebugTraceBlockResult;
343
344    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
345        self.stream.as_mut().poll_next(cx)
346    }
347}
348
349impl std::fmt::Debug for DebugTraceBlockStream<'_> {
350    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
351        f.debug_struct("DebugTraceBlockStream").finish_non_exhaustive()
352    }
353}
354
355/// A javascript tracer that does nothing
356#[derive(Debug, Clone, Copy, Default)]
357#[non_exhaustive]
358pub struct NoopJsTracer;
359
360impl From<NoopJsTracer> for GethDebugTracingOptions {
361    fn from(_: NoopJsTracer) -> Self {
362        Self {
363            tracer: Some(GethDebugTracerType::JsTracer(NOOP_TRACER.to_string())),
364            tracer_config: serde_json::Value::Object(Default::default()).into(),
365            ..Default::default()
366        }
367    }
368}
369impl From<NoopJsTracer> for Option<GethDebugTracingOptions> {
370    fn from(_: NoopJsTracer) -> Self {
371        Some(NoopJsTracer.into())
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use crate::{
378        debug::{DebugApiExt, JsTracerBuilder, NoopJsTracer},
379        utils::parse_env_url,
380    };
381    use alloy_rpc_types_trace::geth::{CallConfig, GethDebugTracingOptions};
382    use futures::StreamExt;
383    use jsonrpsee::http_client::HttpClientBuilder;
384
385    // random tx <https://sepolia.etherscan.io/tx/0x5525c63a805df2b83c113ebcc8c7672a3b290673c4e81335b410cd9ebc64e085>
386    const TX_1: &str = "0x5525c63a805df2b83c113ebcc8c7672a3b290673c4e81335b410cd9ebc64e085";
387
388    #[tokio::test]
389    #[ignore]
390    async fn can_trace_noop_sepolia() {
391        let tx = TX_1.parse().unwrap();
392        let url = parse_env_url("RETH_RPC_TEST_NODE_URL").unwrap();
393        let client = HttpClientBuilder::default().build(url).unwrap();
394        let res =
395            client.debug_trace_transaction_json(tx, NoopJsTracer::default().into()).await.unwrap();
396        assert_eq!(res, serde_json::Value::Object(Default::default()));
397    }
398
399    #[tokio::test]
400    #[ignore]
401    async fn can_trace_default_template() {
402        let tx = TX_1.parse().unwrap();
403        let url = parse_env_url("RETH_RPC_TEST_NODE_URL").unwrap();
404        let client = HttpClientBuilder::default().build(url).unwrap();
405        let res = client
406            .debug_trace_transaction_json(tx, JsTracerBuilder::default().into())
407            .await
408            .unwrap();
409        assert_eq!(res, serde_json::Value::Object(Default::default()));
410    }
411
412    #[tokio::test]
413    #[ignore]
414    async fn can_debug_trace_block_transactions() {
415        let block = 11_117_104u64;
416        let url = parse_env_url("RETH_RPC_TEST_NODE_URL").unwrap();
417        let client = HttpClientBuilder::default().build(url).unwrap();
418
419        let opts = GethDebugTracingOptions::default()
420            .with_call_config(CallConfig::default().only_top_call());
421
422        let mut stream = client.debug_trace_transactions_in_block(block, opts).await.unwrap();
423        while let Some(res) = stream.next().await {
424            if let Err((err, tx)) = res {
425                println!("failed to trace {tx:?}  {err}");
426            }
427        }
428    }
429}