alloy-provider 2.1.0

Interface with an Ethereum blockchain
Documentation
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
use super::WatchCanonicalBlocksFrom;
use alloy_eips::BlockNumberOrTag;
use alloy_json_rpc::{RpcError, RpcRecv};
use alloy_network::{BlockResponse, Network};
use alloy_network_primitives::{BlockTransactionsKind, HeaderResponse};
use alloy_primitives::U64;
use alloy_rpc_client::{RpcCall, RpcClientInner, WeakClient};
use alloy_transport::{TransportError, TransportResult};
use futures::{ready, Stream};
use pin_project::pin_project;
use std::{
    future::Future,
    marker::PhantomData,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
    time::Duration,
};

#[cfg(all(target_family = "wasm", target_os = "unknown"))]
use wasmtimer::{
    std::Instant,
    tokio::{interval_at, Interval},
};

#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
use tokio::time::{interval_at, Instant, Interval};

pub(super) const DEFAULT_POLL_INTERVAL: Duration = Duration::from_secs(1);

#[derive(Debug)]
pub(super) struct PollIntervalDelay {
    timer: Option<Interval>,
}

impl PollIntervalDelay {
    pub(super) fn new(poll_interval: Duration) -> Self {
        if poll_interval.is_zero() {
            return Self { timer: None };
        }
        Self { timer: Some(interval_at(Instant::now() + poll_interval, poll_interval)) }
    }

    pub(super) fn poll(&mut self, cx: &mut Context<'_>) -> Poll<()> {
        if let Some(timer) = &mut self.timer {
            ready!(timer.poll_tick(cx));
        }
        Poll::Ready(())
    }
}

/// Future that fetches one block by number.
///
/// This is the item yielded by [`WatchBlocksFromStream`], and is also reused by
/// [`WatchLogsFrom`](super::WatchLogsFrom) to fetch the block paired with a log batch. The future
/// requests `eth_getBlockByNumber` with either transaction hashes or full transaction bodies,
/// depending on [`BlockTransactionsKind`].
///
/// A `null` block response means the requested height is not available yet. In that case the future
/// sleeps for the configured poll interval and retries the same height. Other transport/RPC errors
/// are returned to the caller, so retry policy should be configured on the provider transport.
#[pin_project]
#[derive(Debug)]
pub struct BlockFut<T>
where
    T: BlockResponse + RpcRecv,
{
    client: Option<Arc<RpcClientInner>>,
    block_number: u64,
    kind: BlockTransactionsKind,
    poll_interval: Duration,
    #[pin]
    state: BlockFutState<T>,
}

#[pin_project(project = BlockFutStateProj)]
#[derive(Debug)]
enum BlockFutState<T>
where
    T: BlockResponse + RpcRecv,
{
    /// Polling an `eth_getBlockByNumber` request for the target height.
    Request {
        #[pin]
        call: RpcCall<(BlockNumberOrTag, bool), Option<T>>,
    },
    /// Waiting before retrying the same height after the node returned `null`.
    Sleeping { delay: PollIntervalDelay },
    /// Returning a prebuilt result, used when the parent stream cannot create a normal request.
    Ready { result: Option<TransportResult<T>> },
    /// Future has completed and must not be polled again.
    Complete,
}

impl<T> BlockFut<T>
where
    T: BlockResponse + RpcRecv,
{
    pub(super) fn new(
        client: Arc<RpcClientInner>,
        block_number: u64,
        kind: BlockTransactionsKind,
        poll_interval: Duration,
    ) -> Self {
        let call = Self::block_request_call(&client, block_number, kind);
        Self {
            client: Some(client),
            block_number,
            kind,
            poll_interval,
            state: BlockFutState::Request { call },
        }
    }

    pub(super) const fn err(err: TransportError) -> Self {
        Self {
            client: None,
            block_number: 0,
            kind: BlockTransactionsKind::Hashes,
            poll_interval: Duration::from_secs(0),
            state: BlockFutState::Ready { result: Some(Err(err)) },
        }
    }

    fn block_request_call(
        client: &Arc<RpcClientInner>,
        block_number: u64,
        kind: BlockTransactionsKind,
    ) -> RpcCall<(BlockNumberOrTag, bool), Option<T>> {
        client
            .request("eth_getBlockByNumber", (BlockNumberOrTag::from(block_number), kind.is_full()))
    }
}

impl<T> Future for BlockFut<T>
where
    T: BlockResponse + RpcRecv,
{
    type Output = TransportResult<T>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.project();

        loop {
            match this.state.as_mut().project() {
                BlockFutStateProj::Request { call } => match ready!(call.poll(cx)) {
                    Ok(Some(mut block)) => {
                        if this.kind.is_hashes() && block.transactions().is_empty() {
                            block.transactions_mut().convert_to_hashes();
                        }
                        this.state.set(BlockFutState::Complete);
                        return Poll::Ready(Ok(block));
                    }
                    Ok(None) => {
                        this.state.set(BlockFutState::Sleeping {
                            delay: PollIntervalDelay::new(*this.poll_interval),
                        });
                    }
                    Err(err) => {
                        this.state.set(BlockFutState::Complete);
                        return Poll::Ready(Err(err));
                    }
                },
                BlockFutStateProj::Sleeping { delay } => {
                    ready!(delay.poll(cx));
                    let Some(client) = this.client.as_ref() else {
                        this.state.set(BlockFutState::Complete);
                        return Poll::Ready(Err(TransportError::local_usage_str(
                            "provider was dropped",
                        )));
                    };
                    this.state.set(BlockFutState::Request {
                        call: Self::block_request_call(client, *this.block_number, *this.kind),
                    });
                }
                BlockFutStateProj::Ready { result } => {
                    let result = result.take().expect("polled BlockFut after completion");
                    this.state.set(BlockFutState::Complete);
                    return Poll::Ready(result);
                }
                BlockFutStateProj::Complete => panic!("polled BlockFut after completion"),
            }
        }
    }
}

/// Future that resolves a block tag into a numeric head height.
///
/// `WatchBlocksFromStream` and `WatchLogsFromStream` use this before yielding per-height futures so
/// they only schedule work through the configured head tag. Numeric tags and `earliest` resolve
/// immediately. `latest` uses `eth_blockNumber`; other tags use `eth_getBlockByNumber` and return
/// the tagged block's header number.
#[pin_project]
#[derive(Debug)]
pub(super) struct FetchHeadFut<HeaderResp>
where
    HeaderResp: HeaderResponse + RpcRecv,
{
    #[pin]
    state: FetchHeadFutState<HeaderResp>,
}

#[pin_project(project = FetchHeadFutStateProj)]
#[derive(Debug)]
enum FetchHeadFutState<HeaderResp>
where
    HeaderResp: HeaderResponse + RpcRecv,
{
    /// Polling `eth_blockNumber` for a `latest` head.
    Latest {
        #[pin]
        call: RpcCall<[(); 0], U64>,
    },
    /// Polling `eth_getBlockByNumber` for a non-latest tag such as finalized or safe.
    Tagged {
        #[pin]
        call: RpcCall<(BlockNumberOrTag, bool), Option<HeaderResp>>,
    },
    /// Returning an immediately known height, such as a numeric tag or `earliest`.
    Ready { result: Option<TransportResult<u64>> },
    /// Future has completed and must not be polled again.
    Complete,
}

impl<HeaderResp> FetchHeadFut<HeaderResp>
where
    HeaderResp: HeaderResponse + RpcRecv,
{
    pub(super) fn new(client: Arc<RpcClientInner>, tag: BlockNumberOrTag) -> Self {
        let state = match tag {
            BlockNumberOrTag::Number(number) => {
                FetchHeadFutState::Ready { result: Some(Ok(number)) }
            }
            BlockNumberOrTag::Earliest => FetchHeadFutState::Ready { result: Some(Ok(0)) },
            BlockNumberOrTag::Latest => {
                FetchHeadFutState::Latest { call: client.request_noparams("eth_blockNumber") }
            }
            _ => FetchHeadFutState::Tagged {
                call: client.request("eth_getBlockByNumber", (tag, false)),
            },
        };
        Self { state }
    }
}

impl<HeaderResp> Future for FetchHeadFut<HeaderResp>
where
    HeaderResp: HeaderResponse + RpcRecv,
{
    type Output = TransportResult<u64>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.project();

        match this.state.as_mut().project() {
            FetchHeadFutStateProj::Latest { call } => {
                let result = ready!(call.poll(cx)).map(|n| n.to());
                this.state.set(FetchHeadFutState::Complete);
                Poll::Ready(result)
            }
            FetchHeadFutStateProj::Tagged { call } => {
                let result = match ready!(call.poll(cx)) {
                    Ok(resp) => resp.map(|header| header.number()).ok_or(RpcError::NullResp),
                    Err(err) => Err(err),
                };
                this.state.set(FetchHeadFutState::Complete);
                Poll::Ready(result)
            }
            FetchHeadFutStateProj::Ready { result } => {
                let result = result.take().expect("polled FetchHeadFut after completion");
                this.state.set(FetchHeadFutState::Complete);
                Poll::Ready(result)
            }
            FetchHeadFutStateProj::Complete => panic!("polled FetchHeadFut after completion"),
        }
    }
}

/// A builder for streaming blocks from a historical block and continuing indefinitely.
#[derive(Debug, Clone)]
#[must_use = "this builder does nothing unless you call `.into_stream`"]
pub struct WatchBlocksFrom<N: Network> {
    client: WeakClient,
    start_block: u64,
    poll_interval: Duration,
    block_tag: BlockNumberOrTag,
    kind: BlockTransactionsKind,
    _phantom: PhantomData<fn() -> N>,
}

impl<N: Network> WatchBlocksFrom<N> {
    /// Creates a new [`WatchBlocksFrom`] builder.
    pub(crate) const fn new(client: WeakClient, start_block: u64) -> Self {
        Self {
            client,
            start_block,
            poll_interval: DEFAULT_POLL_INTERVAL,
            block_tag: BlockNumberOrTag::Latest,
            kind: BlockTransactionsKind::Hashes,
            _phantom: PhantomData,
        }
    }

    /// Streams blocks with full transaction bodies.
    pub const fn full(mut self) -> Self {
        self.kind = BlockTransactionsKind::Full;
        self
    }

    /// Streams blocks with transaction hashes only.
    pub const fn hashes(mut self) -> Self {
        self.kind = BlockTransactionsKind::Hashes;
        self
    }

    /// Sets the poll interval used when the stream is caught up.
    pub const fn poll_interval(mut self, poll_interval: Duration) -> Self {
        self.poll_interval = poll_interval;
        self
    }

    /// Sets the head block tag used to determine stream progress.
    pub const fn block_tag(mut self, block_tag: BlockNumberOrTag) -> Self {
        self.block_tag = block_tag;
        self
    }

    /// Converts this builder into a canonical-stream builder that emits
    /// [`crate::CanonicalEvent`] deltas on reorgs.
    pub const fn canonical(self) -> WatchCanonicalBlocksFrom<N> {
        WatchCanonicalBlocksFrom::new(self)
    }

    /// Creates a future that fetches a single block by number.
    pub(super) fn get_block(&self, block_number: u64) -> BlockFut<N::BlockResponse> {
        self.client
            .upgrade()
            .map(|client| BlockFut::new(client, block_number, self.kind, self.poll_interval))
            .unwrap_or_else(|| BlockFut::err(RpcError::local_usage_str("provider was dropped")))
    }

    /// Stream blocks from a historical block using sequential `eth_getBlockByNumber` calls.
    ///
    /// This stream continues polling after catching up and continues yielding new blocks
    /// indefinitely.
    ///
    /// This stream _does not_ handle reorgs. Instead, each item yielded from the stream
    /// is strictly ordered in terms of block number, regardless of the blocks parent.
    ///
    /// For example (height, hash, parent):
    ///
    /// You should expect blocks in order by number with no gaps and with disjoint parents:
    /// [(1, 1A, 0A),(2, 2A, 1A),(3,3B,2B)]
    ///
    /// And you should not expect receiving two blocks with the same number:
    /// [(1, 1A, 0A),(2, 2A, 1A),(2,2B,1A)]
    ///
    /// Each yielded future contains one block request.
    ///
    /// If a block request returns `NullResp`, the yielded future retries the same block until it
    /// succeeds.
    ///
    /// Other errors are surfaced to the caller. Configure retries on the underlying client
    /// transport (for example with `RetryBackoffLayer`) for transport-level retry behavior.
    ///
    /// This can be buffered by the caller, for example with
    /// [`StreamExt::buffered`](futures::StreamExt::buffered).
    pub const fn into_stream(self) -> WatchBlocksFromStream<N> {
        let current_block = self.start_block;
        WatchBlocksFromStream {
            inner: self,
            current_block,
            head: 0,
            state: WatchBlocksFromState::FetchHead,
        }
    }
}

/// A stream of block-fetching futures produced by [`WatchBlocksFrom`].
///
/// Each item is a [`BlockFut`] that, when awaited, fetches one block via
/// `eth_getBlockByNumber`. Callers typically apply
/// [`StreamExt::buffered`](futures::StreamExt::buffered) to resolve
/// multiple block requests concurrently.
#[derive(Debug)]
pub struct WatchBlocksFromStream<N: Network> {
    inner: WatchBlocksFrom<N>,
    current_block: u64,
    head: u64,
    state: WatchBlocksFromState<N>,
}

#[derive(Debug)]
enum WatchBlocksFromState<N: Network> {
    /// Upgrade the client and begin fetching head.
    FetchHead,
    /// Polling the in-flight head-block-number future.
    FetchingHead { fut: FetchHeadFut<N::HeaderResponse> },
    /// Yielding block futures for `current_block..=head`.
    Yielding,
    /// Sleeping between poll cycles.
    Sleeping { delay: PollIntervalDelay },
    /// Stream terminated.
    Done,
}

impl<N: Network> Stream for WatchBlocksFromStream<N> {
    type Item = BlockFut<N::BlockResponse>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();

        loop {
            match &mut this.state {
                WatchBlocksFromState::FetchHead => {
                    let Some(client) = this.inner.client.upgrade() else {
                        this.state = WatchBlocksFromState::Done;
                        continue;
                    };
                    let fut = FetchHeadFut::new(client, this.inner.block_tag);
                    this.state = WatchBlocksFromState::FetchingHead { fut };
                }
                WatchBlocksFromState::FetchingHead { fut } => {
                    match ready!(Pin::new(fut).poll(cx)) {
                        Ok(head) => {
                            this.head = head;
                            if this.current_block > head {
                                this.state = WatchBlocksFromState::Sleeping {
                                    delay: PollIntervalDelay::new(this.inner.poll_interval),
                                };
                            } else {
                                this.state = WatchBlocksFromState::Yielding;
                            }
                        }
                        Err(err) => {
                            this.state = WatchBlocksFromState::Sleeping {
                                delay: PollIntervalDelay::new(this.inner.poll_interval),
                            };
                            return Poll::Ready(Some(BlockFut::err(err)));
                        }
                    }
                }
                WatchBlocksFromState::Yielding => {
                    if this.current_block > this.head {
                        this.state = WatchBlocksFromState::Sleeping {
                            delay: PollIntervalDelay::new(this.inner.poll_interval),
                        };
                        continue;
                    }

                    let next_block = this.current_block.saturating_add(1);
                    if next_block <= this.current_block {
                        let err = RpcError::local_usage_str(
                            "watch stream step did not advance block cursor",
                        );
                        this.state = WatchBlocksFromState::Sleeping {
                            delay: PollIntervalDelay::new(this.inner.poll_interval),
                        };
                        return Poll::Ready(Some(BlockFut::err(err)));
                    }

                    let Some(client) = this.inner.client.upgrade() else {
                        this.state = WatchBlocksFromState::Done;
                        continue;
                    };

                    let item_fut: BlockFut<N::BlockResponse> = BlockFut::new(
                        client,
                        this.current_block,
                        this.inner.kind,
                        this.inner.poll_interval,
                    );
                    this.current_block = next_block;
                    return Poll::Ready(Some(item_fut));
                }
                WatchBlocksFromState::Sleeping { delay } => {
                    ready!(delay.poll(cx));
                    this.state = WatchBlocksFromState::FetchHead;
                }
                WatchBlocksFromState::Done => return Poll::Ready(None),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Provider, ProviderBuilder};
    use alloy_rpc_client::RpcClient;
    use alloy_rpc_types_eth::Block;
    use alloy_transport::{
        layers::{RetryBackoffLayer, RetryPolicy},
        mock::MockTransport,
    };
    use futures::StreamExt;
    use tokio::time::timeout;

    fn block(number: u64) -> Block {
        let mut block: Block = Block::default();
        block.header.inner.number = number;
        block
    }

    #[tokio::test]
    async fn streams_blocks_from_start_block() {
        let asserter = alloy_transport::mock::Asserter::new();
        let provider = ProviderBuilder::new().connect_mocked_client(asserter.clone());

        asserter.push_success(&3_u64);
        asserter.push_success(&Some(block(1)));
        asserter.push_success(&Some(block(2)));
        asserter.push_success(&Some(block(3)));

        let mut stream = provider
            .watch_blocks_from(1)
            .block_tag(BlockNumberOrTag::Latest)
            .poll_interval(Duration::from_millis(1))
            .into_stream()
            .buffered(1);

        let first = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(first.header.number, 1);

        let second =
            timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(second.header.number, 2);

        let third = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(third.header.number, 3);
    }

    #[tokio::test]
    async fn advances_to_next_block_after_error() {
        let asserter = alloy_transport::mock::Asserter::new();
        let provider = ProviderBuilder::new().connect_mocked_client(asserter.clone());

        asserter.push_success(&1_u64);
        asserter.push_failure_msg("boom");
        asserter.push_success(&2_u64);
        asserter.push_success(&Some(block(2)));

        let mut stream = provider
            .watch_blocks_from(1)
            .block_tag(BlockNumberOrTag::Latest)
            .poll_interval(Duration::from_millis(1))
            .into_stream()
            .buffered(1);

        let first = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap();
        assert!(first.is_err());

        let second =
            timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(second.header.number, 2);
    }

    #[tokio::test]
    async fn retries_same_block_after_null_response() {
        let asserter = alloy_transport::mock::Asserter::new();
        let provider = ProviderBuilder::new().connect_mocked_client(asserter.clone());

        let no_block: Option<Block> = None;
        asserter.push_success(&1_u64);
        asserter.push_success(&no_block);
        asserter.push_success(&Some(block(1)));
        asserter.push_success(&2_u64);
        asserter.push_success(&Some(block(2)));

        let mut stream = provider
            .watch_blocks_from(1)
            .block_tag(BlockNumberOrTag::Latest)
            .poll_interval(Duration::from_millis(1))
            .into_stream()
            .buffered(1);

        let first = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(first.header.number, 1);

        let second =
            timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(second.header.number, 2);
    }

    #[tokio::test]
    async fn recovers_after_head_fetch_error() {
        let asserter = alloy_transport::mock::Asserter::new();
        let provider = ProviderBuilder::new().connect_mocked_client(asserter.clone());

        asserter.push_failure_msg("head boom");
        asserter.push_success(&1_u64);
        asserter.push_success(&Some(block(1)));

        let mut stream = provider
            .watch_blocks_from(1)
            .block_tag(BlockNumberOrTag::Latest)
            .poll_interval(Duration::from_millis(1))
            .into_stream()
            .buffered(1);

        let first = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap();
        assert!(first.is_err());

        let second =
            timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(second.header.number, 1);
    }

    #[tokio::test]
    async fn uses_provider_retry_layer() {
        #[derive(Clone, Debug)]
        struct AlwaysRetryPolicy;

        impl RetryPolicy for AlwaysRetryPolicy {
            fn should_retry(&self, _error: &alloy_transport::TransportError) -> bool {
                true
            }

            fn backoff_hint(&self, _error: &alloy_transport::TransportError) -> Option<Duration> {
                None
            }
        }

        let asserter = alloy_transport::mock::Asserter::new();
        let retry_layer = RetryBackoffLayer::new_with_policy(3, 0, 10_000, AlwaysRetryPolicy);
        let client = RpcClient::builder()
            .layer(retry_layer)
            .transport(MockTransport::new(asserter.clone()), true);
        let provider = ProviderBuilder::new().connect_client(client);

        asserter.push_failure_msg("temporary head error");
        asserter.push_success(&1_u64);
        asserter.push_failure_msg("temporary block error");
        asserter.push_success(&Some(block(1)));

        let mut stream = provider
            .watch_blocks_from(1)
            .block_tag(BlockNumberOrTag::Latest)
            .poll_interval(Duration::from_millis(1))
            .into_stream()
            .buffered(1);

        let first = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(first.header.number, 1);
    }

    #[tokio::test]
    async fn waits_until_head_reaches_start_block() {
        let asserter = alloy_transport::mock::Asserter::new();
        let provider = ProviderBuilder::new().connect_mocked_client(asserter.clone());

        asserter.push_success(&0_u64);
        asserter.push_success(&1_u64);
        asserter.push_success(&Some(block(1)));

        let mut stream = provider
            .watch_blocks_from(1)
            .block_tag(BlockNumberOrTag::Latest)
            .poll_interval(Duration::from_millis(1))
            .into_stream()
            .buffered(1);

        let first = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(first.header.number, 1);
    }

    #[tokio::test]
    async fn fixed_block_tag_number_does_not_fetch_head() {
        let asserter = alloy_transport::mock::Asserter::new();
        let provider = ProviderBuilder::new().connect_mocked_client(asserter.clone());

        asserter.push_success(&Some(block(5)));

        let mut stream = provider
            .watch_blocks_from(5)
            .block_tag(BlockNumberOrTag::Number(5))
            .poll_interval(Duration::from_millis(1))
            .into_stream()
            .buffered(1);

        let first = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(first.header.number, 5);
    }

    #[tokio::test]
    async fn earliest_block_tag_starts_at_zero() {
        let asserter = alloy_transport::mock::Asserter::new();
        let provider = ProviderBuilder::new().connect_mocked_client(asserter.clone());

        asserter.push_success(&Some(block(0)));

        let mut stream = provider
            .watch_blocks_from(0)
            .block_tag(BlockNumberOrTag::Earliest)
            .poll_interval(Duration::from_millis(1))
            .into_stream()
            .buffered(1);

        let first = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(first.header.number, 0);
    }

    #[tokio::test]
    async fn stream_ends_when_provider_is_dropped() {
        let provider =
            ProviderBuilder::new().connect_mocked_client(alloy_transport::mock::Asserter::new());
        let mut stream = provider.watch_blocks_from(0).into_stream();
        drop(provider);

        let next = timeout(Duration::from_secs(1), stream.next()).await.unwrap();
        assert!(next.is_none());
    }

    #[tokio::test]
    async fn yielded_future_outlives_provider() {
        let asserter = alloy_transport::mock::Asserter::new();
        let provider = ProviderBuilder::new().connect_mocked_client(asserter.clone());

        asserter.push_success(&1_u64);
        asserter.push_success(&Some(block(1)));

        let mut stream = provider
            .watch_blocks_from(1)
            .block_tag(BlockNumberOrTag::Latest)
            .poll_interval(Duration::from_millis(1))
            .into_stream();

        let fut = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap();
        drop(stream);
        drop(provider);

        let block = timeout(Duration::from_secs(1), fut).await.unwrap().unwrap();
        assert_eq!(block.header.number, 1);
    }

    #[tokio::test]
    async fn multiple_yielded_futures_outlive_provider() {
        let asserter = alloy_transport::mock::Asserter::new();
        let provider = ProviderBuilder::new().connect_mocked_client(asserter.clone());

        asserter.push_success(&2_u64);
        asserter.push_success(&Some(block(1)));
        asserter.push_success(&Some(block(2)));

        let mut stream = provider
            .watch_blocks_from(1)
            .block_tag(BlockNumberOrTag::Latest)
            .poll_interval(Duration::from_millis(1))
            .into_stream();

        let fut1 = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap();
        let fut2 = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap();
        drop(provider);

        let first = timeout(Duration::from_secs(1), fut1).await.unwrap().unwrap();
        let second = timeout(Duration::from_secs(1), fut2).await.unwrap().unwrap();
        assert_eq!(first.header.number, 1);
        assert_eq!(second.header.number, 2);
    }

    #[tokio::test]
    async fn errors_when_cursor_cannot_advance() {
        let asserter = alloy_transport::mock::Asserter::new();
        let provider = ProviderBuilder::new().connect_mocked_client(asserter);

        let mut stream = provider
            .watch_blocks_from(u64::MAX)
            .block_tag(BlockNumberOrTag::Number(u64::MAX))
            .poll_interval(Duration::from_millis(1))
            .into_stream()
            .buffered(1);

        let first = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap();
        let err = first.unwrap_err();
        assert!(err.is_local_usage_error());
    }

    #[tokio::test]
    async fn future_stream_can_be_buffered() {
        let asserter = alloy_transport::mock::Asserter::new();
        let provider = ProviderBuilder::new().connect_mocked_client(asserter.clone());

        asserter.push_success(&2_u64);
        asserter.push_success(&Some(block(1)));
        asserter.push_success(&Some(block(2)));

        let mut stream = provider
            .watch_blocks_from(1)
            .block_tag(BlockNumberOrTag::Latest)
            .poll_interval(Duration::from_millis(1))
            .into_stream()
            .buffered(2);

        let first = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(first.header.number, 1);

        let second =
            timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(second.header.number, 2);
    }

    #[tokio::test]
    async fn buffered_stream_does_not_skip_after_null_response() {
        let asserter = alloy_transport::mock::Asserter::new();
        let provider = ProviderBuilder::new().connect_mocked_client(asserter.clone());

        let no_block: Option<Block> = None;
        asserter.push_success(&2_u64);
        asserter.push_success(&no_block);
        asserter.push_success(&Some(block(2)));
        asserter.push_success(&Some(block(1)));

        let mut stream = provider
            .watch_blocks_from(1)
            .block_tag(BlockNumberOrTag::Latest)
            .poll_interval(Duration::from_millis(1))
            .into_stream()
            .buffered(2);

        let first = timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(first.header.number, 1);

        let second =
            timeout(Duration::from_secs(1), stream.next()).await.unwrap().unwrap().unwrap();
        assert_eq!(second.header.number, 2);
    }
}