reth_rpc_api_testing_util/
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
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
//! Helpers for testing trace calls.

use alloy_eips::BlockId;
use alloy_primitives::{map::HashSet, Bytes, TxHash, B256};
use alloy_rpc_types_eth::{transaction::TransactionRequest, Index};
use alloy_rpc_types_trace::{
    filter::TraceFilter,
    opcode::BlockOpcodeGas,
    parity::{LocalizedTransactionTrace, TraceResults, TraceType},
    tracerequest::TraceCallRequest,
};
use futures::{Stream, StreamExt};
use jsonrpsee::core::client::Error as RpcError;
use reth_rpc_api::clients::TraceApiClient;
use std::{
    pin::Pin,
    task::{Context, Poll},
};

/// A type alias that represents the result of a raw transaction trace stream.
type RawTransactionTraceResult<'a> =
    Pin<Box<dyn Stream<Item = Result<(TraceResults, Bytes), (RpcError, Bytes)>> + 'a>>;

/// A result type for the `trace_block` method that also captures the requested block.
pub type TraceBlockResult = Result<(Vec<LocalizedTransactionTrace>, BlockId), (RpcError, BlockId)>;

/// A result type for the `trace_blockOpcodeGas` method that also captures the requested block.
pub type TraceBlockOpCodeGasResult = Result<(BlockOpcodeGas, BlockId), (RpcError, BlockId)>;

/// Type alias representing the result of replaying a transaction.
pub type ReplayTransactionResult = Result<(TraceResults, TxHash), (RpcError, TxHash)>;

/// A type representing the result of calling `trace_call_many` method.
pub type CallManyTraceResult = Result<
    (Vec<TraceResults>, Vec<(TransactionRequest, HashSet<TraceType>)>),
    (RpcError, Vec<(TransactionRequest, HashSet<TraceType>)>),
>;

/// Result type for the `trace_get` method that also captures the requested transaction hash and
/// index.
pub type TraceGetResult =
    Result<(Option<LocalizedTransactionTrace>, B256, Vec<Index>), (RpcError, B256, Vec<Index>)>;

/// Represents a result type for the `trace_filter` stream extension.
pub type TraceFilterResult =
    Result<(Vec<LocalizedTransactionTrace>, TraceFilter), (RpcError, TraceFilter)>;

/// Represents the result of a single trace call.
pub type TraceCallResult = Result<TraceResults, (RpcError, TraceCallRequest)>;

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

    /// Returns a new stream that yields the traces for the given blocks.
    ///
    /// See also [`StreamExt::buffered`].
    fn trace_block_buffered<I, B>(&self, params: I, n: usize) -> TraceBlockStream<'_>
    where
        I: IntoIterator<Item = B>,
        B: Into<BlockId>;

    /// Returns a new stream that yields the traces for the given blocks.
    ///
    /// See also [`StreamExt::buffer_unordered`].
    fn trace_block_buffered_unordered<I, B>(&self, params: I, n: usize) -> TraceBlockStream<'_>
    where
        I: IntoIterator<Item = B>,
        B: Into<BlockId>;

    /// Returns a new stream that yields the traces the opcodes for the given blocks.
    ///
    /// See also [`StreamExt::buffered`].
    fn trace_block_opcode_gas_unordered<I, B>(
        &self,
        params: I,
        n: usize,
    ) -> TraceBlockOpcodeGasStream<'_>
    where
        I: IntoIterator<Item = B>,
        B: Into<BlockId>;

    /// Returns a new stream that replays the transactions for the given transaction hashes.
    ///
    /// This returns all results in order.
    fn replay_transactions<I>(
        &self,
        tx_hashes: I,
        trace_types: HashSet<TraceType>,
    ) -> ReplayTransactionStream<'_>
    where
        I: IntoIterator<Item = TxHash>;

    /// Returns a new stream that traces the provided raw transaction data.
    fn trace_raw_transaction_stream(
        &self,
        data: Bytes,
        trace_types: HashSet<TraceType>,
        block_id: Option<BlockId>,
    ) -> RawTransactionTraceStream<'_>;

    /// Creates a stream of results for multiple dependent transaction calls on top of the same
    /// block.
    fn trace_call_many_stream<I>(
        &self,
        calls: I,
        block_id: Option<BlockId>,
    ) -> CallManyTraceStream<'_>
    where
        I: IntoIterator<Item = (TransactionRequest, HashSet<TraceType>)>;

    /// Returns a new stream that yields the traces for the given transaction hash and indices.
    fn trace_get_stream<I>(&self, hash: B256, indices: I) -> TraceGetStream<'_>
    where
        I: IntoIterator<Item = Index>;

    /// Returns a new stream that yields traces for given filters.
    fn trace_filter_stream<I>(&self, filters: I) -> TraceFilterStream<'_>
    where
        I: IntoIterator<Item = TraceFilter>;

    /// Returns a new stream that yields the trace results for the given call requests.
    fn trace_call_stream(&self, request: TraceCallRequest) -> TraceCallStream<'_>;
}
/// `TraceCallStream` provides an asynchronous stream of tracing results.
#[must_use = "streams do nothing unless polled"]
pub struct TraceCallStream<'a> {
    stream: Pin<Box<dyn Stream<Item = TraceCallResult> + 'a>>,
}

impl Stream for TraceCallStream<'_> {
    type Item = TraceCallResult;

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

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

/// Represents a stream that asynchronously yields the results of the `trace_filter` method.
#[must_use = "streams do nothing unless polled"]
pub struct TraceFilterStream<'a> {
    stream: Pin<Box<dyn Stream<Item = TraceFilterResult> + 'a>>,
}

impl Stream for TraceFilterStream<'_> {
    type Item = TraceFilterResult;

    /// Attempts to pull out the next value of the stream.
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.stream.as_mut().poll_next(cx)
    }
}

impl std::fmt::Debug for TraceFilterStream<'_> {
    /// Provides a debug representation of the `TraceFilterStream`.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TraceFilterStream").finish_non_exhaustive()
    }
}

/// A stream that asynchronously yields the results of the `trace_get` method for a given
/// transaction hash and a series of indices.
#[must_use = "streams do nothing unless polled"]
pub struct TraceGetStream<'a> {
    stream: Pin<Box<dyn Stream<Item = TraceGetResult> + 'a>>,
}

impl Stream for TraceGetStream<'_> {
    type Item = TraceGetResult;

    /// Attempts to pull out the next item of the stream
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.stream.as_mut().poll_next(cx)
    }
}

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

/// A stream that provides asynchronous iteration over results from the `trace_call_many` function.
///
/// The stream yields items of type `CallManyTraceResult`.
#[must_use = "streams do nothing unless polled"]
pub struct CallManyTraceStream<'a> {
    stream: Pin<Box<dyn Stream<Item = CallManyTraceResult> + 'a>>,
}

impl Stream for CallManyTraceStream<'_> {
    type Item = CallManyTraceResult;

    /// Polls for the next item from the stream.
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.stream.as_mut().poll_next(cx)
    }
}

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

/// A stream that traces the provided raw transaction data.
#[must_use = "streams do nothing unless polled"]
pub struct RawTransactionTraceStream<'a> {
    stream: RawTransactionTraceResult<'a>,
}

impl Stream for RawTransactionTraceStream<'_> {
    type Item = Result<(TraceResults, Bytes), (RpcError, Bytes)>;

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

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

/// A stream that replays the transactions for the requested hashes.
#[must_use = "streams do nothing unless polled"]
pub struct ReplayTransactionStream<'a> {
    stream: Pin<Box<dyn Stream<Item = ReplayTransactionResult> + 'a>>,
}

impl Stream for ReplayTransactionStream<'_> {
    type Item = ReplayTransactionResult;

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

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

impl<T: TraceApiClient + Sync> TraceApiExt for T {
    type Provider = T;

    fn trace_block_buffered<I, B>(&self, params: I, n: usize) -> TraceBlockStream<'_>
    where
        I: IntoIterator<Item = B>,
        B: Into<BlockId>,
    {
        let blocks = params.into_iter().map(|b| b.into()).collect::<Vec<_>>();
        let stream = futures::stream::iter(blocks.into_iter().map(move |block| async move {
            match self.trace_block(block).await {
                Ok(result) => Ok((result.unwrap_or_default(), block)),
                Err(err) => Err((err, block)),
            }
        }))
        .buffered(n);
        TraceBlockStream { stream: Box::pin(stream) }
    }

    fn trace_block_buffered_unordered<I, B>(&self, params: I, n: usize) -> TraceBlockStream<'_>
    where
        I: IntoIterator<Item = B>,
        B: Into<BlockId>,
    {
        let blocks = params.into_iter().map(|b| b.into()).collect::<Vec<_>>();
        let stream = futures::stream::iter(blocks.into_iter().map(move |block| async move {
            match self.trace_block(block).await {
                Ok(result) => Ok((result.unwrap_or_default(), block)),
                Err(err) => Err((err, block)),
            }
        }))
        .buffer_unordered(n);
        TraceBlockStream { stream: Box::pin(stream) }
    }

    fn trace_block_opcode_gas_unordered<I, B>(
        &self,
        params: I,
        n: usize,
    ) -> TraceBlockOpcodeGasStream<'_>
    where
        I: IntoIterator<Item = B>,
        B: Into<BlockId>,
    {
        let blocks = params.into_iter().map(|b| b.into()).collect::<Vec<_>>();
        let stream = futures::stream::iter(blocks.into_iter().map(move |block| async move {
            match self.trace_block_opcode_gas(block).await {
                Ok(result) => Ok((result.unwrap(), block)),
                Err(err) => Err((err, block)),
            }
        }))
        .buffered(n);
        TraceBlockOpcodeGasStream { stream: Box::pin(stream) }
    }

    fn replay_transactions<I>(
        &self,
        tx_hashes: I,
        trace_types: HashSet<TraceType>,
    ) -> ReplayTransactionStream<'_>
    where
        I: IntoIterator<Item = TxHash>,
    {
        let hashes = tx_hashes.into_iter().collect::<Vec<_>>();
        let stream = futures::stream::iter(hashes.into_iter().map(move |hash| {
            let trace_types_clone = trace_types.clone(); // Clone outside of the async block
            async move {
                match self.replay_transaction(hash, trace_types_clone).await {
                    Ok(result) => Ok((result, hash)),
                    Err(err) => Err((err, hash)),
                }
            }
        }))
        .buffered(10);
        ReplayTransactionStream { stream: Box::pin(stream) }
    }

    fn trace_raw_transaction_stream(
        &self,
        data: Bytes,
        trace_types: HashSet<TraceType>,
        block_id: Option<BlockId>,
    ) -> RawTransactionTraceStream<'_> {
        let stream = futures::stream::once(async move {
            match self.trace_raw_transaction(data.clone(), trace_types, block_id).await {
                Ok(result) => Ok((result, data)),
                Err(err) => Err((err, data)),
            }
        });
        RawTransactionTraceStream { stream: Box::pin(stream) }
    }

    fn trace_call_many_stream<I>(
        &self,
        calls: I,
        block_id: Option<BlockId>,
    ) -> CallManyTraceStream<'_>
    where
        I: IntoIterator<Item = (TransactionRequest, HashSet<TraceType>)>,
    {
        let call_set = calls.into_iter().collect::<Vec<_>>();
        let stream = futures::stream::once(async move {
            match self.trace_call_many(call_set.clone(), block_id).await {
                Ok(results) => Ok((results, call_set)),
                Err(err) => Err((err, call_set)),
            }
        });
        CallManyTraceStream { stream: Box::pin(stream) }
    }

    fn trace_get_stream<I>(&self, hash: B256, indices: I) -> TraceGetStream<'_>
    where
        I: IntoIterator<Item = Index>,
    {
        let index_list = indices.into_iter().collect::<Vec<_>>();
        let stream = futures::stream::iter(index_list.into_iter().map(move |index| async move {
            match self.trace_get(hash, vec![index]).await {
                Ok(result) => Ok((result, hash, vec![index])),
                Err(err) => Err((err, hash, vec![index])),
            }
        }))
        .buffered(10);
        TraceGetStream { stream: Box::pin(stream) }
    }

    fn trace_filter_stream<I>(&self, filters: I) -> TraceFilterStream<'_>
    where
        I: IntoIterator<Item = TraceFilter>,
    {
        let filter_list = filters.into_iter().collect::<Vec<_>>();
        let stream = futures::stream::iter(filter_list.into_iter().map(move |filter| async move {
            match self.trace_filter(filter.clone()).await {
                Ok(result) => Ok((result, filter)),
                Err(err) => Err((err, filter)),
            }
        }))
        .buffered(10);
        TraceFilterStream { stream: Box::pin(stream) }
    }

    fn trace_call_stream(&self, request: TraceCallRequest) -> TraceCallStream<'_> {
        let stream = futures::stream::once(async move {
            match self
                .trace_call(
                    request.call.clone(),
                    request.trace_types.clone(),
                    request.block_id,
                    request.state_overrides.clone(),
                    request.block_overrides.clone(),
                )
                .await
            {
                Ok(result) => Ok(result),
                Err(err) => Err((err, request)),
            }
        });
        TraceCallStream { stream: Box::pin(stream) }
    }
}

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

impl TraceBlockStream<'_> {
    /// 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 Stream for TraceBlockStream<'_> {
    type Item = TraceBlockResult;

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

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

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

impl TraceBlockOpcodeGasStream<'_> {
    /// 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 Stream for TraceBlockOpcodeGasStream<'_> {
    type Item = TraceBlockOpCodeGasResult;

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

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

/// A utility to compare RPC responses from two different clients.
///
/// The `RpcComparer` is designed to perform comparisons between two RPC clients.
/// It is useful in scenarios where there's a need to ensure that two different RPC clients
/// return consistent responses. This can be particularly valuable in testing environments
/// where one might want to compare a test client's responses against a production client
/// or compare two different Ethereum client implementations.
#[derive(Debug)]
pub struct RpcComparer<C1, C2>
where
    C1: TraceApiExt,
    C2: TraceApiExt,
{
    client1: C1,
    client2: C2,
}
impl<C1, C2> RpcComparer<C1, C2>
where
    C1: TraceApiExt,
    C2: TraceApiExt,
{
    /// Constructs a new `RpcComparer`.
    ///
    /// Initializes the comparer with two clients that will be used for fetching
    /// and comparison.
    ///
    /// # Arguments
    ///
    /// * `client1` - The first RPC client.
    /// * `client2` - The second RPC client.
    pub const fn new(client1: C1, client2: C2) -> Self {
        Self { client1, client2 }
    }

    /// Compares the `trace_block` responses from the two RPC clients.
    ///
    /// Fetches the `trace_block` responses for the provided block IDs from both clients
    /// and compares them. If there are inconsistencies between the two responses, this
    /// method will panic with a relevant message indicating the difference.
    pub async fn compare_trace_block_responses(&self, block_ids: Vec<BlockId>) {
        let stream1 = self.client1.trace_block_buffered(block_ids.clone(), 2);
        let stream2 = self.client2.trace_block_buffered(block_ids, 2);

        let mut zipped_streams = stream1.zip(stream2);

        while let Some((result1, result2)) = zipped_streams.next().await {
            match (result1, result2) {
                (Ok((ref traces1_data, ref block1)), Ok((ref traces2_data, ref block2))) => {
                    similar_asserts::assert_eq!(
                        traces1_data,
                        traces2_data,
                        "Mismatch in traces for block: {:?}",
                        block1
                    );
                    assert_eq!(block1, block2, "Mismatch in block ids.");
                }
                (Err((ref err1, ref block1)), Err((ref err2, ref block2))) => {
                    assert_eq!(
                        format!("{err1:?}"),
                        format!("{err2:?}"),
                        "Different errors for block: {block1:?}"
                    );
                    assert_eq!(block1, block2, "Mismatch in block ids.");
                }
                _ => panic!("One client returned Ok while the other returned Err."),
            }
        }
    }

    /// Compares the `replay_transactions` responses from the two RPC clients.
    pub async fn compare_replay_transaction_responses(
        &self,
        transaction_hashes: Vec<TxHash>,
        trace_types: HashSet<TraceType>,
    ) {
        let stream1 =
            self.client1.replay_transactions(transaction_hashes.clone(), trace_types.clone());
        let stream2 = self.client2.replay_transactions(transaction_hashes, trace_types);

        let mut zipped_streams = stream1.zip(stream2);

        while let Some((result1, result2)) = zipped_streams.next().await {
            match (result1, result2) {
                (Ok((ref trace1_data, ref tx_hash1)), Ok((ref trace2_data, ref tx_hash2))) => {
                    similar_asserts::assert_eq!(
                        trace1_data,
                        trace2_data,
                        "Mismatch in trace results for transaction: {tx_hash1:?}",
                    );
                    assert_eq!(tx_hash1, tx_hash2, "Mismatch in transaction hashes.");
                }
                (Err((ref err1, ref tx_hash1)), Err((ref err2, ref tx_hash2))) => {
                    assert_eq!(
                        format!("{err1:?}"),
                        format!("{err2:?}"),
                        "Different errors for transaction: {tx_hash1:?}",
                    );
                    assert_eq!(tx_hash1, tx_hash2, "Mismatch in transaction hashes.");
                }
                _ => panic!("One client returned Ok while the other returned Err."),
            }
        }
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use alloy_eips::BlockNumberOrTag;
    use alloy_rpc_types_trace::filter::TraceFilterMode;
    use jsonrpsee::http_client::HttpClientBuilder;

    const fn assert_is_stream<St: Stream>(_: &St) {}

    #[tokio::test]
    async fn can_create_block_stream() {
        let client = HttpClientBuilder::default().build("http://localhost:8545").unwrap();
        let block = vec![BlockId::Number(5u64.into()), BlockNumberOrTag::Latest.into()];
        let stream = client.trace_block_buffered(block, 2);
        assert_is_stream(&stream);
    }

    #[tokio::test]
    #[ignore]
    async fn can_create_replay_transaction_stream() {
        let client = HttpClientBuilder::default().build("http://localhost:8545").unwrap();

        // Assuming you have some transactions you want to test, replace with actual hashes.
        let transactions = vec![
            "0x4e08fe36db723a338e852f89f613e606b0c9a17e649b18b01251f86236a2cef3".parse().unwrap(),
            "0xea2817f1aeeb587b82f4ab87a6dbd3560fc35ed28de1be280cb40b2a24ab48bb".parse().unwrap(),
        ];

        let trace_types = HashSet::from_iter([TraceType::StateDiff, TraceType::VmTrace]);

        let mut stream = client.replay_transactions(transactions, trace_types);
        let mut successes = 0;
        let mut failures = 0;

        assert_is_stream(&stream);

        while let Some(result) = stream.next().await {
            match result {
                Ok((trace_result, tx_hash)) => {
                    println!("Success for tx_hash {tx_hash:?}: {trace_result:?}");
                    successes += 1;
                }
                Err((error, tx_hash)) => {
                    println!("Error for tx_hash {tx_hash:?}: {error:?}");
                    failures += 1;
                }
            }
        }

        println!("Total successes: {successes}");
        println!("Total failures: {failures}");
    }

    #[tokio::test]
    #[ignore]
    async fn can_create_trace_call_many_stream() {
        let client = HttpClientBuilder::default().build("http://localhost:8545").unwrap();

        let call_request_1 = TransactionRequest::default();
        let call_request_2 = TransactionRequest::default();
        let trace_types = HashSet::from_iter([TraceType::StateDiff, TraceType::VmTrace]);
        let calls = vec![(call_request_1, trace_types.clone()), (call_request_2, trace_types)];

        let mut stream = client.trace_call_many_stream(calls, None);

        assert_is_stream(&stream);

        while let Some(result) = stream.next().await {
            match result {
                Ok(trace_result) => {
                    println!("Success: {trace_result:?}");
                }
                Err(error) => {
                    println!("Error: {error:?}");
                }
            }
        }
    }
    #[tokio::test]
    #[ignore]
    async fn can_create_trace_get_stream() {
        let client = HttpClientBuilder::default().build("http://localhost:8545").unwrap();

        let tx_hash: B256 = "".parse().unwrap();

        let indices: Vec<Index> = vec![Index::from(0)];

        let mut stream = client.trace_get_stream(tx_hash, indices);

        while let Some(result) = stream.next().await {
            match result {
                Ok(trace) => {
                    println!("Received trace: {trace:?}");
                }
                Err(e) => {
                    println!("Error fetching trace: {e:?}");
                }
            }
        }
    }

    #[tokio::test]
    #[ignore]
    async fn can_create_trace_filter() {
        let client = HttpClientBuilder::default().build("http://localhost:8545").unwrap();

        let filter = TraceFilter {
            from_block: None,
            to_block: None,
            from_address: Vec::new(),
            to_address: Vec::new(),
            mode: TraceFilterMode::Union,
            after: None,
            count: None,
        };

        let filters = vec![filter];
        let mut stream = client.trace_filter_stream(filters);

        while let Some(result) = stream.next().await {
            match result {
                Ok(trace) => {
                    println!("Received trace: {trace:?}");
                }
                Err(e) => {
                    println!("Error fetching trace: {e:?}");
                }
            }
        }
    }

    #[tokio::test]
    #[ignore]
    async fn can_create_trace_call_stream() {
        let client = HttpClientBuilder::default().build("http://localhost:8545").unwrap();

        let trace_call_request = TraceCallRequest::default();

        let mut stream = client.trace_call_stream(trace_call_request);
        let mut successes = 0;
        let mut failures = 0;

        assert_is_stream(&stream);

        while let Some(result) = stream.next().await {
            match result {
                Ok(trace_result) => {
                    println!("Success: {trace_result:?}");
                    successes += 1;
                }
                Err((error, request)) => {
                    println!("Error for request {request:?}: {error:?}");
                    failures += 1;
                }
            }
        }

        println!("Total successes: {successes}");
        println!("Total failures: {failures}");
    }

    #[tokio::test]
    #[ignore]
    async fn block_opcode_gas_stream() {
        let client = HttpClientBuilder::default().build("http://localhost:8545").unwrap();
        let block = vec![BlockNumberOrTag::Latest];
        let mut stream = client.trace_block_opcode_gas_unordered(block, 2);
        assert_is_stream(&stream);
        let _opcodes = stream.next().await.unwrap();
    }
}