alloy_provider/ext/
trace.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
//! This module extends the Ethereum JSON-RPC provider with the Trace namespace's RPC methods.
use crate::{Provider, RpcWithBlock};
use alloy_eips::BlockId;
use alloy_network::Network;
use alloy_primitives::TxHash;
use alloy_rpc_types_eth::Index;
use alloy_rpc_types_trace::{
    filter::TraceFilter,
    parity::{LocalizedTransactionTrace, TraceResults, TraceResultsWithTransactionHash, TraceType},
};
use alloy_transport::{Transport, TransportResult};

/// List of trace calls for use with [`TraceApi::trace_call_many`]
pub type TraceCallList<'a, N> = &'a [(<N as Network>::TransactionRequest, &'a [TraceType])];

/// Trace 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 TraceApi<N, T>: Send + Sync
where
    N: Network,
    T: Transport + Clone,
{
    /// Executes the given transaction and returns a number of possible traces.
    ///
    /// # Note
    ///
    /// Not all nodes support this call.
    fn trace_call<'a, 'b>(
        &self,
        request: &'a N::TransactionRequest,
        trace_type: &'b [TraceType],
    ) -> RpcWithBlock<T, (&'a N::TransactionRequest, &'b [TraceType]), TraceResults>;

    /// Traces multiple transactions on top of the same block, i.e. transaction `n` will be executed
    /// on top of the given block with all `n - 1` transaction applied first.
    ///
    /// Allows tracing dependent transactions.
    ///
    /// # Note
    ///
    /// Not all nodes support this call.
    fn trace_call_many<'a>(
        &self,
        request: TraceCallList<'a, N>,
    ) -> RpcWithBlock<T, (TraceCallList<'a, N>,), Vec<TraceResults>>;

    /// Parity trace transaction.
    async fn trace_transaction(
        &self,
        hash: TxHash,
    ) -> TransportResult<Vec<LocalizedTransactionTrace>>;

    /// Traces of the transaction on the given positions
    ///
    /// # Note
    ///
    /// This function accepts single index and build list with it under the hood because
    /// trace_get method accepts list of indices but limits this list to len == 1.
    async fn trace_get(
        &self,
        hash: TxHash,
        index: usize,
    ) -> TransportResult<LocalizedTransactionTrace>;

    /// Trace the given raw transaction.
    async fn trace_raw_transaction(
        &self,
        data: &[u8],
        trace_type: &[TraceType],
    ) -> TransportResult<TraceResults>;

    /// Traces matching given filter.
    async fn trace_filter(
        &self,
        tracer: &TraceFilter,
    ) -> TransportResult<Vec<LocalizedTransactionTrace>>;

    /// Trace all transactions in the given block.
    ///
    /// # Note
    ///
    /// Not all nodes support this call.
    async fn trace_block(&self, block: BlockId) -> TransportResult<Vec<LocalizedTransactionTrace>>;

    /// Replays a transaction.
    async fn trace_replay_transaction(
        &self,
        hash: TxHash,
        trace_types: &[TraceType],
    ) -> TransportResult<TraceResults>;

    /// Replays all transactions in the given block.
    async fn trace_replay_block_transactions(
        &self,
        block: BlockId,
        trace_types: &[TraceType],
    ) -> TransportResult<Vec<TraceResultsWithTransactionHash>>;
}

#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
impl<N, T, P> TraceApi<N, T> for P
where
    N: Network,
    T: Transport + Clone,
    P: Provider<T, N>,
{
    fn trace_call<'a, 'b>(
        &self,
        request: &'a <N as Network>::TransactionRequest,
        trace_types: &'b [TraceType],
    ) -> RpcWithBlock<T, (&'a <N as Network>::TransactionRequest, &'b [TraceType]), TraceResults>
    {
        self.client().request("trace_call", (request, trace_types)).into()
    }

    fn trace_call_many<'a>(
        &self,
        request: TraceCallList<'a, N>,
    ) -> RpcWithBlock<T, (TraceCallList<'a, N>,), Vec<TraceResults>> {
        self.client().request("trace_callMany", (request,)).into()
    }

    async fn trace_transaction(
        &self,
        hash: TxHash,
    ) -> TransportResult<Vec<LocalizedTransactionTrace>> {
        self.client().request("trace_transaction", (hash,)).await
    }

    async fn trace_get(
        &self,
        hash: TxHash,
        index: usize,
    ) -> TransportResult<LocalizedTransactionTrace> {
        // We are using `[index]` because API accepts a list, but only supports a single index
        self.client().request("trace_get", (hash, (Index::from(index),))).await
    }

    async fn trace_raw_transaction(
        &self,
        data: &[u8],
        trace_types: &[TraceType],
    ) -> TransportResult<TraceResults> {
        self.client().request("trace_rawTransaction", (data, trace_types)).await
    }

    async fn trace_filter(
        &self,
        tracer: &TraceFilter,
    ) -> TransportResult<Vec<LocalizedTransactionTrace>> {
        self.client().request("trace_filter", (tracer,)).await
    }

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

    async fn trace_replay_transaction(
        &self,
        hash: TxHash,
        trace_types: &[TraceType],
    ) -> TransportResult<TraceResults> {
        self.client().request("trace_replayTransaction", (hash, trace_types)).await
    }

    async fn trace_replay_block_transactions(
        &self,
        block: BlockId,
        trace_types: &[TraceType],
    ) -> TransportResult<Vec<TraceResultsWithTransactionHash>> {
        self.client().request("trace_replayBlockTransactions", (block, trace_types)).await
    }
}

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

    #[tokio::test]
    async fn trace_block() {
        let provider = ProviderBuilder::new().on_anvil();
        let traces = provider.trace_block(BlockId::Number(BlockNumberOrTag::Latest)).await.unwrap();
        assert_eq!(traces.len(), 0);
    }

    #[tokio::test]
    #[cfg(not(windows))]
    async fn trace_call() {
        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().on_http(reth.endpoint_url());

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

                let result = provider.trace_call(&tx, &[TraceType::Trace]).await;
                assert!(result.is_ok());

                let traces = result.unwrap();
                assert_eq!(
                    serde_json::to_string_pretty(&traces).unwrap().trim(),
                    r#"
{
  "output": "0x",
  "stateDiff": null,
  "trace": [
    {
      "type": "call",
      "action": {
        "from": "0x0000000000000000000000000000000000000123",
        "callType": "call",
        "gas": "0x2fa9e78",
        "input": "0x",
        "to": "0x0000000000000000000000000000000000000456",
        "value": "0x0"
      },
      "result": {
        "gasUsed": "0x0",
        "output": "0x"
      },
      "subtraces": 0,
      "traceAddress": []
    }
  ],
  "vmTrace": null
}
"#
                    .trim(),
                );
            })
            .await;
        })
        .await;
    }

    #[tokio::test]
    #[cfg(not(windows))]
    async fn 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().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 result = provider
                    .trace_call_many(&[(tx1, &[TraceType::Trace]), (tx2, &[TraceType::Trace])])
                    .await;
                assert!(result.is_ok());

                let traces = result.unwrap();
                assert_eq!(
                    serde_json::to_string_pretty(&traces).unwrap().trim(),
                    r#"
[
  {
    "output": "0x",
    "stateDiff": null,
    "trace": [
      {
        "type": "call",
        "action": {
          "from": "0x0000000000000000000000000000000000000123",
          "callType": "call",
          "gas": "0x2fa9e78",
          "input": "0x",
          "to": "0x0000000000000000000000000000000000000456",
          "value": "0x0"
        },
        "result": {
          "gasUsed": "0x0",
          "output": "0x"
        },
        "subtraces": 0,
        "traceAddress": []
      }
    ],
    "vmTrace": null
  },
  {
    "output": "0x",
    "stateDiff": null,
    "trace": [
      {
        "type": "call",
        "action": {
          "from": "0x0000000000000000000000000000000000000456",
          "callType": "call",
          "gas": "0x2fa9e78",
          "input": "0x",
          "to": "0x0000000000000000000000000000000000000789",
          "value": "0x0"
        },
        "result": {
          "gasUsed": "0x0",
          "output": "0x"
        },
        "subtraces": 0,
        "traceAddress": []
      }
    ],
    "vmTrace": null
  }
]
"#
                    .trim()
                );
            })
            .await;
        })
        .await;
    }
}