ethers_providers/
utils.rs

1use crate::ProviderError;
2use ethers_core::types::U256;
3use futures_timer::Delay;
4use futures_util::{stream, FutureExt, StreamExt};
5use std::{future::Future, pin::Pin};
6
7/// A simple gas escalation policy
8pub type EscalationPolicy = Box<dyn Fn(U256, usize) -> U256 + Send + Sync>;
9
10// Helper type alias
11#[cfg(target_arch = "wasm32")]
12pub(crate) type PinBoxFut<'a, T> = Pin<Box<dyn Future<Output = Result<T, ProviderError>> + 'a>>;
13#[cfg(not(target_arch = "wasm32"))]
14pub(crate) type PinBoxFut<'a, T> =
15    Pin<Box<dyn Future<Output = Result<T, ProviderError>> + Send + 'a>>;
16
17/// Calls the future if `item` is None, otherwise returns a `futures::ok`
18pub async fn maybe<F, T, E>(item: Option<T>, f: F) -> Result<T, E>
19where
20    F: Future<Output = Result<T, E>>,
21{
22    if let Some(item) = item {
23        futures_util::future::ok(item).await
24    } else {
25        f.await
26    }
27}
28
29// https://github.com/tomusdrw/rust-web3/blob/befcb2fb8f3ca0a43e3081f68886fa327e64c8e6/src/api/eth_filter.rs#L20
30/// Create a stream that emits items at a fixed interval. Used for rate control
31pub fn interval(
32    duration: instant::Duration,
33) -> impl futures_core::stream::Stream<Item = ()> + Send + Unpin {
34    stream::unfold((), move |_| Delay::new(duration).map(|_| Some(((), ())))).map(drop)
35}