#![allow(clippy::return_self_not_must_use)]
use super::base::{decode_function_data, AbiError};
use ethers_core::{
abi::{AbiDecode, AbiEncode, Detokenize, Function, InvalidOutputType, Tokenizable},
types::{
transaction::eip2718::TypedTransaction, Address, BlockId, Bytes, Selector,
TransactionRequest, U256,
},
utils::id,
};
use ethers_providers::{
call_raw::{CallBuilder, RawCall},
Middleware, PendingTransaction, ProviderError,
};
use std::{
borrow::Cow,
fmt::Debug,
future::{Future, IntoFuture},
marker::PhantomData,
pin::Pin,
sync::Arc,
};
use thiserror::Error as ThisError;
pub trait EthCall: Tokenizable + AbiDecode + AbiEncode + Send + Sync {
fn function_name() -> Cow<'static, str>;
fn abi_signature() -> Cow<'static, str>;
fn selector() -> Selector {
id(Self::abi_signature())
}
}
#[derive(ThisError, Debug)]
pub enum ContractError<M: Middleware> {
#[error(transparent)]
DecodingError(#[from] ethers_core::abi::Error),
#[error(transparent)]
AbiError(#[from] AbiError),
#[error(transparent)]
DetokenizationError(#[from] InvalidOutputType),
#[error("{0}")]
MiddlewareError(M::Error),
#[error("{0}")]
ProviderError(ProviderError),
#[error("constructor is not defined in the ABI")]
ConstructorError,
#[error("Contract was not deployed")]
ContractNotDeployed,
}
#[derive(Debug)]
#[must_use = "contract calls do nothing unless you `send` or `call` them"]
pub struct ContractCall<M, D> {
pub tx: TypedTransaction,
pub function: Function,
pub block: Option<BlockId>,
pub(crate) client: Arc<M>,
pub(crate) datatype: PhantomData<D>,
}
impl<M, D> Clone for ContractCall<M, D> {
fn clone(&self) -> Self {
ContractCall {
tx: self.tx.clone(),
function: self.function.clone(),
block: self.block,
client: self.client.clone(),
datatype: self.datatype,
}
}
}
impl<M, D: Detokenize> ContractCall<M, D> {
pub fn from<T: Into<Address>>(mut self, from: T) -> Self {
self.tx.set_from(from.into());
self
}
pub fn legacy(mut self) -> Self {
self.tx = match self.tx {
TypedTransaction::Eip1559(inner) => {
let tx: TransactionRequest = inner.into();
TypedTransaction::Legacy(tx)
}
other => other,
};
self
}
pub fn gas<T: Into<U256>>(mut self, gas: T) -> Self {
self.tx.set_gas(gas);
self
}
pub fn gas_price<T: Into<U256>>(mut self, gas_price: T) -> Self {
self.tx.set_gas_price(gas_price);
self
}
pub fn value<T: Into<U256>>(mut self, value: T) -> Self {
self.tx.set_value(value);
self
}
pub fn block<T: Into<BlockId>>(mut self, block: T) -> Self {
self.block = Some(block.into());
self
}
}
impl<M, D> ContractCall<M, D>
where
M: Middleware,
D: Detokenize,
{
pub fn calldata(&self) -> Option<Bytes> {
self.tx.data().cloned()
}
pub async fn estimate_gas(&self) -> Result<U256, ContractError<M>> {
self.client.estimate_gas(&self.tx, self.block).await.map_err(ContractError::MiddlewareError)
}
pub async fn call(&self) -> Result<D, ContractError<M>> {
let bytes =
self.client.call(&self.tx, self.block).await.map_err(ContractError::MiddlewareError)?;
let data = decode_function_data(&self.function, &bytes, false)?;
Ok(data)
}
pub fn call_raw(
&self,
) -> impl RawCall<'_> + Future<Output = Result<D, ContractError<M>>> + Debug {
let call = self.call_raw_bytes();
call.map(move |res: Result<Bytes, ProviderError>| {
let bytes = res.map_err(ContractError::ProviderError)?;
decode_function_data(&self.function, &bytes, false).map_err(From::from)
})
}
pub fn call_raw_bytes(&self) -> CallBuilder<'_, M::Provider> {
let call = self.client.provider().call_raw(&self.tx);
if let Some(block) = self.block {
call.block(block)
} else {
call
}
}
pub async fn send(&self) -> Result<PendingTransaction<'_, M::Provider>, ContractError<M>> {
self.client
.send_transaction(self.tx.clone(), self.block)
.await
.map_err(ContractError::MiddlewareError)
}
}
impl<M, D> IntoFuture for ContractCall<M, D>
where
Self: 'static,
M: Middleware,
D: Detokenize,
{
type Output = Result<D, ContractError<M>>;
type IntoFuture = Pin<Box<dyn Future<Output = Self::Output>>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(async move { self.call().await })
}
}