1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Helpers for testing debug trace calls.

use std::{
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};

use alloy_primitives::{TxHash, B256};
use futures::{Stream, StreamExt};
use jsonrpsee::core::client::Error as RpcError;
use reth_primitives::{BlockId, Receipt};
use reth_rpc_api::{clients::DebugApiClient, EthApiClient};
use reth_rpc_types::{
    trace::{
        common::TraceResult,
        geth::{GethDebugTracerType, GethDebugTracingOptions, GethTrace},
    },
    Block, Transaction, TransactionRequest,
};

const NOOP_TRACER: &str = include_str!("../assets/noop-tracer.js");
const JS_TRACER_TEMPLATE: &str = include_str!("../assets/tracer-template.js");

/// A result type for the `debug_trace_transaction` method that also captures the requested hash.
pub type TraceTransactionResult = Result<(serde_json::Value, TxHash), (RpcError, TxHash)>;

/// A result type for the `debug_trace_block` method that also captures the requested block.
pub type DebugTraceBlockResult =
    Result<(Vec<TraceResult<GethTrace, String>>, BlockId), (RpcError, BlockId)>;

/// An extension trait for the Trace API.
pub trait DebugApiExt {
    /// The provider type that is used to make the requests.
    type Provider;

    /// Same as [`DebugApiClient::debug_trace_transaction`] but returns the result as json.
    fn debug_trace_transaction_json(
        &self,
        hash: B256,
        opts: GethDebugTracingOptions,
    ) -> impl Future<Output = Result<serde_json::Value, RpcError>> + Send;

    /// Trace all transactions in a block individually with the given tracing opts.
    fn debug_trace_transactions_in_block<B>(
        &self,
        block: B,
        opts: GethDebugTracingOptions,
    ) -> impl Future<Output = Result<DebugTraceTransactionsStream<'_>, RpcError>> + Send
    where
        B: Into<BlockId> + Send;

    /// Trace all given blocks with the given tracing opts, returning a stream.
    fn debug_trace_block_buffered_unordered<I, B>(
        &self,
        params: I,
        opts: Option<GethDebugTracingOptions>,
        n: usize,
    ) -> DebugTraceBlockStream<'_>
    where
        I: IntoIterator<Item = B>,
        B: Into<BlockId> + Send;

    ///  method  for `debug_traceCall`
    fn debug_trace_call_json(
        &self,
        request: TransactionRequest,
        opts: GethDebugTracingOptions,
    ) -> impl Future<Output = Result<serde_json::Value, RpcError>> + Send;

    ///  method for `debug_traceCall` using raw JSON strings for the request and options.
    fn debug_trace_call_raw_json(
        &self,
        request_json: String,
        opts_json: String,
    ) -> impl Future<Output = Result<serde_json::Value, RpcError>> + Send;
}

impl<T> DebugApiExt for T
where
    T: EthApiClient<Transaction, Block, Receipt> + DebugApiClient + Sync,
{
    type Provider = T;

    async fn debug_trace_transaction_json(
        &self,
        hash: B256,
        opts: GethDebugTracingOptions,
    ) -> Result<serde_json::Value, RpcError> {
        let mut params = jsonrpsee::core::params::ArrayParams::new();
        params.insert(hash).unwrap();
        params.insert(opts).unwrap();
        self.request("debug_traceTransaction", params).await
    }

    async fn debug_trace_transactions_in_block<B>(
        &self,
        block: B,
        opts: GethDebugTracingOptions,
    ) -> Result<DebugTraceTransactionsStream<'_>, RpcError>
    where
        B: Into<BlockId> + Send,
    {
        let block = match block.into() {
            BlockId::Hash(hash) => self.block_by_hash(hash.block_hash, false).await,
            BlockId::Number(tag) => self.block_by_number(tag, false).await,
        }?
        .ok_or_else(|| RpcError::Custom("block not found".to_string()))?;
        let hashes = block.transactions.hashes().map(|tx| (tx, opts.clone())).collect::<Vec<_>>();
        let stream = futures::stream::iter(hashes.into_iter().map(move |(tx, opts)| async move {
            match self.debug_trace_transaction_json(tx, opts).await {
                Ok(result) => Ok((result, tx)),
                Err(err) => Err((err, tx)),
            }
        }))
        .buffered(10);

        Ok(DebugTraceTransactionsStream { stream: Box::pin(stream) })
    }

    fn debug_trace_block_buffered_unordered<I, B>(
        &self,
        params: I,
        opts: Option<GethDebugTracingOptions>,
        n: usize,
    ) -> DebugTraceBlockStream<'_>
    where
        I: IntoIterator<Item = B>,
        B: Into<BlockId> + Send,
    {
        let blocks =
            params.into_iter().map(|block| (block.into(), opts.clone())).collect::<Vec<_>>();
        let stream =
            futures::stream::iter(blocks.into_iter().map(move |(block, opts)| async move {
                let trace_future = match block {
                    BlockId::Hash(hash) => {
                        self.debug_trace_block_by_hash(hash.block_hash, opts.clone())
                    }
                    BlockId::Number(tag) => self.debug_trace_block_by_number(tag, opts.clone()),
                };

                match trace_future.await {
                    Ok(result) => Ok((result, block)),
                    Err(err) => Err((err, block)),
                }
            }))
            .buffer_unordered(n);
        DebugTraceBlockStream { stream: Box::pin(stream) }
    }

    async fn debug_trace_call_json(
        &self,
        request: TransactionRequest,
        opts: GethDebugTracingOptions,
    ) -> Result<serde_json::Value, RpcError> {
        let mut params = jsonrpsee::core::params::ArrayParams::new();
        params.insert(request).unwrap();
        params.insert(opts).unwrap();
        self.request("debug_traceCall", params).await
    }

    async fn debug_trace_call_raw_json(
        &self,
        request_json: String,
        opts_json: String,
    ) -> Result<serde_json::Value, RpcError> {
        let request = serde_json::from_str::<TransactionRequest>(&request_json)
            .map_err(|e| RpcError::Custom(e.to_string()))?;
        let opts = serde_json::from_str::<GethDebugTracingOptions>(&opts_json)
            .map_err(|e| RpcError::Custom(e.to_string()))?;

        self.debug_trace_call_json(request, opts).await
    }
}

/// A helper type that can be used to build a javascript tracer.
#[derive(Debug, Clone, Default)]
pub struct JsTracerBuilder {
    /// `setup_body` is invoked once at the beginning, during the construction of a given
    /// transaction.
    setup_body: Option<String>,

    /// `fault_body` is invoked when an error happens during the execution of an opcode which
    /// wasn't reported in step.
    fault_body: Option<String>,

    /// `result_body` returns a JSON-serializable value to the RPC caller.
    result_body: Option<String>,

    /// `enter_body` is invoked on stepping in of an internal call.
    enter_body: Option<String>,

    /// `step_body` is called for each step of the EVM, or when an error occurs, as the specified
    /// transaction is traced.
    step_body: Option<String>,

    /// `exit_body` is invoked on stepping out of an internal call.
    exit_body: Option<String>,
}

impl JsTracerBuilder {
    /// Sets the body of the fault function
    ///
    /// The body code has access to the `log` and `db` variables.
    pub fn fault_body(mut self, body: impl Into<String>) -> Self {
        self.fault_body = Some(body.into());
        self
    }

    /// Sets the body of the setup function
    ///
    /// This body includes the `cfg` object variable
    pub fn setup_body(mut self, body: impl Into<String>) -> Self {
        self.setup_body = Some(body.into());
        self
    }

    /// Sets the body of the result function
    ///
    /// The body code has access to the `ctx` and `db` variables.
    ///
    /// ```
    /// use reth_rpc_api_testing_util::debug::JsTracerBuilder;
    /// let code = JsTracerBuilder::default().result_body("return {};").code();
    /// ```
    pub fn result_body(mut self, body: impl Into<String>) -> Self {
        self.result_body = Some(body.into());
        self
    }

    /// Sets the body of the enter function
    ///
    /// The body code has access to the `frame` variable.
    pub fn enter_body(mut self, body: impl Into<String>) -> Self {
        self.enter_body = Some(body.into());
        self
    }

    /// Sets the body of the step function
    ///
    /// The body code has access to the `log` and `db` variables.
    pub fn step_body(mut self, body: impl Into<String>) -> Self {
        self.step_body = Some(body.into());
        self
    }

    /// Sets the body of the exit function
    ///
    /// The body code has access to the `res` variable.
    pub fn exit_body(mut self, body: impl Into<String>) -> Self {
        self.exit_body = Some(body.into());
        self
    }

    /// Returns the tracers JS code
    pub fn code(self) -> String {
        let mut template = JS_TRACER_TEMPLATE.to_string();
        template = template.replace("//<setup>", self.setup_body.as_deref().unwrap_or_default());
        template = template.replace("//<fault>", self.fault_body.as_deref().unwrap_or_default());
        template =
            template.replace("//<result>", self.result_body.as_deref().unwrap_or("return {};"));
        template = template.replace("//<step>", self.step_body.as_deref().unwrap_or_default());
        template = template.replace("//<enter>", self.enter_body.as_deref().unwrap_or_default());
        template = template.replace("//<exit>", self.exit_body.as_deref().unwrap_or_default());
        template
    }
}

impl std::fmt::Display for JsTracerBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.clone().code())
    }
}

impl From<JsTracerBuilder> for GethDebugTracingOptions {
    fn from(b: JsTracerBuilder) -> Self {
        Self {
            tracer: Some(GethDebugTracerType::JsTracer(b.code())),
            tracer_config: serde_json::Value::Object(Default::default()).into(),
            ..Default::default()
        }
    }
}
impl From<JsTracerBuilder> for Option<GethDebugTracingOptions> {
    fn from(b: JsTracerBuilder) -> Self {
        Some(b.into())
    }
}

/// A stream that yields the traces for the requested blocks.
#[must_use = "streams do nothing unless polled"]
pub struct DebugTraceTransactionsStream<'a> {
    stream: Pin<Box<dyn Stream<Item = TraceTransactionResult> + 'a>>,
}

impl<'a> DebugTraceTransactionsStream<'a> {
    /// Returns the next error result of the stream.
    pub async fn next_err(&mut self) -> Option<(RpcError, TxHash)> {
        loop {
            match self.next().await? {
                Ok(_) => continue,
                Err(err) => return Some(err),
            }
        }
    }
}

impl<'a> Stream for DebugTraceTransactionsStream<'a> {
    type Item = TraceTransactionResult;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.stream.as_mut().poll_next(cx)
    }
}

impl<'a> std::fmt::Debug for DebugTraceTransactionsStream<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DebugTraceTransactionsStream").finish_non_exhaustive()
    }
}

/// A stream that yields the `debug_` traces for the requested blocks.
#[must_use = "streams do nothing unless polled"]
pub struct DebugTraceBlockStream<'a> {
    stream: Pin<Box<dyn Stream<Item = DebugTraceBlockResult> + 'a>>,
}

impl<'a> DebugTraceBlockStream<'a> {
    /// Returns the next error result of the stream.
    pub async fn next_err(&mut self) -> Option<(RpcError, BlockId)> {
        loop {
            match self.next().await? {
                Ok(_) => continue,
                Err(err) => return Some(err),
            }
        }
    }
}

impl<'a> Stream for DebugTraceBlockStream<'a> {
    type Item = DebugTraceBlockResult;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.stream.as_mut().poll_next(cx)
    }
}

impl<'a> std::fmt::Debug for DebugTraceBlockStream<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DebugTraceBlockStream").finish_non_exhaustive()
    }
}

/// A javascript tracer that does nothing
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct NoopJsTracer;

impl From<NoopJsTracer> for GethDebugTracingOptions {
    fn from(_: NoopJsTracer) -> Self {
        Self {
            tracer: Some(GethDebugTracerType::JsTracer(NOOP_TRACER.to_string())),
            tracer_config: serde_json::Value::Object(Default::default()).into(),
            ..Default::default()
        }
    }
}
impl From<NoopJsTracer> for Option<GethDebugTracingOptions> {
    fn from(_: NoopJsTracer) -> Self {
        Some(NoopJsTracer.into())
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        debug::{DebugApiExt, JsTracerBuilder, NoopJsTracer},
        utils::parse_env_url,
    };
    use futures::StreamExt;
    use jsonrpsee::http_client::HttpClientBuilder;
    use reth_rpc_types::trace::geth::{CallConfig, GethDebugTracingOptions};

    // random tx <https://sepolia.etherscan.io/tx/0x5525c63a805df2b83c113ebcc8c7672a3b290673c4e81335b410cd9ebc64e085>
    const TX_1: &str = "0x5525c63a805df2b83c113ebcc8c7672a3b290673c4e81335b410cd9ebc64e085";

    #[tokio::test]
    #[ignore]
    async fn can_trace_noop_sepolia() {
        let tx = TX_1.parse().unwrap();
        let url = parse_env_url("RETH_RPC_TEST_NODE_URL").unwrap();
        let client = HttpClientBuilder::default().build(url).unwrap();
        let res =
            client.debug_trace_transaction_json(tx, NoopJsTracer::default().into()).await.unwrap();
        assert_eq!(res, serde_json::Value::Object(Default::default()));
    }

    #[tokio::test]
    #[ignore]
    async fn can_trace_default_template() {
        let tx = TX_1.parse().unwrap();
        let url = parse_env_url("RETH_RPC_TEST_NODE_URL").unwrap();
        let client = HttpClientBuilder::default().build(url).unwrap();
        let res = client
            .debug_trace_transaction_json(tx, JsTracerBuilder::default().into())
            .await
            .unwrap();
        assert_eq!(res, serde_json::Value::Object(Default::default()));
    }

    #[tokio::test]
    #[ignore]
    async fn can_debug_trace_block_transactions() {
        let block = 11_117_104u64;
        let url = parse_env_url("RETH_RPC_TEST_NODE_URL").unwrap();
        let client = HttpClientBuilder::default().build(url).unwrap();

        let opts = GethDebugTracingOptions::default()
            .with_call_config(CallConfig::default().only_top_call());

        let mut stream = client.debug_trace_transactions_in_block(block, opts).await.unwrap();
        while let Some(res) = stream.next().await {
            if let Err((err, tx)) = res {
                println!("failed to trace {tx:?}  {err}");
            }
        }
    }
}