1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
use ethers_core::{
abi::{Detokenize, Error as AbiError, Function, InvalidOutputType},
types::{Address, BlockNumber, TransactionRequest, U256},
};
use ethers_providers::{JsonRpcClient, PendingTransaction, ProviderError};
use ethers_signers::{Client, ClientError, Signer};
use std::{fmt::Debug, marker::PhantomData};
use thiserror::Error as ThisError;
#[derive(ThisError, Debug)]
pub enum ContractError {
#[error(transparent)]
DecodingError(#[from] AbiError),
#[error(transparent)]
DetokenizationError(#[from] InvalidOutputType),
#[error(transparent)]
ClientError(#[from] ClientError),
#[error(transparent)]
ProviderError(#[from] ProviderError),
#[error("constructor is not defined in the ABI")]
ConstructorError,
#[error("Contract was not deployed")]
ContractNotDeployed,
}
#[derive(Debug, Clone)]
#[must_use = "contract calls do nothing unless you `send` or `call` them"]
pub struct ContractCall<'a, P, S, D> {
pub tx: TransactionRequest,
pub function: Function,
pub block: Option<BlockNumber>,
pub(crate) client: &'a Client<P, S>,
pub(crate) datatype: PhantomData<D>,
}
impl<'a, P, S, D: Detokenize> ContractCall<'a, P, S, D> {
pub fn from<T: Into<Address>>(mut self, from: T) -> Self {
self.tx.from = Some(from.into());
self
}
pub fn gas<T: Into<U256>>(mut self, gas: T) -> Self {
self.tx.gas = Some(gas.into());
self
}
pub fn gas_price<T: Into<U256>>(mut self, gas_price: T) -> Self {
self.tx.gas_price = Some(gas_price.into());
self
}
pub fn value<T: Into<U256>>(mut self, value: T) -> Self {
self.tx.value = Some(value.into());
self
}
pub fn block<T: Into<BlockNumber>>(mut self, block: T) -> Self {
self.block = Some(block.into());
self
}
}
impl<'a, P, S, D> ContractCall<'a, P, S, D>
where
S: Signer,
P: JsonRpcClient,
D: Detokenize,
{
pub async fn call(&self) -> Result<D, ContractError> {
let bytes = self.client.call(&self.tx, self.block).await?;
let tokens = self.function.decode_output(&bytes.0)?;
let data = D::from_tokens(tokens)?;
Ok(data)
}
pub async fn send(self) -> Result<PendingTransaction<'a, P>, ContractError> {
Ok(self.client.send_transaction(self.tx, self.block).await?)
}
}