#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
use std::time::{SystemTime, UNIX_EPOCH};
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
use web_time::{SystemTime, UNIX_EPOCH};
use std::fmt;
use crate::{
config::EvmConfig,
domain::{
Address, Amount, Balance, BlockContext, BlockSelector, ChainId, Observation,
ObservationContext, Source, Timestamp,
},
error::{Error, ProviderError},
transport::{HttpClient, OperationBudget},
};
use super::wire::{
CanonicalBlock, RpcBlock, chain_error, invalid_response, parse_quantity, state_error,
};
mod execution;
mod reads;
mod submission;
pub struct EvmClient {
config: EvmConfig,
chain_id: ChainId,
http: HttpClient,
}
impl EvmClient {
pub async fn connect(config: EvmConfig) -> Result<Self, Error> {
let budget = OperationBudget::new(config.limits())?;
let http = HttpClient::new(config.http_config())?;
let mut client = Self {
chain_id: config.network().chain_id(),
config,
http,
};
let chain_id = budget.run(client.verify_chain(&budget)).await?;
client.chain_id = chain_id;
Ok(client)
}
pub async fn get_native_balance(
&self,
address: Address,
selector: Option<BlockSelector>,
) -> Result<Observation<Balance>, Error> {
let budget = OperationBudget::new(self.config.limits())?;
let selector = selector.unwrap_or_else(|| self.config.default_selector());
budget
.run(self.native_balance(address, selector, &budget))
.await
}
#[must_use]
pub const fn config(&self) -> &EvmConfig {
&self.config
}
#[must_use]
pub const fn chain_id(&self) -> ChainId {
self.chain_id
}
async fn verify_chain(&self, budget: &OperationBudget) -> Result<ChainId, Error> {
let quantity: String = self
.http
.read_rpc(budget, "eth_chainId", &[] as &[(); 0], chain_error)
.await?
.ok_or_else(invalid_response)?;
let chain_id = ChainId::new(parse_quantity(&quantity)?);
if chain_id != self.config.network().chain_id() {
return Err(Error::Provider(ProviderError::ChainMismatch));
}
Ok(chain_id)
}
async fn resolve_block(
&self,
selector: BlockSelector,
budget: &OperationBudget,
) -> Result<BlockContext, Error> {
let (method, identifier) = match selector {
BlockSelector::Latest => ("eth_getBlockByNumber", "latest".to_owned()),
BlockSelector::Safe => ("eth_getBlockByNumber", "safe".to_owned()),
BlockSelector::Finalized => ("eth_getBlockByNumber", "finalized".to_owned()),
BlockSelector::Number(number) => ("eth_getBlockByNumber", format!("0x{number:x}")),
BlockSelector::Hash(hash) => ("eth_getBlockByHash", hash.to_string()),
};
let block: RpcBlock = self
.http
.read_rpc(budget, method, &(identifier, false), state_error)
.await?
.ok_or(Error::UnavailableData)?;
let block = block.context()?;
let mismatch = match selector {
BlockSelector::Number(number) => number != block.number(),
BlockSelector::Hash(hash) => hash != *block.hash(),
BlockSelector::Latest | BlockSelector::Safe | BlockSelector::Finalized => false,
};
if mismatch {
return Err(invalid_response());
}
Ok(block)
}
async fn native_balance(
&self,
address: Address,
selector: BlockSelector,
budget: &OperationBudget,
) -> Result<Observation<Balance>, Error> {
self.verify_chain(budget).await?;
let block = self.resolve_block(selector, budget).await?;
let quantity: String = self
.http
.read_rpc(
budget,
"eth_getBalance",
&(address, CanonicalBlock::new(*block.hash())),
state_error,
)
.await?
.ok_or(Error::UnavailableData)?;
let amount = Amount::new(
parse_quantity(&quantity)?,
Some(self.config.native_asset().decimals()),
);
let retrieved_at = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| Timestamp::from_unix_seconds(duration.as_secs()))
.map_err(|_| Error::Configuration)?;
let source = Source::new(
self.config.provider_id(),
"eth_getBalance",
env!("CARGO_PKG_VERSION"),
)?;
let context = ObservationContext::new(
self.config.network().clone(),
selector,
block,
source,
retrieved_at,
)?;
let balance = Balance::new(address, self.config.native_asset().clone(), amount)?;
Observation::native_balance(balance, context)
}
}
impl fmt::Debug for EvmClient {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("EvmClient")
.field("config", &self.config)
.field("chain_id", &self.chain_id)
.finish_non_exhaustive()
}
}
impl super::NativeBalanceReader for EvmClient {
fn get_native_balance(
&self,
address: Address,
selector: Option<BlockSelector>,
) -> impl std::future::Future<Output = Result<Observation<Balance>, Error>> + crate::future::MaybeSend
{
Self::get_native_balance(self, address, selector)
}
}