-
Notifications
You must be signed in to change notification settings - Fork 45
/
lib.rs
379 lines (331 loc) · 13 KB
/
lib.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
extern crate proc_macro;
use anyhow::{anyhow, Result};
use ethabi::{Function, Param, ParamType};
use ethcontract_common::truffle::Artifact;
use inflector::Inflector;
use proc_macro2::{Ident, Literal, TokenStream};
use quote::quote;
use std::borrow::Cow;
use syn::{parse_macro_input, Error as SynError, LitStr};
#[proc_macro]
pub fn contract(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as LitStr);
expand_contract(input.clone())
.unwrap_or_else(|e| SynError::new(input.span(), e.to_string()).to_compile_error())
.into()
}
macro_rules! ident {
($name:expr) => {
Ident::new($name, proc_macro2::Span::call_site())
};
}
fn expand_contract(input: LitStr) -> Result<TokenStream> {
// TODO(nlordell): we need a general strategy for name collision; we could
// keep a set of all names in each scope and append things like `_1` to
// the end of the ident in case of collision
// TODO(nlordell): Due to limitation with the proc-macro Span API, we can't
// currently get a path the the file where we were called from; therefore,
// the path will always be rooted on the cargo manifest directory.
// Eventually we can use the `Span::source_file` API to have a better
// experience.
let artifact_path = input.value();
let artifact = Artifact::load(&artifact_path)?;
let contract_name = ident!(&artifact.contract_name.to_pascal_case());
let doc_str = artifact
.devdoc
.details
.as_ref()
.map(String::as_str)
.unwrap_or("Generated by `ethcontract`");
let doc = expand_doc(doc_str);
let deployed = expand_deployed(&artifact);
let deploy = expand_deploy(&artifact)?;
// TODO(nlordell): Generate fallback, events
let functions = artifact
.abi
.functions()
.map(|function| expand_function(&artifact, function))
.collect::<Result<Vec<_>>>()?;
Ok(quote! {
#doc
pub struct #contract_name {
instance: ethcontract::DynInstance,
}
impl #contract_name {
/// Retrieves the truffle artifact used to generate the type safe API
/// for this contract.
pub fn artifact() -> &'static ethcontract::truffle::Artifact {
use ethcontract::foreign::lazy_static;
use ethcontract::truffle::Artifact;
lazy_static! {
pub static ref ARTIFACT: Artifact = {
Artifact::from_json(
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/", #input)))
.expect("valid artifact JSON")
};
}
&ARTIFACT
}
/// Creates a new contract instance with the specified `web3`
/// provider at the given `Address`.
///
/// Note that this does not verify that a contract with a maching
/// `Abi` is actually deployed at the given address.
pub fn at<F, T>(
web3: ðcontract::web3::api::Web3<T>,
address: ethcontract::web3::types::Address,
) -> Self
where
F: ethcontract::web3::futures::Future<Item = ethcontract::json::Value, Error = ethcontract::web3::Error> + Send + 'static,
T: ethcontract::web3::Transport<Out = F> + 'static,
{
use ethcontract::contract::Instance;
use ethcontract::transport::DynTransport;
use ethcontract::web3::api::Web3;
let transport = DynTransport::new(web3.transport().clone());
let web3 = Web3::new(transport);
let abi = Self::artifact().abi.clone();
let instance = Instance::at(web3, abi, address);
Self{ instance }
}
/// Retrieve the undelying instance being used by this contract.
pub fn instance(&self) -> ðcontract::DynInstance {
&self.instance
}
/// Returns the contract address being used by this instance.
pub fn address(&self) -> ethcontract::web3::types::Address {
self.instance.address()
}
#deployed
#deploy
#( #functions )*
}
impl ethcontract::contract::Deploy<ethcontract::DynTransport> for #contract_name {
fn deployed_at(
web3: ethcontract::web3::api::Web3<ethcontract::DynTransport>,
abi: ethcontract::truffle::Abi,
at: ethcontract::web3::types::Address,
) -> Self {
use ethcontract::contract::Instance;
// NOTE(nlordell): we need to make sure that we were deployed
// with the correct ABI; luckily Abi implementes PartialEq
assert_eq!(abi, Self::artifact().abi);
Self {
instance: Instance::at(web3, abi, at),
}
}
}
})
}
fn expand_deployed(artifact: &Artifact) -> TokenStream {
if artifact.networks.is_empty() {
return quote! {};
}
quote! {
/// Locates a deployed contract based on the current network ID
/// reported by the `web3` provider.
///
/// Note that this does not verify that a contract with a maching
/// `Abi` is actually deployed at the given address.
pub fn deployed<F, T>(
web3: ðcontract::web3::api::Web3<T>,
) -> ethcontract::contract::DeployedFuture<ethcontract::DynTransport, Self>
where
F: ethcontract::web3::futures::Future<Item = ethcontract::json::Value, Error = ethcontract::web3::Error> + Send + 'static,
T: ethcontract::web3::Transport<Out = F> + 'static,
{
use ethcontract::contract::DeployedFuture;
use ethcontract::transport::DynTransport;
use ethcontract::truffle::Artifact;
use ethcontract::web3::api::Web3;
let transport = DynTransport::new(web3.transport().clone());
let web3 = Web3::new(transport);
let artifact = { // only clone the pieces we need
let artifact = Self::artifact();
Artifact {
abi: artifact.abi.clone(),
networks: artifact.networks.clone(),
..Artifact::empty()
}
};
DeployedFuture::from_args(web3, artifact)
}
}
}
fn expand_deploy(artifact: &Artifact) -> Result<TokenStream> {
// TODO(nlordell): not sure how contructor documentation get generated as I
// can't seem to get truffle to output it
let doc = expand_doc("Generated by `ethcontract`");
let (input, arg) = match artifact.abi.constructor() {
Some(contructor) => (
expand_inputs(&contructor.inputs)?,
expand_inputs_call_arg(&contructor.inputs),
),
None => (quote! {}, quote! {()}),
};
// TODO(nlordell): we don't handle duplicate library names
let libraries: Vec<_> = artifact
.bytecode
.undefined_libraries()
.map(|name| Param {
name: name.to_snake_case(),
kind: ParamType::Address,
})
.collect();
let lib_input = expand_inputs(&libraries)?;
let link = if libraries.is_empty() {
let link_libraries = libraries.iter().map(|lib| {
let name = Literal::string(&lib.name);
let address = ident!(&lib.name);
quote! {
artifact.bytecode.link(#name, #address).expect("valid library");
}
});
quote! {
let mut artifact = artifact;
#( #link_libraries )*
}
} else {
quote! {}
};
Ok(quote! {
#doc
pub fn deploy<F, T>(
web3: ðcontract::web3::api::Web3<T> #input #lib_input ,
) -> ethcontract::contract::DeployBuilder<ethcontract::DynTransport, Self>
where
F: ethcontract::web3::futures::Future<Item = ethcontract::json::Value, Error = ethcontract::web3::Error> + Send + 'static,
T: ethcontract::web3::Transport<Out = F> + 'static,
{
use ethcontract::contract::DeployBuilder;
use ethcontract::transport::DynTransport;
use ethcontract::truffle::Artifact;
use ethcontract::web3::api::Web3;
let transport = DynTransport::new(web3.transport().clone());
let web3 = Web3::new(transport);
let artifact = { // only clone the pieces we need
let artifact = Self::artifact();
Artifact {
abi: artifact.abi.clone(),
bytecode: artifact.bytecode.clone(),
..Artifact::empty()
}
};
#link
DeployBuilder::new(web3, artifact, #arg).expect("valid deployment args")
}
})
}
fn expand_function(artifact: &Artifact, function: &Function) -> Result<TokenStream> {
let name = ident!(&function.name.to_snake_case());
let name_str = Literal::string(&function.name);
let doc_str = artifact
.devdoc
.methods
.get(&function.name)
.or_else(|| artifact.userdoc.methods.get(&function.name))
.map(String::as_str)
.unwrap_or("Generated by `ethcontract`");
let doc = expand_doc(doc_str);
let input = expand_inputs(&function.inputs)?;
let (method, result) = if function.constant {
let outputs = expand_fn_outputs(&function)?;
(
quote! { call },
quote! { ethcontract::contract::CallBuilder<ethcontract::DynTransport, #outputs> },
)
} else {
(
quote! { send },
quote! { ethcontract::contract::SendBuilder<ethcontract::DynTransport> },
)
};
let arg = expand_inputs_call_arg(&function.inputs);
Ok(quote! {
#doc
pub fn #name(&self #input) -> #result {
self.instance.#method(#name_str, #arg)
.expect("generated call")
}
})
}
fn fix_input_name<'a>(i: usize, n: &'a str) -> Cow<'a, str> {
match n {
"" => format!("p{}", i).into(),
n => n.into(),
}
}
fn expand_inputs(inputs: &[Param]) -> Result<TokenStream> {
let params = inputs
.iter()
.enumerate()
.map(|(i, param)| {
let name_str = fix_input_name(i, ¶m.name);
let name = ident!(&name_str);
let kind = expand_type(¶m.kind)?;
Ok(quote! { #name : #kind })
})
.collect::<Result<Vec<_>>>()?;
Ok(quote! { #( , #params )* })
}
fn expand_inputs_call_arg(inputs: &[Param]) -> TokenStream {
let names = inputs.iter().enumerate().map(|(i, param)| {
let name = fix_input_name(i, ¶m.name);
ident!(&name)
});
quote! { ( #( #names ),* ) }
}
fn expand_fn_outputs(function: &Function) -> Result<TokenStream> {
match function.outputs.len() {
0 => Ok(quote! { () }),
1 => expand_type(&function.outputs[0].kind),
_ => {
let types = function
.outputs
.iter()
.map(|param| expand_type(¶m.kind))
.collect::<Result<Vec<_>>>()?;
Ok(quote! { (#( #types ),*) })
}
}
}
fn expand_type(kind: &ParamType) -> Result<TokenStream> {
match kind {
ParamType::Address => Ok(quote! { ethcontract::web3::types::Address }),
ParamType::Bytes => Ok(quote! { ethcontract::web3::types::Bytes }),
ParamType::Int(n) | ParamType::Uint(n) => match n {
// TODO(nlordell): for now, not all uint/int types implement the
// `Tokenizable` trait, only `u64`, `U128`, and `U256` so we need
// to map solidity int/uint types to those; eventually we should
// add more implementations to the `web3` crate
8 | 16 | 32 | 64 => Ok(quote! { u64 }),
128 => Ok(quote! { ethcontract::web3::types::U128 }),
256 => Ok(quote! { ethcontract::web3::types::U256 }),
n => Err(anyhow!("unsupported solidity type int{}", n)),
},
ParamType::Bool => Ok(quote! { bool }),
ParamType::String => Ok(quote! { String }),
ParamType::Array(t) => {
let inner = expand_type(t)?;
Ok(quote! { Vec<#inner> })
}
ParamType::FixedBytes(n) => {
// TODO(nlordell): what is the performance impact of returning large
// `FixedBytes` and `FixedArray`s with `web3`?
let size = Literal::usize_unsuffixed(*n);
Ok(quote! { [u8; #size] })
}
ParamType::FixedArray(t, n) => {
// TODO(nlordell): see above
let inner = expand_type(t)?;
let size = Literal::usize_unsuffixed(*n);
Ok(quote! { [#inner; #size] })
}
}
}
fn expand_doc(s: &str) -> TokenStream {
let doc = Literal::string(s);
quote! {
#[doc = #doc]
}
}