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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
use ethers_providers_rs::Provider;
use ethers_signer_rs::signer::Signer;
use ethers_types_rs::{
Address, BlockNumberOrTag, Bytecode, Eip55, EthereumUnit, LegacyTransactionRequest, Status,
H256, U256,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use crate::Error;
#[derive(Clone)]
pub struct Client {
pub provider: Provider,
pub signer: Option<Signer>,
}
impl From<Provider> for Client {
fn from(value: Provider) -> Self {
Client {
provider: value.clone(),
signer: None,
}
}
}
impl From<(Provider, Signer)> for Client {
fn from(value: (Provider, Signer)) -> Self {
Client {
provider: value.0.clone(),
signer: Some(value.1),
}
}
}
impl Client {
pub fn is_signer(&self) -> bool {
self.signer.is_some()
}
pub async fn balance(&mut self) -> anyhow::Result<U256> {
let mut signer = self
.signer
.clone()
.ok_or(Error::InvokeMethodExpectSigner("balance".to_owned()))?;
let address = signer.address().await?;
Ok(self.provider.eth_get_balance(address).await?)
}
pub async fn eth_call(&mut self, to: Address, call_data: Vec<u8>) -> anyhow::Result<Vec<u8>> {
let mut provider = self.provider.clone();
let call_data: Bytecode = call_data.into();
let tx: LegacyTransactionRequest = json!({
"to": to,
"data":call_data,
})
.try_into()?;
let result = provider.eth_call(tx, None::<BlockNumberOrTag>).await?;
Ok(result.0)
}
pub async fn deploy_contract(
&mut self,
call_data: Vec<u8>,
ops: TxOptions,
) -> anyhow::Result<Address> {
let tx_hash = self
.send_raw_transaction("deploy", None, call_data, ops)
.await?;
let receipt = self
.provider
.register_transaction_listener(tx_hash)?
.wait()
.await?;
let status = receipt.status.ok_or(Error::TxFailure(tx_hash))?;
match status {
Status::Success => {
if let Some(contract_address) = receipt.contract_address {
return Ok(contract_address);
} else {
return Err(Error::ContractAddress(tx_hash).into());
}
}
Status::Failure => return Err(Error::TxFailure(tx_hash).into()),
}
}
pub async fn send_raw_transaction(
&mut self,
tag: &str,
to: Option<Address>,
call_data: Vec<u8>,
ops: TxOptions,
) -> anyhow::Result<H256> {
let mut provider = self.provider.clone();
let mut signer = self
.signer
.clone()
.ok_or(Error::InvokeMethodExpectSigner(tag.to_owned()))?;
let accounts = signer.accounts().await?;
if accounts.is_empty() {
return Err(Error::SignerAccounts.into());
}
let address = accounts[0];
let nonce = provider.eth_get_transaction_count(address).await?;
log::debug!(
target: tag,
"Fetch account {} nonce, {:#x}",
address.to_checksum_string(),
nonce
);
let chain_id = provider.eth_chain_id().await?;
log::debug!(target: tag, "Fetch chain_id, {}", chain_id);
let mut tx = LegacyTransactionRequest {
chain_id: Some(chain_id),
nonce: Some(nonce),
to,
data: Some(call_data.into()),
value: ops.value,
..Default::default()
};
let gas = provider
.eth_estimate_gas(tx.clone(), None::<BlockNumberOrTag>)
.await?;
log::debug!(target: tag, "Fetch estimate gas, {:#x}", gas);
tx.gas = Some(gas);
let gas_price = if let Some(gas_price) = ops.gas_price {
gas_price
} else {
provider.eth_gas_price().await?
};
log::debug!(target: tag, "Fetch gas price, {:#x}", gas_price);
tx.gas_price = Some(gas_price);
log::debug!(
target: tag,
"Try sign transaction, {}",
serde_json::to_string(&tx)?,
);
let signed_tx = signer.sign_eth_transaction(tx).await?;
log::debug!(target: tag, "Signed transaction, {}", signed_tx.to_string());
let hash = provider.eth_send_raw_transaction(signed_tx).await?;
log::debug!(target: tag, "Send transaction success, {:#?}", hash);
Ok(hash)
}
}
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct TxOptions {
#[serde(skip_serializing_if = "Option::is_none")]
pub gas_price: Option<U256>,
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<U256>,
}
impl<'a> TryFrom<&'a str> for TxOptions {
type Error = anyhow::Error;
fn try_from(value: &'a str) -> Result<Self, Self::Error> {
Ok(serde_json::from_str(value)?)
}
}
impl TryFrom<String> for TxOptions {
type Error = anyhow::Error;
fn try_from(value: String) -> Result<Self, Self::Error> {
Ok(serde_json::from_str(&value)?)
}
}
impl TryFrom<serde_json::Value> for TxOptions {
type Error = anyhow::Error;
fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
Ok(serde_json::from_value(value)?)
}
}
pub trait ToTxOptions {
fn to_tx_options(self) -> TxOptions;
}
impl<T: EthereumUnit> ToTxOptions for T {
fn to_tx_options(self) -> TxOptions {
TxOptions {
gas_price: None,
value: Some(self.to_u256()),
}
}
}