alloy_provider/layers/chain.rs
1use crate::{Provider, ProviderLayer};
2use alloy_chains::NamedChain;
3use alloy_network::Network;
4use std::time::Duration;
5
6/// A layer that wraps a [`NamedChain`]. The layer will be used to set
7/// the client's poll interval based on the average block time for this chain.
8///
9/// Does nothing to the client with a local transport.
10#[derive(Debug, Clone, Copy)]
11pub struct ChainLayer(NamedChain);
12
13impl ChainLayer {
14 /// Create a new `ChainLayer` from the given chain.
15 pub const fn new(chain: NamedChain) -> Self {
16 Self(chain)
17 }
18
19 /// Get the chain's average blocktime, if applicable.
20 pub const fn average_blocktime_hint(&self) -> Option<Duration> {
21 self.0.average_blocktime_hint()
22 }
23}
24
25impl From<NamedChain> for ChainLayer {
26 fn from(chain: NamedChain) -> Self {
27 Self(chain)
28 }
29}
30
31impl<P, N> ProviderLayer<P, N> for ChainLayer
32where
33 P: Provider<N>,
34 N: Network,
35{
36 type Provider = P;
37
38 fn layer(&self, inner: P) -> Self::Provider {
39 if !inner.client().is_local() {
40 if let Some(avg_block_time) = self.average_blocktime_hint() {
41 let poll_interval = avg_block_time.mul_f32(0.6);
42 inner.client().set_poll_interval(poll_interval);
43 }
44 }
45 inner
46 }
47}