This repository has been archived by the owner on Oct 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 791
/
contract.rs
328 lines (280 loc) · 10.5 KB
/
contract.rs
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#![deny(missing_docs)]
mod common;
mod events;
mod methods;
mod structs;
mod types;
use super::{util, Abigen};
use crate::{contract::structs::InternalStructs, rawabi::RawAbi};
use anyhow::{anyhow, Context as _, Result};
use ethers_core::{
abi::{Abi, AbiParser},
macros::{ethers_contract_crate, ethers_core_crate, ethers_providers_crate},
};
use crate::contract::methods::MethodAlias;
use proc_macro2::{Ident, Literal, TokenStream};
use quote::quote;
use serde::Deserialize;
use std::collections::BTreeMap;
use syn::Path;
/// The result of `Context::expand`
#[derive(Debug)]
pub struct ExpandedContract {
/// The name of the contract module
pub module: Ident,
/// The contract module's imports
pub imports: TokenStream,
/// Contract, Middle related implementations
pub contract: TokenStream,
/// All event impls of the contract
pub events: TokenStream,
/// All contract call struct related types
pub call_structs: TokenStream,
/// The contract's internal structs
pub abi_structs: TokenStream,
}
impl ExpandedContract {
/// Merges everything into a single module
pub fn into_tokens(self) -> TokenStream {
let ExpandedContract { module, imports, contract, events, call_structs, abi_structs } =
self;
quote! {
// export all the created data types
pub use #module::*;
#[allow(clippy::too_many_arguments)]
mod #module {
#imports
#contract
#events
#call_structs
#abi_structs
}
}
}
}
/// Internal shared context for generating smart contract bindings.
pub struct Context {
/// The ABI string pre-parsing.
abi_str: Literal,
/// The parsed ABI.
abi: Abi,
/// The parser used for human readable format
abi_parser: AbiParser,
/// Contains all the solidity structs extracted from the JSON ABI.
internal_structs: InternalStructs,
/// Was the ABI in human readable format?
human_readable: bool,
/// The contract name as an identifier.
contract_name: Ident,
/// Manually specified method aliases.
method_aliases: BTreeMap<String, MethodAlias>,
/// Derives added to event structs and enums.
event_derives: Vec<Path>,
/// Manually specified event aliases.
event_aliases: BTreeMap<String, Ident>,
}
impl Context {
/// Expands the whole rust contract
pub fn expand(&self) -> Result<ExpandedContract> {
let name = &self.contract_name;
let name_mod =
util::ident(&format!("{}_mod", self.contract_name.to_string().to_lowercase()));
let abi_name = super::util::safe_ident(&format!("{}_ABI", name.to_string().to_uppercase()));
// 0. Imports
let imports = common::imports(&name.to_string());
// 1. Declare Contract struct
let struct_decl = common::struct_declaration(self, &abi_name);
// 2. Declare events structs & impl FromTokens for each event
let events_decl = self.events_declaration()?;
// 3. impl block for the event functions
let contract_events = self.event_methods()?;
// 4. impl block for the contract methods and their corresponding types
let (contract_methods, call_structs) = self.methods_and_call_structs()?;
// 5. Declare the structs parsed from the human readable abi
let abi_structs_decl = self.abi_structs()?;
let ethers_core = ethers_core_crate();
let ethers_contract = ethers_contract_crate();
let ethers_providers = ethers_providers_crate();
let contract = quote! {
#struct_decl
impl<'a, M: #ethers_providers::Middleware> #name<M> {
/// Creates a new contract instance with the specified `ethers`
/// client at the given `Address`. The contract derefs to a `ethers::Contract`
/// object
pub fn new<T: Into<#ethers_core::types::Address>>(address: T, client: ::std::sync::Arc<M>) -> Self {
let contract = #ethers_contract::Contract::new(address.into(), #abi_name.clone(), client);
Self(contract)
}
// TODO: Implement deployment.
#contract_methods
#contract_events
}
};
Ok(ExpandedContract {
module: name_mod,
imports,
contract,
events: events_decl,
call_structs,
abi_structs: abi_structs_decl,
})
}
/// Create a context from the code generation arguments.
pub fn from_abigen(args: Abigen) -> Result<Self> {
// get the actual ABI string
let abi_str =
args.abi_source.get().map_err(|e| anyhow!("failed to get ABI JSON: {}", e))?;
let (abi, human_readable, abi_parser) = parse_abi(&abi_str)?;
let abi_str = serde_json::to_string(&abi).context("fail to serialize abi to json")?;
// try to extract all the solidity structs from the normal JSON ABI
// we need to parse the json abi again because we need the internalType fields which are
// omitted by ethabi. If the ABI was defined as human readable we use the `internal_structs`
// from the Abi Parser
let internal_structs = if human_readable {
let mut internal_structs = InternalStructs::default();
// the types in the abi_parser are already valid rust types so simply clone them to make
// it consistent with the `RawAbi` variant
internal_structs
.rust_type_names
.extend(abi_parser.function_params.values().map(|ty| (ty.clone(), ty.clone())));
internal_structs.function_params = abi_parser.function_params.clone();
internal_structs.outputs = abi_parser.outputs.clone();
internal_structs
} else {
serde_json::from_str::<RawAbi>(&abi_str)
.ok()
.map(InternalStructs::new)
.unwrap_or_default()
};
let contract_name = util::ident(&args.contract_name);
// NOTE: We only check for duplicate signatures here, since if there are
// duplicate aliases, the compiler will produce a warning because a
// method will be re-defined.
let mut method_aliases = BTreeMap::new();
for (signature, alias) in args.method_aliases.into_iter() {
let alias = MethodAlias {
function_name: util::safe_ident(&alias),
struct_name: util::safe_pascal_case_ident(&alias),
};
if method_aliases.insert(signature.clone(), alias).is_some() {
return Err(anyhow!("duplicate method signature '{}' in method aliases", signature,))
}
}
let mut event_aliases = BTreeMap::new();
for (signature, alias) in args.event_aliases.into_iter() {
let alias = syn::parse_str(&alias)?;
event_aliases.insert(signature, alias);
}
let event_derives = args
.event_derives
.iter()
.map(|derive| syn::parse_str::<Path>(derive))
.collect::<Result<Vec<_>, _>>()
.context("failed to parse event derives")?;
Ok(Context {
abi,
human_readable,
abi_str: Literal::string(&abi_str),
abi_parser,
internal_structs,
contract_name,
method_aliases,
event_derives,
event_aliases,
})
}
/// The internal abi struct mapping table
pub fn internal_structs(&self) -> &InternalStructs {
&self.internal_structs
}
/// The internal mutable abi struct mapping table
pub fn internal_structs_mut(&mut self) -> &mut InternalStructs {
&mut self.internal_structs
}
}
/// Parse the abi via `Source::parse` and return if the abi defined as human readable
fn parse_abi(abi_str: &str) -> Result<(Abi, bool, AbiParser)> {
let mut abi_parser = AbiParser::default();
let res = if let Ok(abi) = abi_parser.parse_str(abi_str) {
(abi, true, abi_parser)
} else {
#[derive(Deserialize)]
struct Contract {
abi: Abi,
}
// a best-effort coercion of an ABI or an artifact JSON into an artifact JSON.
let contract: Contract = if abi_str.trim_start().starts_with('[') {
serde_json::from_str(&format!(r#"{{"abi":{}}}"#, abi_str.trim()))?
} else {
serde_json::from_str::<Contract>(abi_str)?
};
(contract.abi, false, abi_parser)
};
Ok(res)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_abi_str_is_human_readable() {
let abi_str = r#"{
"abi": [
{
"type": "function",
"name": "allowance",
"inputs": [
{
"internalType": "address",
"name": "owner",
"type": "address"
},
{
"internalType": "address",
"name": "spender",
"type": "address"
}
],
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"constant": false,
"stateMutability": "view"
},
{
"type": "function",
"name": "approve",
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"constant": false,
"stateMutability": "nonpayable"
}
],
"bin": "0x",
"bin-runtime": "0x"
}"#;
let (abi, _, _) = parse_abi(&abi_str).unwrap();
let abi_str = serde_json::to_string(&abi).context("fail to serialize abi to json").unwrap();
assert!(&abi_str.starts_with('['));
}
}