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