reth_rpc_api_testing_util/
debug.rs
1use 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
24pub type TraceTransactionResult = Result<(serde_json::Value, TxHash), (RpcError, TxHash)>;
26
27pub type DebugTraceBlockResult =
29 Result<(Vec<TraceResult<GethTrace, String>>, BlockId), (RpcError, BlockId)>;
30
31pub trait DebugApiExt {
33 type Provider;
35
36 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 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 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 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 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) => self.debug_trace_block_by_hash(hash.block_hash, opts),
136 BlockId::Number(tag) => self.debug_trace_block_by_number(tag, opts),
137 };
138
139 match trace_future.await {
140 Ok(result) => Ok((result, block)),
141 Err(err) => Err((err, block)),
142 }
143 }))
144 .buffer_unordered(n);
145 DebugTraceBlockStream { stream: Box::pin(stream) }
146 }
147
148 async fn debug_trace_call_json(
149 &self,
150 request: TransactionRequest,
151 opts: GethDebugTracingOptions,
152 ) -> Result<serde_json::Value, RpcError> {
153 let mut params = jsonrpsee::core::params::ArrayParams::new();
154 params.insert(request).unwrap();
155 params.insert(opts).unwrap();
156 self.request("debug_traceCall", params).await
157 }
158
159 async fn debug_trace_call_raw_json(
160 &self,
161 request_json: String,
162 opts_json: String,
163 ) -> Result<serde_json::Value, RpcError> {
164 let request = serde_json::from_str::<TransactionRequest>(&request_json)
165 .map_err(|e| RpcError::Custom(e.to_string()))?;
166 let opts = serde_json::from_str::<GethDebugTracingOptions>(&opts_json)
167 .map_err(|e| RpcError::Custom(e.to_string()))?;
168
169 self.debug_trace_call_json(request, opts).await
170 }
171}
172
173#[derive(Debug, Clone, Default)]
175pub struct JsTracerBuilder {
176 setup_body: Option<String>,
179
180 fault_body: Option<String>,
183
184 result_body: Option<String>,
186
187 enter_body: Option<String>,
189
190 step_body: Option<String>,
193
194 exit_body: Option<String>,
196}
197
198impl JsTracerBuilder {
199 pub fn fault_body(mut self, body: impl Into<String>) -> Self {
203 self.fault_body = Some(body.into());
204 self
205 }
206
207 pub fn setup_body(mut self, body: impl Into<String>) -> Self {
211 self.setup_body = Some(body.into());
212 self
213 }
214
215 pub fn result_body(mut self, body: impl Into<String>) -> Self {
224 self.result_body = Some(body.into());
225 self
226 }
227
228 pub fn enter_body(mut self, body: impl Into<String>) -> Self {
232 self.enter_body = Some(body.into());
233 self
234 }
235
236 pub fn step_body(mut self, body: impl Into<String>) -> Self {
240 self.step_body = Some(body.into());
241 self
242 }
243
244 pub fn exit_body(mut self, body: impl Into<String>) -> Self {
248 self.exit_body = Some(body.into());
249 self
250 }
251
252 pub fn code(self) -> String {
254 let mut template = JS_TRACER_TEMPLATE.to_string();
255 template = template.replace("//<setup>", self.setup_body.as_deref().unwrap_or_default());
256 template = template.replace("//<fault>", self.fault_body.as_deref().unwrap_or_default());
257 template =
258 template.replace("//<result>", self.result_body.as_deref().unwrap_or("return {};"));
259 template = template.replace("//<step>", self.step_body.as_deref().unwrap_or_default());
260 template = template.replace("//<enter>", self.enter_body.as_deref().unwrap_or_default());
261 template = template.replace("//<exit>", self.exit_body.as_deref().unwrap_or_default());
262 template
263 }
264}
265
266impl std::fmt::Display for JsTracerBuilder {
267 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
268 write!(f, "{}", self.clone().code())
269 }
270}
271
272impl From<JsTracerBuilder> for GethDebugTracingOptions {
273 fn from(b: JsTracerBuilder) -> Self {
274 Self {
275 tracer: Some(GethDebugTracerType::JsTracer(b.code())),
276 tracer_config: serde_json::Value::Object(Default::default()).into(),
277 ..Default::default()
278 }
279 }
280}
281impl From<JsTracerBuilder> for Option<GethDebugTracingOptions> {
282 fn from(b: JsTracerBuilder) -> Self {
283 Some(b.into())
284 }
285}
286
287#[must_use = "streams do nothing unless polled"]
289pub struct DebugTraceTransactionsStream<'a> {
290 stream: Pin<Box<dyn Stream<Item = TraceTransactionResult> + 'a>>,
291}
292
293impl DebugTraceTransactionsStream<'_> {
294 pub async fn next_err(&mut self) -> Option<(RpcError, TxHash)> {
296 loop {
297 match self.next().await? {
298 Ok(_) => {}
299 Err(err) => return Some(err),
300 }
301 }
302 }
303}
304
305impl Stream for DebugTraceTransactionsStream<'_> {
306 type Item = TraceTransactionResult;
307
308 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
309 self.stream.as_mut().poll_next(cx)
310 }
311}
312
313impl std::fmt::Debug for DebugTraceTransactionsStream<'_> {
314 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
315 f.debug_struct("DebugTraceTransactionsStream").finish_non_exhaustive()
316 }
317}
318
319#[must_use = "streams do nothing unless polled"]
321pub struct DebugTraceBlockStream<'a> {
322 stream: Pin<Box<dyn Stream<Item = DebugTraceBlockResult> + 'a>>,
323}
324
325impl DebugTraceBlockStream<'_> {
326 pub async fn next_err(&mut self) -> Option<(RpcError, BlockId)> {
328 loop {
329 match self.next().await? {
330 Ok(_) => {}
331 Err(err) => return Some(err),
332 }
333 }
334 }
335}
336
337impl Stream for DebugTraceBlockStream<'_> {
338 type Item = DebugTraceBlockResult;
339
340 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
341 self.stream.as_mut().poll_next(cx)
342 }
343}
344
345impl std::fmt::Debug for DebugTraceBlockStream<'_> {
346 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
347 f.debug_struct("DebugTraceBlockStream").finish_non_exhaustive()
348 }
349}
350
351#[derive(Debug, Clone, Copy, Default)]
353#[non_exhaustive]
354pub struct NoopJsTracer;
355
356impl From<NoopJsTracer> for GethDebugTracingOptions {
357 fn from(_: NoopJsTracer) -> Self {
358 Self {
359 tracer: Some(GethDebugTracerType::JsTracer(NOOP_TRACER.to_string())),
360 tracer_config: serde_json::Value::Object(Default::default()).into(),
361 ..Default::default()
362 }
363 }
364}
365impl From<NoopJsTracer> for Option<GethDebugTracingOptions> {
366 fn from(_: NoopJsTracer) -> Self {
367 Some(NoopJsTracer.into())
368 }
369}
370
371#[cfg(test)]
372mod tests {
373 use crate::{
374 debug::{DebugApiExt, JsTracerBuilder, NoopJsTracer},
375 utils::parse_env_url,
376 };
377 use alloy_rpc_types_trace::geth::{CallConfig, GethDebugTracingOptions};
378 use futures::StreamExt;
379 use jsonrpsee::http_client::HttpClientBuilder;
380
381 const TX_1: &str = "0x5525c63a805df2b83c113ebcc8c7672a3b290673c4e81335b410cd9ebc64e085";
383
384 #[tokio::test]
385 #[ignore]
386 async fn can_trace_noop_sepolia() {
387 let tx = TX_1.parse().unwrap();
388 let url = parse_env_url("RETH_RPC_TEST_NODE_URL").unwrap();
389 let client = HttpClientBuilder::default().build(url).unwrap();
390 let res =
391 client.debug_trace_transaction_json(tx, NoopJsTracer::default().into()).await.unwrap();
392 assert_eq!(res, serde_json::Value::Object(Default::default()));
393 }
394
395 #[tokio::test]
396 #[ignore]
397 async fn can_trace_default_template() {
398 let tx = TX_1.parse().unwrap();
399 let url = parse_env_url("RETH_RPC_TEST_NODE_URL").unwrap();
400 let client = HttpClientBuilder::default().build(url).unwrap();
401 let res = client
402 .debug_trace_transaction_json(tx, JsTracerBuilder::default().into())
403 .await
404 .unwrap();
405 assert_eq!(res, serde_json::Value::Object(Default::default()));
406 }
407
408 #[tokio::test]
409 #[ignore]
410 async fn can_debug_trace_block_transactions() {
411 let block = 11_117_104u64;
412 let url = parse_env_url("RETH_RPC_TEST_NODE_URL").unwrap();
413 let client = HttpClientBuilder::default().build(url).unwrap();
414
415 let opts = GethDebugTracingOptions::default()
416 .with_call_config(CallConfig::default().only_top_call());
417
418 let mut stream = client.debug_trace_transactions_in_block(block, opts).await.unwrap();
419 while let Some(res) = stream.next().await {
420 if let Err((err, tx)) = res {
421 println!("failed to trace {tx:?} {err}");
422 }
423 }
424 }
425}