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