This repository has been archived by the owner on Jun 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 54
/
classtemplate.js
474 lines (378 loc) · 13.8 KB
/
classtemplate.js
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
var Web3 = require("web3");
var SolidityEvent = require("web3/lib/web3/event.js");
(function() {
// Planned for future features, logging, etc.
function Provider(provider) {
this.provider = provider;
}
Provider.prototype.send = function() {
this.provider.send.apply(this.provider, arguments);
};
Provider.prototype.sendAsync = function() {
this.provider.sendAsync.apply(this.provider, arguments);
};
var BigNumber = (new Web3()).toBigNumber(0).constructor;
var Utils = {
is_object: function(val) {
return typeof val == "object" && !Array.isArray(val);
},
is_big_number: function(val) {
if (typeof val != "object") return false;
// Instanceof won't work because we have multiple versions of Web3.
try {
new BigNumber(val);
return true;
} catch (e) {
return false;
}
},
merge: function() {
var merged = {};
var args = Array.prototype.slice.call(arguments);
for (var i = 0; i < args.length; i++) {
var object = args[i];
var keys = Object.keys(object);
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
var value = object[key];
merged[key] = value;
}
}
return merged;
},
promisifyFunction: function(fn, C) {
var self = this;
return function() {
var instance = this;
var args = Array.prototype.slice.call(arguments);
var tx_params = {};
var last_arg = args[args.length - 1];
// It's only tx_params if it's an object and not a BigNumber.
if (Utils.is_object(last_arg) && !Utils.is_big_number(last_arg)) {
tx_params = args.pop();
}
tx_params = Utils.merge(C.class_defaults, tx_params);
return new Promise(function(accept, reject) {
var callback = function(error, result) {
if (error != null) {
reject(error);
} else {
accept(result);
}
};
args.push(tx_params, callback);
fn.apply(instance.contract, args);
});
};
},
synchronizeFunction: function(fn, instance, C) {
var self = this;
return function() {
var args = Array.prototype.slice.call(arguments);
var tx_params = {};
var last_arg = args[args.length - 1];
// It's only tx_params if it's an object and not a BigNumber.
if (Utils.is_object(last_arg) && !Utils.is_big_number(last_arg)) {
tx_params = args.pop();
}
tx_params = Utils.merge(C.class_defaults, tx_params);
return new Promise(function(accept, reject) {
var decodeLogs = function(logs) {
return logs.map(function(log) {
var logABI = C.events[log.topics[0]];
if (logABI == null) {
return null;
}
var decoder = new SolidityEvent(null, logABI, instance.address);
return decoder.decode(log);
}).filter(function(log) {
return log != null;
});
};
var callback = function(error, tx) {
if (error != null) {
reject(error);
return;
}
var timeout = C.synchronization_timeout || 240000;
var start = new Date().getTime();
var make_attempt = function() {
C.web3.eth.getTransactionReceipt(tx, function(err, receipt) {
if (err) return reject(err);
if (receipt != null) {
// If they've opted into next gen, return more information.
if (C.next_gen == true) {
return accept({
tx: tx,
receipt: receipt,
logs: decodeLogs(receipt.logs)
});
} else {
return accept(tx);
}
}
if (timeout > 0 && new Date().getTime() - start > timeout) {
return reject(new Error("Transaction " + tx + " wasn't processed in " + (timeout / 1000) + " seconds!"));
}
setTimeout(make_attempt, 1000);
});
};
make_attempt();
};
args.push(tx_params, callback);
fn.apply(self, args);
});
};
}
};
function instantiate(instance, contract) {
instance.contract = contract;
var constructor = instance.constructor;
// Provision our functions.
for (var i = 0; i < instance.abi.length; i++) {
var item = instance.abi[i];
if (item.type == "function") {
if (item.constant == true) {
instance[item.name] = Utils.promisifyFunction(contract[item.name], constructor);
} else {
instance[item.name] = Utils.synchronizeFunction(contract[item.name], instance, constructor);
}
instance[item.name].call = Utils.promisifyFunction(contract[item.name].call, constructor);
instance[item.name].sendTransaction = Utils.promisifyFunction(contract[item.name].sendTransaction, constructor);
instance[item.name].request = contract[item.name].request;
instance[item.name].estimateGas = Utils.promisifyFunction(contract[item.name].estimateGas, constructor);
}
if (item.type == "event") {
instance[item.name] = contract[item.name];
}
}
instance.allEvents = contract.allEvents;
instance.address = contract.address;
instance.transactionHash = contract.transactionHash;
};
// Use inheritance to create a clone of this contract,
// and copy over contract's static functions.
function mutate(fn) {
var temp = function Clone() { return fn.apply(this, arguments); };
Object.keys(fn).forEach(function(key) {
temp[key] = fn[key];
});
temp.prototype = Object.create(fn.prototype);
bootstrap(temp);
return temp;
};
function bootstrap(fn) {
fn.web3 = new Web3();
fn.class_defaults = fn.prototype.defaults || {};
// Set the network iniitally to make default data available and re-use code.
// Then remove the saved network id so the network will be auto-detected on first use.
fn.setNetwork("default");
fn.network_id = null;
return fn;
};
// Accepts a contract object created with web3.eth.contract.
// Optionally, if called without `new`, accepts a network_id and will
// create a new version of the contract abstraction with that network_id set.
function Contract() {
if (this instanceof Contract) {
instantiate(this, arguments[0]);
} else {
var C = mutate(Contract);
var network_id = arguments.length > 0 ? arguments[0] : "default";
C.setNetwork(network_id);
return C;
}
};
Contract.currentProvider = null;
Contract.setProvider = function(provider) {
var wrapped = new Provider(provider);
this.web3.setProvider(wrapped);
this.currentProvider = provider;
};
Contract.new = function() {
if (this.currentProvider == null) {
throw new Error("{{NAME}} error: Please call setProvider() first before calling new().");
}
var args = Array.prototype.slice.call(arguments);
if (!this.unlinked_binary) {
throw new Error("{{NAME}} error: contract binary not set. Can't deploy new instance.");
}
var regex = /__[^_]+_+/g;
var unlinked_libraries = this.binary.match(regex);
if (unlinked_libraries != null) {
unlinked_libraries = unlinked_libraries.map(function(name) {
// Remove underscores
return name.replace(/_/g, "");
}).sort().filter(function(name, index, arr) {
// Remove duplicates
if (index + 1 >= arr.length) {
return true;
}
return name != arr[index + 1];
}).join(", ");
throw new Error("{{NAME}} contains unresolved libraries. You must deploy and link the following libraries before you can deploy a new version of {{NAME}}: " + unlinked_libraries);
}
var self = this;
return new Promise(function(accept, reject) {
var contract_class = self.web3.eth.contract(self.abi);
var tx_params = {};
var last_arg = args[args.length - 1];
// It's only tx_params if it's an object and not a BigNumber.
if (Utils.is_object(last_arg) && !Utils.is_big_number(last_arg)) {
tx_params = args.pop();
}
tx_params = Utils.merge(self.class_defaults, tx_params);
if (tx_params.data == null) {
tx_params.data = self.binary;
}
// web3 0.9.0 and above calls new twice this callback twice.
// Why, I have no idea...
var intermediary = function(err, web3_instance) {
if (err != null) {
reject(err);
return;
}
if (err == null && web3_instance != null && web3_instance.address != null) {
accept(new self(web3_instance));
}
};
args.push(tx_params, intermediary);
contract_class.new.apply(contract_class, args);
});
};
Contract.at = function(address) {
if (address == null || typeof address != "string" || address.length != 42) {
throw new Error("Invalid address passed to {{NAME}}.at(): " + address);
}
var contract_class = this.web3.eth.contract(this.abi);
var contract = contract_class.at(address);
return new this(contract);
};
Contract.deployed = function() {
if (!this.address) {
throw new Error("Cannot find deployed address: {{NAME}} not deployed or address not set.");
}
return this.at(this.address);
};
Contract.defaults = function(class_defaults) {
if (this.class_defaults == null) {
this.class_defaults = {};
}
if (class_defaults == null) {
class_defaults = {};
}
var self = this;
Object.keys(class_defaults).forEach(function(key) {
var value = class_defaults[key];
self.class_defaults[key] = value;
});
return this.class_defaults;
};
Contract.extend = function() {
var args = Array.prototype.slice.call(arguments);
for (var i = 0; i < arguments.length; i++) {
var object = arguments[i];
var keys = Object.keys(object);
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
var value = object[key];
this.prototype[key] = value;
}
}
};
Contract.all_networks = {{ALL_NETWORKS}};
Contract.checkNetwork = function(callback) {
var self = this;
if (this.network_id != null) {
return callback();
}
this.web3.version.network(function(err, result) {
if (err) return callback(err);
var network_id = result.toString();
// If we have the main network,
if (network_id == "1") {
var possible_ids = ["1", "live", "default"];
for (var i = 0; i < possible_ids.length; i++) {
var id = possible_ids[i];
if (Contract.all_networks[id] != null) {
network_id = id;
break;
}
}
}
if (self.all_networks[network_id] == null) {
return callback(new Error(self.name + " error: Can't find artifacts for network id '" + network_id + "'"));
}
self.setNetwork(network_id);
callback();
})
};
Contract.setNetwork = function(network_id) {
var network = this.all_networks[network_id] || {};
this.abi = this.prototype.abi = network.abi;
this.unlinked_binary = this.prototype.unlinked_binary = network.unlinked_binary;
this.address = this.prototype.address = network.address;
this.updated_at = this.prototype.updated_at = network.updated_at;
this.links = this.prototype.links = network.links || {};
this.events = this.prototype.events = network.events || {};
this.network_id = network_id;
};
Contract.networks = function() {
return Object.keys(this.all_networks);
};
Contract.link = function(name, address) {
if (typeof name == "function") {
var contract = name;
if (contract.address == null) {
throw new Error("Cannot link contract without an address.");
}
Contract.link(contract.contract_name, contract.address);
// Merge events so this contract knows about library's events
Object.keys(contract.events).forEach(function(topic) {
Contract.events[topic] = contract.events[topic];
});
return;
}
if (typeof name == "object") {
var obj = name;
Object.keys(obj).forEach(function(name) {
var a = obj[name];
Contract.link(name, a);
});
return;
}
Contract.links[name] = address;
};
Contract.contract_name = Contract.prototype.contract_name = "{{NAME}}";
Contract.generated_with = Contract.prototype.generated_with = "{{PUDDING_VERSION}}";
// Allow people to opt-in to breaking changes now.
Contract.next_gen = false;
var properties = {
binary: function() {
var binary = Contract.unlinked_binary;
Object.keys(Contract.links).forEach(function(library_name) {
var library_address = Contract.links[library_name];
var regex = new RegExp("__" + library_name + "_*", "g");
binary = binary.replace(regex, library_address.replace("0x", ""));
});
return binary;
}
};
Object.keys(properties).forEach(function(key) {
var getter = properties[key];
var definition = {};
definition.enumerable = true;
definition.configurable = false;
definition.get = getter;
Object.defineProperty(Contract, key, definition);
Object.defineProperty(Contract.prototype, key, definition);
});
bootstrap(Contract);
if (typeof module != "undefined" && typeof module.exports != "undefined") {
module.exports = Contract;
} else {
// There will only be one version of this contract in the browser,
// and we can use that.
window.{{NAME}} = Contract;
}
})();