alloy_provider/layers/
anvil.rsuse alloy_network::Ethereum;
use alloy_node_bindings::{Anvil, AnvilInstance};
use reqwest::Url;
use std::sync::{Arc, OnceLock};
use crate::{Provider, ProviderLayer, RootProvider};
#[derive(Debug, Clone, Default)]
pub struct AnvilLayer {
anvil: Anvil,
instance: OnceLock<Arc<AnvilInstance>>,
}
impl AnvilLayer {
pub fn instance(&self) -> &Arc<AnvilInstance> {
self.instance.get_or_init(|| Arc::new(self.anvil.clone().spawn()))
}
#[doc(alias = "http_endpoint_url")]
pub fn endpoint_url(&self) -> Url {
self.instance().endpoint_url()
}
pub fn ws_endpoint_url(&self) -> Url {
self.instance().ws_endpoint_url()
}
}
impl From<Anvil> for AnvilLayer {
fn from(anvil: Anvil) -> Self {
Self { anvil, instance: OnceLock::new() }
}
}
impl<P> ProviderLayer<P, Ethereum> for AnvilLayer
where
P: Provider,
{
type Provider = AnvilProvider<P>;
fn layer(&self, inner: P) -> Self::Provider {
let anvil = self.instance();
AnvilProvider::new(inner, anvil.clone())
}
}
#[derive(Clone, Debug)]
pub struct AnvilProvider<P> {
inner: P,
anvil: Arc<AnvilInstance>,
}
impl<P> AnvilProvider<P>
where
P: Provider,
{
#[allow(clippy::missing_const_for_fn)]
pub fn new(inner: P, anvil: Arc<AnvilInstance>) -> Self {
Self { inner, anvil }
}
pub fn anvil(&self) -> &Arc<AnvilInstance> {
&self.anvil
}
}
impl<P> Provider for AnvilProvider<P>
where
P: Provider,
{
#[inline(always)]
fn root(&self) -> &RootProvider {
self.inner.root()
}
}