alloy_provider/ext/
debug.rs

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
//! This module extends the Ethereum JSON-RPC provider with the Debug namespace's RPC methods.
use crate::Provider;
use alloy_network::Network;
use alloy_primitives::{hex, Bytes, TxHash, B256};
use alloy_rpc_types_eth::{
    Block, BlockId, BlockNumberOrTag, Bundle, StateContext, TransactionRequest,
};
use alloy_rpc_types_trace::geth::{
    BlockTraceResult, GethDebugTracingCallOptions, GethDebugTracingOptions, GethTrace, TraceResult,
};
use alloy_transport::{Transport, TransportResult};

/// Debug namespace rpc interface that gives access to several non-standard RPC methods.
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
pub trait DebugApi<N, T>: Send + Sync {
    /// Returns an RLP-encoded header.
    async fn debug_get_raw_header(&self, block: BlockId) -> TransportResult<Bytes>;

    /// Retrieves and returns the RLP encoded block by number, hash or tag.
    async fn debug_get_raw_block(&self, block: BlockId) -> TransportResult<Bytes>;

    /// Returns an EIP-2718 binary-encoded transaction.
    async fn debug_get_raw_transaction(&self, hash: TxHash) -> TransportResult<Bytes>;

    /// Returns an array of EIP-2718 binary-encoded receipts.
    async fn debug_get_raw_receipts(&self, block: BlockId) -> TransportResult<Vec<Bytes>>;

    /// Returns an array of recent bad blocks that the client has seen on the network.
    async fn debug_get_bad_blocks(&self) -> TransportResult<Vec<Block>>;

    /// Returns the structured logs created during the execution of EVM between two blocks
    /// (excluding start) as a JSON object.
    async fn debug_trace_chain(
        &self,
        start_exclusive: BlockNumberOrTag,
        end_inclusive: BlockNumberOrTag,
    ) -> TransportResult<Vec<BlockTraceResult>>;

    /// The debug_traceBlock method will return a full stack trace of all invoked opcodes of all
    /// transaction that were included in this block.
    ///
    /// This expects an RLP-encoded block.
    ///
    /// # Note
    ///
    /// The parent of this block must be present, or it will fail.
    async fn debug_trace_block(
        &self,
        rlp_block: &[u8],
        trace_options: GethDebugTracingOptions,
    ) -> TransportResult<Vec<TraceResult>>;

    /// Reruns the transaction specified by the hash and returns the trace.
    ///
    /// It will replay any prior transactions to achieve the same state the transaction was executed
    /// in.
    ///
    /// [GethDebugTracingOptions] can be used to specify the trace options.
    ///
    /// # Note
    ///
    /// Not all nodes support this call.
    async fn debug_trace_transaction(
        &self,
        hash: TxHash,
        trace_options: GethDebugTracingOptions,
    ) -> TransportResult<GethTrace>;

    /// Return a full stack trace of all invoked opcodes of all transaction that were included in
    /// this block.
    ///
    /// The parent of the block must be present or it will fail.
    ///
    /// [GethDebugTracingOptions] can be used to specify the trace options.
    ///
    /// # Note
    ///
    /// Not all nodes support this call.
    async fn debug_trace_block_by_hash(
        &self,
        block: B256,
        trace_options: GethDebugTracingOptions,
    ) -> TransportResult<Vec<TraceResult>>;

    /// Same as `debug_trace_block_by_hash` but block is specified by number.
    ///
    /// [GethDebugTracingOptions] can be used to specify the trace options.
    ///
    /// # Note
    ///
    /// Not all nodes support this call.
    async fn debug_trace_block_by_number(
        &self,
        block: BlockNumberOrTag,
        trace_options: GethDebugTracingOptions,
    ) -> TransportResult<Vec<TraceResult>>;

    /// Executes the given transaction without publishing it like `eth_call` and returns the trace
    /// of the execution.
    ///
    /// The transaction will be executed in the context of the given block number or tag.
    /// The state its run on is the state of the previous block.
    ///
    /// [GethDebugTracingOptions] can be used to specify the trace options.
    ///
    /// # Note
    ///
    ///
    /// Not all nodes support this call.
    async fn debug_trace_call(
        &self,
        tx: TransactionRequest,
        block: BlockId,
        trace_options: GethDebugTracingCallOptions,
    ) -> TransportResult<GethTrace>;

    /// Same as `debug_trace_call` but it used to run and trace multiple transactions at once.
    ///
    /// [GethDebugTracingOptions] can be used to specify the trace options.
    ///
    /// # Note
    ///
    /// Not all nodes support this call.
    async fn debug_trace_call_many(
        &self,
        bundles: Vec<Bundle>,
        state_context: StateContext,
        trace_options: GethDebugTracingCallOptions,
    ) -> TransportResult<Vec<GethTrace>>;
}

#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
impl<N, T, P> DebugApi<N, T> for P
where
    N: Network,
    T: Transport + Clone,
    P: Provider<T, N>,
{
    async fn debug_get_raw_header(&self, block: BlockId) -> TransportResult<Bytes> {
        self.client().request("debug_getRawHeader", (block,)).await
    }

    async fn debug_get_raw_block(&self, block: BlockId) -> TransportResult<Bytes> {
        self.client().request("debug_getRawBlock", (block,)).await
    }

    async fn debug_get_raw_transaction(&self, hash: TxHash) -> TransportResult<Bytes> {
        self.client().request("debug_getRawTransaction", (hash,)).await
    }

    async fn debug_get_raw_receipts(&self, block: BlockId) -> TransportResult<Vec<Bytes>> {
        self.client().request("debug_getRawReceipts", (block,)).await
    }

    async fn debug_get_bad_blocks(&self) -> TransportResult<Vec<Block>> {
        self.client().request_noparams("debug_getBadBlocks").await
    }

    async fn debug_trace_chain(
        &self,
        start_exclusive: BlockNumberOrTag,
        end_inclusive: BlockNumberOrTag,
    ) -> TransportResult<Vec<BlockTraceResult>> {
        self.client().request("debug_traceChain", (start_exclusive, end_inclusive)).await
    }

    async fn debug_trace_block(
        &self,
        rlp_block: &[u8],
        trace_options: GethDebugTracingOptions,
    ) -> TransportResult<Vec<TraceResult>> {
        let rlp_block = hex::encode_prefixed(rlp_block);
        self.client().request("debug_traceBlock", (rlp_block, trace_options)).await
    }

    async fn debug_trace_transaction(
        &self,
        hash: TxHash,
        trace_options: GethDebugTracingOptions,
    ) -> TransportResult<GethTrace> {
        self.client().request("debug_traceTransaction", (hash, trace_options)).await
    }

    async fn debug_trace_block_by_hash(
        &self,
        block: B256,
        trace_options: GethDebugTracingOptions,
    ) -> TransportResult<Vec<TraceResult>> {
        self.client().request("debug_traceBlockByHash", (block, trace_options)).await
    }

    async fn debug_trace_block_by_number(
        &self,
        block: BlockNumberOrTag,
        trace_options: GethDebugTracingOptions,
    ) -> TransportResult<Vec<TraceResult>> {
        self.client().request("debug_traceBlockByNumber", (block, trace_options)).await
    }

    async fn debug_trace_call(
        &self,
        tx: TransactionRequest,
        block: BlockId,
        trace_options: GethDebugTracingCallOptions,
    ) -> TransportResult<GethTrace> {
        self.client().request("debug_traceCall", (tx, block, trace_options)).await
    }

    async fn debug_trace_call_many(
        &self,
        bundles: Vec<Bundle>,
        state_context: StateContext,
        trace_options: GethDebugTracingCallOptions,
    ) -> TransportResult<Vec<GethTrace>> {
        self.client().request("debug_traceCallMany", (bundles, state_context, trace_options)).await
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{ext::test::async_ci_only, ProviderBuilder, WalletProvider};
    use alloy_network::TransactionBuilder;
    use alloy_node_bindings::{utils::run_with_tempdir, Geth, Reth};
    use alloy_primitives::{address, U256};

    #[tokio::test]
    async fn test_debug_trace_transaction() {
        async_ci_only(|| async move {
            let provider = ProviderBuilder::new().with_recommended_fillers().on_anvil_with_wallet();
            let from = provider.default_signer_address();

            let gas_price = provider.get_gas_price().await.unwrap();
            let tx = TransactionRequest::default()
                .from(from)
                .to(address!("deadbeef00000000deadbeef00000000deadbeef"))
                .value(U256::from(100))
                .max_fee_per_gas(gas_price + 1)
                .max_priority_fee_per_gas(gas_price + 1);
            let pending = provider.send_transaction(tx).await.unwrap();
            let receipt = pending.get_receipt().await.unwrap();

            let hash = receipt.transaction_hash;
            let trace_options = GethDebugTracingOptions::default();

            let trace = provider.debug_trace_transaction(hash, trace_options).await.unwrap();

            if let GethTrace::Default(trace) = trace {
                assert_eq!(trace.gas, 21000)
            }
        })
        .await;
    }

    #[tokio::test]
    async fn test_debug_trace_call() {
        async_ci_only(|| async move {
            let provider = ProviderBuilder::new().on_anvil_with_wallet();
            let from = provider.default_signer_address();
            let gas_price = provider.get_gas_price().await.unwrap();
            let tx = TransactionRequest::default()
                .from(from)
                .with_input("0xdeadbeef")
                .max_fee_per_gas(gas_price + 1)
                .max_priority_fee_per_gas(gas_price + 1);

            let trace = provider
                .debug_trace_call(
                    tx,
                    BlockNumberOrTag::Latest.into(),
                    GethDebugTracingCallOptions::default(),
                )
                .await
                .unwrap();

            if let GethTrace::Default(trace) = trace {
                assert!(!trace.struct_logs.is_empty());
            }
        })
        .await;
    }

    #[tokio::test]
    async fn call_debug_get_raw_header() {
        async_ci_only(|| async move {
            run_with_tempdir("geth-test-", |temp_dir| async move {
                let geth = Geth::new().disable_discovery().data_dir(temp_dir).spawn();
                let provider = ProviderBuilder::new().on_http(geth.endpoint_url());

                let rlp_header = provider
                    .debug_get_raw_header(BlockId::Number(BlockNumberOrTag::Latest))
                    .await
                    .expect("debug_getRawHeader call should succeed");

                assert!(!rlp_header.is_empty());
            })
            .await;
        })
        .await;
    }

    #[tokio::test]
    async fn call_debug_get_raw_block() {
        async_ci_only(|| async move {
            run_with_tempdir("geth-test-", |temp_dir| async move {
                let geth = Geth::new().disable_discovery().data_dir(temp_dir).spawn();
                let provider = ProviderBuilder::new().on_http(geth.endpoint_url());

                let rlp_block = provider
                    .debug_get_raw_block(BlockId::Number(BlockNumberOrTag::Latest))
                    .await
                    .expect("debug_getRawBlock call should succeed");

                assert!(!rlp_block.is_empty());
            })
            .await;
        })
        .await;
    }

    #[tokio::test]
    async fn call_debug_get_raw_receipts() {
        async_ci_only(|| async move {
            run_with_tempdir("geth-test-", |temp_dir| async move {
                let geth = Geth::new().disable_discovery().data_dir(temp_dir).spawn();
                let provider = ProviderBuilder::new().on_http(geth.endpoint_url());

                let result = provider
                    .debug_get_raw_receipts(BlockId::Number(BlockNumberOrTag::Latest))
                    .await;
                assert!(result.is_ok());
            })
            .await;
        })
        .await;
    }

    #[tokio::test]
    async fn call_debug_get_bad_blocks() {
        async_ci_only(|| async move {
            run_with_tempdir("geth-test-", |temp_dir| async move {
                let geth = Geth::new().disable_discovery().data_dir(temp_dir).spawn();
                let provider = ProviderBuilder::new().on_http(geth.endpoint_url());

                let result = provider.debug_get_bad_blocks().await;
                assert!(result.is_ok());
            })
            .await;
        })
        .await;
    }

    #[tokio::test]
    #[cfg(not(windows))]
    async fn debug_trace_call_many() {
        async_ci_only(|| async move {
            run_with_tempdir("reth-test-", |temp_dir| async move {
                let reth = Reth::new().dev().disable_discovery().data_dir(temp_dir).spawn();
                let provider =
                    ProviderBuilder::new().with_recommended_fillers().on_http(reth.endpoint_url());

                let tx1 = TransactionRequest::default()
                    .with_from(address!("0000000000000000000000000000000000000123"))
                    .with_to(address!("0000000000000000000000000000000000000456"));

                let tx2 = TransactionRequest::default()
                    .with_from(address!("0000000000000000000000000000000000000456"))
                    .with_to(address!("0000000000000000000000000000000000000789"));

                let bundles = vec![Bundle { transactions: vec![tx1, tx2], block_override: None }];
                let state_context = StateContext::default();
                let trace_options = GethDebugTracingCallOptions::default();
                let result =
                    provider.debug_trace_call_many(bundles, state_context, trace_options).await;
                assert!(result.is_ok());

                let traces = result.unwrap();
                assert_eq!(
                    serde_json::to_string_pretty(&traces).unwrap().trim(),
                    r#"
[
  [
    {
      "failed": false,
      "gas": 21000,
      "returnValue": "",
      "structLogs": []
    },
    {
      "failed": false,
      "gas": 21000,
      "returnValue": "",
      "structLogs": []
    }
  ]
]
"#
                    .trim(),
                );
            })
            .await;
        })
        .await;
    }
}