alloy-provider 2.0.1

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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
use crate::{
    fillers::{
        BlobGasEstimator, BlobGasFiller, CachedNonceManager, ChainIdFiller, FillerControlFlow,
        GasFiller, JoinFill, NonceFiller, NonceManager, RecommendedFillers, SimpleNonceManager,
        TxFiller, WalletFiller,
    },
    layers::{BlockIdLayer, CallBatchLayer, ChainLayer},
    provider::SendableTx,
    utils::Eip1559Estimator,
    Provider, RootProvider,
};
use alloy_chains::NamedChain;
use alloy_network::{Ethereum, IntoWallet, Network};
use alloy_primitives::ChainId;
use alloy_rpc_client::{ClientBuilder, ConnectionConfig, RpcClient};
use alloy_transport::{TransportConnect, TransportError, TransportResult};
use std::marker::PhantomData;

/// A layering abstraction in the vein of [`tower::Layer`]
///
/// [`tower::Layer`]: https://docs.rs/tower/latest/tower/trait.Layer.html
pub trait ProviderLayer<P: Provider<N>, N: Network = Ethereum> {
    /// The provider constructed by this layer.
    type Provider: Provider<N>;

    /// Wrap the given provider in the layer's provider.
    fn layer(&self, inner: P) -> Self::Provider;
}

/// An identity layer that does nothing.
#[derive(Clone, Copy, Debug)]
pub struct Identity;

impl<N> TxFiller<N> for Identity
where
    N: Network,
{
    type Fillable = ();

    fn status(&self, _tx: &<N as Network>::TransactionRequest) -> FillerControlFlow {
        FillerControlFlow::Finished
    }

    fn fill_sync(&self, _tx: &mut SendableTx<N>) {}

    async fn prepare<P>(
        &self,
        _provider: &P,
        _tx: &N::TransactionRequest,
    ) -> TransportResult<Self::Fillable> {
        Ok(())
    }

    async fn fill(
        &self,
        _to_fill: Self::Fillable,
        tx: SendableTx<N>,
    ) -> TransportResult<SendableTx<N>> {
        Ok(tx)
    }
}

impl<P, N> ProviderLayer<P, N> for Identity
where
    N: Network,
    P: Provider<N>,
{
    type Provider = P;

    fn layer(&self, inner: P) -> Self::Provider {
        inner
    }
}

/// A stack of two providers.
#[derive(Debug)]
pub struct Stack<Inner, Outer> {
    inner: Inner,
    outer: Outer,
}

impl<Inner, Outer> Stack<Inner, Outer> {
    /// Create a new `Stack`.
    pub const fn new(inner: Inner, outer: Outer) -> Self {
        Self { inner, outer }
    }
}

impl<P, N, Inner, Outer> ProviderLayer<P, N> for Stack<Inner, Outer>
where
    N: Network,
    P: Provider<N>,
    Inner: ProviderLayer<P, N>,
    Outer: ProviderLayer<Inner::Provider, N>,
{
    type Provider = Outer::Provider;

    fn layer(&self, provider: P) -> Self::Provider {
        let inner = self.inner.layer(provider);

        self.outer.layer(inner)
    }
}

/// A builder for constructing a [`Provider`] from various layers.
///
/// This type is similar to [`tower::ServiceBuilder`], with extra complication
/// around maintaining the network and transport types.
///
/// The [`ProviderBuilder`] can be instantiated in two ways, using `ProviderBuilder::new()` or
/// `ProviderBuilder::default()`.
///
/// `ProviderBuilder::new()` will create a new [`ProviderBuilder`] with the [`RecommendedFillers`]
/// enabled, whereas `ProviderBuilder::default()` will instantiate it in its vanilla
/// [`ProviderBuilder`] form i.e with no fillers enabled.
///
/// [`tower::ServiceBuilder`]: https://docs.rs/tower/latest/tower/struct.ServiceBuilder.html
#[derive(Debug)]
pub struct ProviderBuilder<L, F, N = Ethereum> {
    layer: L,
    filler: F,
    network: PhantomData<fn() -> N>,
}

impl
    ProviderBuilder<
        Identity,
        JoinFill<Identity, <Ethereum as RecommendedFillers>::RecommendedFillers>,
        Ethereum,
    >
{
    /// Create a new [`ProviderBuilder`] with the recommended filler enabled.
    ///
    /// Recommended fillers are preconfigured set of fillers that handle gas estimation, nonce
    /// management, and chain-id fetching.
    ///
    /// Building a provider with this setting enabled will return a [`crate::fillers::FillProvider`]
    /// with [`crate::utils::JoinedRecommendedFillers`].
    ///
    /// You can opt-out of using these fillers by using the `.disable_recommended_fillers()` method.
    pub fn new() -> Self {
        ProviderBuilder::default().with_recommended_fillers()
    }

    /// Opt-out of the recommended fillers by resetting the fillers stack in the
    /// [`ProviderBuilder`].
    ///
    /// This is equivalent to creating the builder using `ProviderBuilder::default()`.
    pub fn disable_recommended_fillers(self) -> ProviderBuilder<Identity, Identity, Ethereum> {
        ProviderBuilder { layer: self.layer, filler: Identity, network: self.network }
    }
}

impl<N> Default for ProviderBuilder<Identity, Identity, N> {
    fn default() -> Self {
        Self { layer: Identity, filler: Identity, network: PhantomData }
    }
}

impl ProviderBuilder<Identity, Identity, Ethereum> {
    /// Create a new [`ProviderBuilder`] with the [`RecommendedFillers`] for the provided
    /// [`Network`].
    pub fn new_with_network<Net: RecommendedFillers>(
    ) -> ProviderBuilder<Identity, JoinFill<Identity, Net::RecommendedFillers>, Net> {
        ProviderBuilder {
            layer: Identity,
            filler: JoinFill::new(Identity, Net::recommended_fillers()),
            network: PhantomData,
        }
    }
}

impl<L, N: Network> ProviderBuilder<L, Identity, N> {
    /// Add preconfigured set of layers handling gas estimation, nonce
    /// management, and chain-id fetching.
    pub fn with_recommended_fillers(
        self,
    ) -> ProviderBuilder<L, JoinFill<Identity, N::RecommendedFillers>, N>
    where
        N: RecommendedFillers,
    {
        self.filler(N::recommended_fillers())
    }
}

impl<L, F, N> ProviderBuilder<L, F, N> {
    /// Apply a function to this builder.
    ///
    /// This is useful for extracting reusable builder-style helper functions without manually
    /// reconstructing the [`ProviderBuilder`].
    pub fn apply<T>(self, f: impl FnOnce(Self) -> T) -> T {
        f(self)
    }

    /// Map the layer stack to a new type.
    ///
    /// This is useful for customizing or replacing the accumulated layers in a reusable helper.
    pub fn map_layer<L2>(self, f: impl FnOnce(L) -> L2) -> ProviderBuilder<L2, F, N> {
        ProviderBuilder { layer: f(self.layer), filler: self.filler, network: PhantomData }
    }

    /// Map the filler stack to a new type.
    ///
    /// This is useful for customizing or replacing the accumulated fillers in a reusable helper.
    pub fn map_filler<F2>(self, f: impl FnOnce(F) -> F2) -> ProviderBuilder<L, F2, N> {
        ProviderBuilder { layer: self.layer, filler: f(self.filler), network: PhantomData }
    }

    /// Add a layer to the stack being built. This is similar to
    /// [`tower::ServiceBuilder::layer`].
    ///
    /// ## Note:
    ///
    /// Layers are added in outer-to-inner order, as in
    /// [`tower::ServiceBuilder`]. The first layer added will be the first to
    /// see the request.
    ///
    /// [`tower::ServiceBuilder::layer`]: https://docs.rs/tower/latest/tower/struct.ServiceBuilder.html#method.layer
    /// [`tower::ServiceBuilder`]: https://docs.rs/tower/latest/tower/struct.ServiceBuilder.html
    pub fn layer<Inner>(self, layer: Inner) -> ProviderBuilder<Stack<Inner, L>, F, N> {
        self.map_layer(|current| Stack::new(layer, current))
    }

    /// Add a transaction filler to the stack being built. Transaction fillers
    /// are used to fill in missing fields on transactions before they are sent,
    /// and are all joined to form the outermost layer of the stack.
    pub fn filler<F2>(self, filler: F2) -> ProviderBuilder<L, JoinFill<F, F2>, N> {
        self.map_filler(|current| JoinFill::new(current, filler))
    }

    /// Change the network.
    ///
    /// By default, the network is `Ethereum`. This method must be called to configure a different
    /// network.
    ///
    /// This replaces the filler stack with the target network's recommended fillers. Any custom
    /// fillers should be added **after** calling `.network()`.
    ///
    /// ```ignore
    /// builder.network::<Arbitrum>()
    /// ```
    pub fn network<Net: RecommendedFillers>(
        self,
    ) -> ProviderBuilder<L, JoinFill<Identity, Net::RecommendedFillers>, Net> {
        ProviderBuilder {
            layer: self.layer,
            filler: JoinFill::new(Identity, Net::recommended_fillers()),
            network: PhantomData,
        }
    }

    /// Add a chain layer to the stack being built. The layer will set
    /// the client's poll interval based on the average block time for this chain.
    ///
    /// Does nothing to the client with a local transport.
    pub fn with_chain(self, chain: NamedChain) -> ProviderBuilder<Stack<ChainLayer, L>, F, N> {
        self.layer(ChainLayer::new(chain))
    }

    // --- Fillers ---

    /// Add blob gas estimation to the stack being built.
    ///
    /// See [`BlobGasFiller`] for more information.
    pub fn with_blob_gas_estimation(self) -> ProviderBuilder<L, JoinFill<F, BlobGasFiller>, N> {
        self.filler(BlobGasFiller::default())
    }

    /// Add blob gas estimation to the stack being built, using the provided estimator.
    ///
    /// See [`BlobGasFiller`] and [`BlobGasEstimator`] for more information.
    pub fn with_blob_gas_estimator(
        self,
        estimator: BlobGasEstimator,
    ) -> ProviderBuilder<L, JoinFill<F, BlobGasFiller>, N> {
        self.filler(BlobGasFiller { estimator })
    }

    /// Add gas estimation to the stack being built.
    ///
    /// See [`GasFiller`] for more information.
    pub fn with_gas_estimation(self) -> ProviderBuilder<L, JoinFill<F, GasFiller>, N> {
        self.filler(GasFiller::default())
    }

    /// Add EIP-1559 gas estimation to the stack being built, using the provided estimator.
    ///
    /// See [`GasFiller`] and [`Eip1559Estimator`] for more information.
    pub fn with_eip1559_estimator(
        self,
        estimator: Eip1559Estimator,
    ) -> ProviderBuilder<L, JoinFill<F, GasFiller>, N> {
        self.filler(GasFiller { estimator })
    }

    /// Add nonce management to the stack being built.
    ///
    /// See [`NonceFiller`] for more information.
    pub fn with_nonce_management<M: NonceManager>(
        self,
        nonce_manager: M,
    ) -> ProviderBuilder<L, JoinFill<F, NonceFiller<M>>, N> {
        self.filler(NonceFiller::new(nonce_manager))
    }

    /// Add simple nonce management to the stack being built.
    ///
    /// See [`SimpleNonceManager`] for more information.
    pub fn with_simple_nonce_management(
        self,
    ) -> ProviderBuilder<L, JoinFill<F, NonceFiller<SimpleNonceManager>>, N> {
        self.with_nonce_management(SimpleNonceManager::default())
    }

    /// Add cached nonce management to the stack being built.
    ///
    /// See [`CachedNonceManager`] for more information.
    pub fn with_cached_nonce_management(
        self,
    ) -> ProviderBuilder<L, JoinFill<F, NonceFiller<CachedNonceManager>>, N> {
        self.with_nonce_management(CachedNonceManager::default())
    }

    /// Add a chain ID filler to the stack being built. The filler will attempt
    /// to fetch the chain ID from the provider using
    /// [`Provider::get_chain_id`]. the first time a transaction is prepared,
    /// and will cache it for future transactions.
    pub fn fetch_chain_id(self) -> ProviderBuilder<L, JoinFill<F, ChainIdFiller>, N> {
        self.filler(ChainIdFiller::default())
    }

    /// Add a specific chain ID to the stack being built. The filler will
    /// fill transactions with the provided chain ID, regardless of the chain ID
    /// that the provider reports via [`Provider::get_chain_id`].
    pub fn with_chain_id(
        self,
        chain_id: ChainId,
    ) -> ProviderBuilder<L, JoinFill<F, ChainIdFiller>, N> {
        self.filler(ChainIdFiller::new(Some(chain_id)))
    }

    /// Add a wallet layer to the stack being built.
    ///
    /// See [`WalletFiller`].
    pub fn wallet<W: IntoWallet<N>>(
        self,
        wallet: W,
    ) -> ProviderBuilder<L, JoinFill<F, WalletFiller<W::NetworkWallet>>, N>
    where
        N: Network,
    {
        self.filler(WalletFiller::new(wallet.into_wallet()))
    }

    // --- Layers ---

    /// Aggregate multiple `eth_call` requests into a single batch request using Multicall3.
    ///
    /// See [`CallBatchLayer`] for more information.
    pub fn with_call_batching(self) -> ProviderBuilder<Stack<CallBatchLayer, L>, F, N> {
        self.layer(CallBatchLayer::new())
    }

    /// Aggregate multiple `eth_call` requests with block number queries done by calling Arbsym
    /// precompile.
    ///
    /// See [`CallBatchLayer`] for more information.
    pub fn with_arbitrum_call_batching(self) -> ProviderBuilder<Stack<CallBatchLayer, L>, F, N> {
        self.layer(CallBatchLayer::new().arbitrum_compat())
    }

    /// Add response caching to the stack being built with the specified maximum cache size.
    ///
    /// See [`CacheLayer`](crate::layers::CacheLayer) for more information.
    #[cfg(not(target_family = "wasm"))]
    pub fn with_caching(
        self,
        max_items: u32,
    ) -> ProviderBuilder<Stack<crate::layers::CacheLayer, L>, F, N> {
        self.layer(crate::layers::CacheLayer::new(max_items))
    }

    /// Add response caching to the stack being built with a default cache size of 100 items.
    ///
    /// See [`CacheLayer`](crate::layers::CacheLayer) for more information.
    #[cfg(not(target_family = "wasm"))]
    pub fn with_default_caching(
        self,
    ) -> ProviderBuilder<Stack<crate::layers::CacheLayer, L>, F, N> {
        self.with_caching(100)
    }

    /// Set a default [`BlockId`] for `eth_call` and `eth_estimateGas`.
    ///
    /// [`BlockId`]: alloy_eips::BlockId
    pub fn with_default_block(
        self,
        block_id: alloy_eips::BlockId,
    ) -> ProviderBuilder<Stack<BlockIdLayer, L>, F, N> {
        self.layer(BlockIdLayer::new(block_id))
    }

    // --- Build to Provider ---

    /// Finish the layer stack by providing a root [`Provider`], outputting
    /// the final [`Provider`] type with all stack components.
    pub fn connect_provider<P>(self, provider: P) -> F::Provider
    where
        L: ProviderLayer<P, N>,
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        P: Provider<N>,
        N: Network,
    {
        let Self { layer, filler, network: PhantomData } = self;
        let stack = Stack::new(layer, filler);
        stack.layer(provider)
    }

    /// Finish the layer stack by providing a root [`RpcClient`], outputting
    /// the final [`Provider`] type with all stack components.
    ///
    /// This is a convenience function for
    /// `ProviderBuilder::on_provider(RootProvider::new(client))`.
    pub fn connect_client(self, client: RpcClient) -> F::Provider
    where
        L: ProviderLayer<RootProvider<N>, N>,
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        N: Network,
    {
        self.connect_provider(RootProvider::new(client))
    }

    /// Finish the layer stack by providing a [`RpcClient`] that mocks responses, outputting
    /// the final [`Provider`] type with all stack components.
    ///
    /// This is a convenience function for
    /// `ProviderBuilder::on_client(RpcClient::mocked(asserter))`.
    pub fn connect_mocked_client(self, asserter: alloy_transport::mock::Asserter) -> F::Provider
    where
        L: ProviderLayer<RootProvider<N>, N>,
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        N: Network,
    {
        self.connect_client(RpcClient::mocked(asserter))
    }

    /// Finish the layer stack by providing a connection string for a built-in
    /// transport type, outputting the final [`Provider`] type with all stack
    /// components.
    #[doc(alias = "on_builtin")]
    pub async fn connect(self, s: &str) -> Result<F::Provider, TransportError>
    where
        L: ProviderLayer<RootProvider<N>, N>,
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        N: Network,
    {
        let client = ClientBuilder::default().connect(s).await?;
        Ok(self.connect_client(client))
    }

    /// Finish the layer stack by providing a connection string with custom configuration.
    ///
    /// This method allows for fine-grained control over connection settings
    /// such as authentication, retry behavior, and transport-specific options.
    /// The transport type is extracted from the connection string and configured
    /// using the provided [`ConnectionConfig`].
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use alloy_provider::{ConnectionConfig, ProviderBuilder};
    /// use alloy_transport::Authorization;
    /// use std::time::Duration;
    ///
    /// let config = ConnectionConfig::new()
    ///     .with_auth(Authorization::bearer("my-token"))
    ///     .with_max_retries(3)
    ///     .with_retry_interval(Duration::from_secs(2));
    ///
    /// let provider =
    ///     ProviderBuilder::new().connect_with_config("ws://localhost:8545", config).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn connect_with_config(
        self,
        s: &str,
        config: ConnectionConfig,
    ) -> Result<F::Provider, TransportError>
    where
        L: ProviderLayer<RootProvider<N>, N>,
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        N: Network,
    {
        let client = ClientBuilder::default().connect_with_config(s, config).await?;
        Ok(self.connect_client(client))
    }

    /// Finish the layer stack by providing a [`TransportConnect`] instance.
    pub async fn connect_with<C>(self, connect: &C) -> Result<F::Provider, TransportError>
    where
        L: ProviderLayer<RootProvider<N>, N>,
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        N: Network,
        C: TransportConnect,
    {
        connect
            .get_transport()
            .await
            .map(|t| RpcClient::new(t, connect.is_local()))
            .map(|client| self.connect_client(client))
    }

    /// Finish the layer stack by providing a [`PubSubConnect`] instance,
    /// producing a [`Provider`] with pubsub capabilities.
    ///
    /// [`PubSubConnect`]: alloy_pubsub::PubSubConnect
    #[cfg(feature = "pubsub")]
    pub async fn connect_pubsub_with<C>(self, connect: C) -> Result<F::Provider, TransportError>
    where
        L: ProviderLayer<RootProvider<N>, N>,
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        N: Network,
        C: alloy_pubsub::PubSubConnect,
    {
        ClientBuilder::default().pubsub(connect).await.map(|client| self.connect_client(client))
    }

    /// Build this provider with a websocket connection.
    #[cfg(feature = "ws")]
    pub async fn connect_ws(
        self,
        connect: alloy_transport_ws::WsConnect,
    ) -> Result<F::Provider, TransportError>
    where
        L: ProviderLayer<RootProvider<N>, N>,
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        N: Network,
    {
        let client = ClientBuilder::default().ws(connect).await?;
        Ok(self.connect_client(client))
    }

    /// Build this provider with an IPC connection.
    #[cfg(feature = "ipc")]
    pub async fn connect_ipc<T>(
        self,
        connect: alloy_transport_ipc::IpcConnect<T>,
    ) -> Result<F::Provider, TransportError>
    where
        alloy_transport_ipc::IpcConnect<T>: alloy_pubsub::PubSubConnect,
        L: ProviderLayer<RootProvider<N>, N>,
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        N: Network,
    {
        let client = ClientBuilder::default().ipc(connect).await?;
        Ok(self.connect_client(client))
    }

    /// Build this provider with an Reqwest HTTP transport.
    #[cfg(any(test, feature = "reqwest"))]
    pub fn connect_http(self, url: reqwest::Url) -> F::Provider
    where
        L: ProviderLayer<crate::RootProvider<N>, N>,
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        N: Network,
    {
        let client = ClientBuilder::default().http(url);
        self.connect_client(client)
    }

    /// Build this provider with a pre-built Reqwest client.
    #[cfg(any(test, feature = "reqwest"))]
    pub fn connect_reqwest<C>(self, client: C, url: reqwest::Url) -> F::Provider
    where
        L: ProviderLayer<crate::RootProvider<N>, N>,
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        N: Network,
        C: Into<reqwest::Client>,
    {
        let client = ClientBuilder::default().http_with_client(client.into(), url);
        self.connect_client(client)
    }

    /// Build this provider with a provided Reqwest client builder.
    #[cfg(any(test, feature = "reqwest"))]
    pub fn with_reqwest<B>(self, url: reqwest::Url, builder: B) -> F::Provider
    where
        L: ProviderLayer<crate::RootProvider<N>, N>,
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        N: Network,
        B: FnOnce(reqwest::ClientBuilder) -> reqwest::Client,
    {
        self.connect_reqwest(builder(reqwest::ClientBuilder::default()), url)
    }

    /// Build this provider with an Hyper HTTP transport.
    #[cfg(feature = "hyper")]
    pub fn connect_hyper_http(self, url: url::Url) -> F::Provider
    where
        L: ProviderLayer<crate::RootProvider<N>, N>,
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        N: Network,
    {
        let client = ClientBuilder::default().hyper_http(url);
        self.connect_client(client)
    }
}

#[cfg(any(test, feature = "anvil-node"))]
type JoinedEthereumWalletFiller<F> = JoinFill<F, WalletFiller<alloy_network::EthereumWallet>>;

#[cfg(any(test, feature = "anvil-node"))]
type AnvilProviderResult<T> = Result<T, alloy_node_bindings::NodeError>;

#[cfg(any(test, feature = "anvil-node"))]
impl<L, F, N: Network> ProviderBuilder<L, F, N> {
    /// Build this provider with anvil, using the BoxTransport.
    ///
    /// This method requires the `anvil-node` feature on `alloy-provider`.
    /// When using the `alloy` meta-crate, enable `provider-anvil-node`, or
    /// combine `providers` with `node-bindings`.
    #[cfg_attr(docsrs, doc(cfg(feature = "anvil-node")))]
    pub fn connect_anvil(self) -> F::Provider
    where
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        L: crate::builder::ProviderLayer<
            crate::layers::AnvilProvider<crate::provider::RootProvider<N>, N>,
            N,
        >,
    {
        self.connect_anvil_with_config(std::convert::identity)
    }

    /// Build this provider with anvil, using the BoxTransport. This
    /// function configures a wallet backed by anvil keys, and is intended for
    /// use in tests.
    ///
    /// This method requires the `anvil-node` feature on `alloy-provider`.
    /// When using the `alloy` meta-crate, enable `provider-anvil-node`, or
    /// combine `providers` with `node-bindings`.
    #[cfg_attr(docsrs, doc(cfg(feature = "anvil-node")))]
    pub fn connect_anvil_with_wallet(
        self,
    ) -> <JoinedEthereumWalletFiller<F> as ProviderLayer<L::Provider, N>>::Provider
    where
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        L: crate::builder::ProviderLayer<
            crate::layers::AnvilProvider<crate::provider::RootProvider<N>, N>,
            N,
        >,
        alloy_network::EthereumWallet: alloy_network::NetworkWallet<N>,
    {
        self.connect_anvil_with_wallet_and_config(std::convert::identity)
            .expect("failed to build provider")
    }

    /// Build this provider with anvil, using the BoxTransport. The
    /// given function is used to configure the anvil instance.
    ///
    /// This method requires the `anvil-node` feature on `alloy-provider`.
    /// When using the `alloy` meta-crate, enable `provider-anvil-node`, or
    /// combine `providers` with `node-bindings`.
    #[cfg_attr(docsrs, doc(cfg(feature = "anvil-node")))]
    pub fn connect_anvil_with_config(
        self,
        f: impl FnOnce(alloy_node_bindings::Anvil) -> alloy_node_bindings::Anvil,
    ) -> F::Provider
    where
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        L: crate::builder::ProviderLayer<
            crate::layers::AnvilProvider<crate::provider::RootProvider<N>, N>,
            N,
        >,
    {
        let anvil_layer = crate::layers::AnvilLayer::from(f(Default::default()));
        let url = anvil_layer.endpoint_url();

        let rpc_client = ClientBuilder::default().http(url);

        self.layer(anvil_layer).connect_client(rpc_client)
    }

    /// Build this provider with anvil, using the BoxTransport. The
    /// given function is used to configure the anvil instance.
    ///
    /// This method requires the `anvil-node` feature on `alloy-provider`.
    /// When using the `alloy` meta-crate, enable `provider-anvil-node`, or
    /// combine `providers` with `node-bindings`.
    #[cfg_attr(docsrs, doc(cfg(feature = "anvil-node")))]
    #[deprecated(since = "0.12.6", note = "use `connect_anvil_with_config` instead")]
    pub fn on_anvil_with_config(
        self,
        f: impl FnOnce(alloy_node_bindings::Anvil) -> alloy_node_bindings::Anvil,
    ) -> F::Provider
    where
        L: ProviderLayer<crate::layers::AnvilProvider<RootProvider<N>, N>, N>,
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
    {
        let anvil_layer = crate::layers::AnvilLayer::from(f(Default::default()));
        let url = anvil_layer.endpoint_url();

        let rpc_client = ClientBuilder::default().http(url);

        self.layer(anvil_layer).connect_client(rpc_client)
    }

    /// Build this provider with anvil, using the BoxTransport.
    /// This calls `try_on_anvil_with_wallet_and_config` and panics on error.
    ///
    /// This method requires the `anvil-node` feature on `alloy-provider`.
    /// When using the `alloy` meta-crate, enable `provider-anvil-node`, or
    /// combine `providers` with `node-bindings`.
    #[cfg_attr(docsrs, doc(cfg(feature = "anvil-node")))]
    pub fn connect_anvil_with_wallet_and_config(
        self,
        f: impl FnOnce(alloy_node_bindings::Anvil) -> alloy_node_bindings::Anvil,
    ) -> AnvilProviderResult<
        <JoinedEthereumWalletFiller<F> as ProviderLayer<L::Provider, N>>::Provider,
    >
    where
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        L: crate::builder::ProviderLayer<
            crate::layers::AnvilProvider<crate::provider::RootProvider<N>, N>,
            N,
        >,
        alloy_network::EthereumWallet: alloy_network::NetworkWallet<N>,
    {
        let anvil_layer = crate::layers::AnvilLayer::from(f(Default::default()));
        let url = anvil_layer.endpoint_url();

        let wallet = anvil_layer
            .instance()
            .wallet()
            .ok_or(alloy_node_bindings::NodeError::NoKeysAvailable)?;

        let rpc_client = ClientBuilder::default().http(url);

        Ok(self.wallet(wallet).layer(anvil_layer).connect_client(rpc_client))
    }

    /// Build this provider with anvil, using the BoxTransport.
    /// This calls `try_on_anvil_with_wallet_and_config` and panics on error.
    ///
    /// This method requires the `anvil-node` feature on `alloy-provider`.
    /// When using the `alloy` meta-crate, enable `provider-anvil-node`, or
    /// combine `providers` with `node-bindings`.
    #[cfg_attr(docsrs, doc(cfg(feature = "anvil-node")))]
    #[deprecated(since = "0.12.6", note = "use `connect_anvil_with_wallet_and_config` instead")]
    pub fn on_anvil_with_wallet_and_config(
        self,
        f: impl FnOnce(alloy_node_bindings::Anvil) -> alloy_node_bindings::Anvil,
    ) -> AnvilProviderResult<
        <JoinedEthereumWalletFiller<F> as ProviderLayer<L::Provider, N>>::Provider,
    >
    where
        F: TxFiller<N> + ProviderLayer<L::Provider, N>,
        L: crate::builder::ProviderLayer<
            crate::layers::AnvilProvider<crate::provider::RootProvider<N>, N>,
            N,
        >,
        alloy_network::EthereumWallet: alloy_network::NetworkWallet<N>,
    {
        let anvil_layer = crate::layers::AnvilLayer::from(f(Default::default()));
        let url = anvil_layer.endpoint_url();

        let wallet = anvil_layer
            .instance()
            .wallet()
            .ok_or(alloy_node_bindings::NodeError::NoKeysAvailable)?;

        let rpc_client = ClientBuilder::default().http(url);

        Ok(self.wallet(wallet).layer(anvil_layer).connect_client(rpc_client))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Provider;
    use alloy_network::AnyNetwork;

    #[tokio::test]
    async fn basic() {
        let provider = ProviderBuilder::new()
            .with_cached_nonce_management()
            .with_call_batching()
            .connect_http("http://localhost:8545".parse().unwrap());
        let _ = provider.get_account(Default::default());
        let provider = provider.erased();
        let _ = provider.get_account(Default::default());
    }

    #[tokio::test]
    #[cfg(feature = "reqwest")]
    async fn test_connect_reqwest() {
        let provider = ProviderBuilder::new()
            .with_cached_nonce_management()
            .with_call_batching()
            .connect_reqwest(
                reqwest::Client::new(),
                reqwest::Url::parse("http://localhost:8545").unwrap(),
            );
        let _ = provider.get_account(Default::default());
        let provider = provider.erased();
        let _ = provider.get_account(Default::default());
    }

    #[tokio::test]
    #[cfg(feature = "reqwest")]
    async fn test_with_reqwest() {
        let provider = ProviderBuilder::new()
            .with_cached_nonce_management()
            .with_call_batching()
            .with_reqwest(reqwest::Url::parse("http://localhost:8545").unwrap(), |builder| {
                builder
                    .user_agent("alloy/test")
                    .timeout(std::time::Duration::from_secs(10))
                    .build()
                    .expect("failed to build reqwest client")
            });
        let _ = provider.get_account(Default::default());
        let provider = provider.erased();
        let _ = provider.get_account(Default::default());
    }

    #[tokio::test]
    async fn compile_with_network() {
        let p = ProviderBuilder::new_with_network::<AnyNetwork>().connect_anvil();
        let num = p.get_block_number().await.unwrap();
        assert_eq!(num, 0);
    }

    // Ensures `.network()` replaces fillers rather than keeping the old ones.
    #[test]
    fn network_replaces_fillers() {
        // Add an extra filler before swapping, it should be dropped.
        let builder = ProviderBuilder::new().filler(GasFiller::default()).network::<AnyNetwork>();

        let _: ProviderBuilder<
            Identity,
            JoinFill<Identity, <AnyNetwork as RecommendedFillers>::RecommendedFillers>,
            AnyNetwork,
        > = builder;
    }

    #[test]
    fn apply_transforms_builder() {
        let builder = ProviderBuilder::new()
            .apply(|builder| builder.disable_recommended_fillers().with_gas_estimation());

        let _: ProviderBuilder<Identity, JoinFill<Identity, GasFiller>, Ethereum> = builder;
    }

    #[test]
    fn map_filler_replaces_fillers() {
        let builder = ProviderBuilder::new().map_filler(|_| GasFiller::default());

        let _: ProviderBuilder<Identity, GasFiller, Ethereum> = builder;
    }

    #[test]
    fn map_layer_replaces_layers() {
        let builder = ProviderBuilder::<Identity, Identity>::default()
            .map_layer(|_| ChainLayer::new(NamedChain::Mainnet));

        let _: ProviderBuilder<ChainLayer, Identity, Ethereum> = builder;
    }

    #[tokio::test]
    async fn network_swap_works_at_runtime() {
        // Verify that `ProviderBuilder::new().network::<AnyNetwork>()` produces a working provider.
        let p = ProviderBuilder::new().network::<AnyNetwork>().connect_anvil();
        let num = p.get_block_number().await.unwrap();
        assert_eq!(num, 0);
    }
}