This repository has been archived by the owner on Jan 1, 2020. It is now read-only.
forked from oladotunr/truffle-contract
-
Notifications
You must be signed in to change notification settings - Fork 0
/
contract.js
795 lines (638 loc) · 22.8 KB
/
contract.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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
var ethJSABI = require("ethjs-abi");
var BlockchainUtils = require("truffle-blockchain-utils");
var Web3 = require("web3");
// For browserified version. If browserify gave us an empty version,
// look for the one provided by the user.
if (typeof Web3 == "object" && Object.keys(Web3).length == 0) {
Web3 = global.Web3;
}
var contract = (function(module) {
// Planned for future features, logging, etc.
function Provider(provider) {
this.provider = provider;
}
Provider.prototype.send = function() {
return this.provider.send.apply(this.provider, arguments);
};
Provider.prototype.sendAsync = function() {
return 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;
}
},
decodeLogs: function(C, instance, logs) {
return logs.map(function(log) {
var logABI = C.events[log.topics[0]];
if (logABI == null) {
return null;
}
// This function has been adapted from web3's SolidityEvent.decode() method,
// and built to work with ethjs-abi.
var copy = Utils.merge({}, log);
function partialABI(fullABI, indexed) {
var inputs = fullABI.inputs.filter(function (i) {
return i.indexed === indexed;
});
var partial = {
inputs: inputs,
name: fullABI.name,
type: fullABI.type,
anonymous: fullABI.anonymous
};
return partial;
}
var argTopics = logABI.anonymous ? copy.topics : copy.topics.slice(1);
var indexedData = "0x" + argTopics.map(function (topics) { return topics.slice(2); }).join("");
var indexedParams = ethJSABI.decodeEvent(partialABI(logABI, true), indexedData);
var notIndexedData = copy.data;
var notIndexedParams = ethJSABI.decodeEvent(partialABI(logABI, false), notIndexedData);
copy.event = logABI.name;
copy.args = logABI.inputs.reduce(function (acc, current) {
var val = indexedParams[current.name];
if (val === undefined) {
val = notIndexedParams[current.name];
}
acc[current.name] = val;
return acc;
}, {});
Object.keys(copy.args).forEach(function(key) {
var val = copy.args[key];
// We have BN. Convert it to BigNumber
if (val.constructor.isBN) {
copy.args[key] = C.web3.toBigNumber("0x" + val.toString(16));
}
});
delete copy.data;
delete copy.topics;
return copy;
}).filter(function(log) {
return log != null;
});
},
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 C.detectNetwork().then(function() {
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 C.detectNetwork().then(function() {
return new Promise(function(accept, reject) {
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) {
return accept({
tx: tx,
receipt: receipt,
logs: Utils.decodeLogs(C, instance, receipt.logs)
});
}
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);
});
});
};
},
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;
},
parallel: function (arr, callback) {
callback = callback || function () {};
if (!arr.length) {
return callback(null, []);
}
var index = 0;
var results = new Array(arr.length);
arr.forEach(function (fn, position) {
fn(function (err, result) {
if (err) {
callback(err);
callback = function () {};
} else {
index++;
results[position] = result;
if (index >= arr.length) {
callback(null, results);
}
}
});
});
},
bootstrap: function(fn) {
// Add our static methods
Object.keys(fn._static_methods).forEach(function(key) {
fn[key] = fn._static_methods[key].bind(fn);
});
// Add our properties.
Object.keys(fn._properties).forEach(function(key) {
fn.addProp(key, fn._properties[key]);
});
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(contract) {
var self = this;
var constructor = this.constructor;
this.abi = constructor.abi;
if (typeof contract == "string") {
var address = contract;
var contract_class = constructor.web3.eth.contract(this.abi);
contract = contract_class.at(address);
}
this.contract = contract;
// Provision our functions.
for (var i = 0; i < this.abi.length; i++) {
var item = this.abi[i];
if (item.type == "function") {
if (item.constant == true) {
this[item.name] = Utils.promisifyFunction(contract[item.name], constructor);
} else {
this[item.name] = Utils.synchronizeFunction(contract[item.name], this, constructor);
}
this[item.name].call = Utils.promisifyFunction(contract[item.name].call, constructor);
this[item.name].sendTransaction = Utils.promisifyFunction(contract[item.name].sendTransaction, constructor);
this[item.name].request = contract[item.name].request;
this[item.name].estimateGas = Utils.promisifyFunction(contract[item.name].estimateGas, constructor);
}
if (item.type == "event") {
this[item.name] = contract[item.name];
}
}
this.sendTransaction = Utils.synchronizeFunction(function(tx_params, callback) {
if (typeof tx_params == "function") {
callback = tx_params;
tx_params = {};
}
tx_params.to = self.address;
constructor.web3.eth.sendTransaction.apply(constructor.web3.eth, [tx_params, callback]);
}, this, constructor);
this.send = function(value) {
return self.sendTransaction({value: value});
};
this.allEvents = contract.allEvents;
this.address = contract.address;
this.transactionHash = contract.transactionHash;
};
Contract._static_methods = {
setProvider: function(provider) {
if (!provider) {
throw new Error("Invalid provider passed to setProvider(); provider is " + provider);
}
var wrapped = new Provider(provider);
this.web3.setProvider(wrapped);
this.currentProvider = provider;
},
new: function() {
var self = this;
if (this.currentProvider == null) {
throw new Error(this.contract_name + " error: Please call setProvider() first before calling new().");
}
var args = Array.prototype.slice.call(arguments);
if (!this.unlinked_binary) {
throw new Error(this._json.contract_name + " error: contract binary not set. Can't deploy new instance.");
}
return self.detectNetwork().then(function(network_id) {
// After the network is set, check to make sure everything's ship shape.
var regex = /__[^_]+_+/g;
var unlinked_libraries = self.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(self.contract_name + " contains unresolved libraries. You must deploy and link the following libraries before you can deploy a new version of " + self._json.contract_name + ": " + unlinked_libraries);
}
}).then(function() {
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 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);
});
});
},
at: function(address) {
var self = this;
if (address == null || typeof address != "string" || address.length != 42) {
throw new Error("Invalid address passed to " + this._json.contract_name + ".at(): " + address);
}
var contract = new this(address);
// Add thennable to allow people opt into new recommended usage.
contract.then = function(fn) {
return self.detectNetwork().then(function(network_id) {
var instance = new self(address);
return new Promise(function(accept, reject) {
self.web3.eth.getCode(address, function(err, code) {
if (err) return reject(err);
if (!code || code.replace("0x", "").replace(/0/g, "") === '') {
return reject(new Error("Cannot create instance of " + self.contract_name + "; no code at address " + address));
}
accept(instance);
});
});
}).then(fn);
};
return contract;
},
deployed: function() {
var self = this;
return self.detectNetwork().then(function() {
// We don't have a network config for the one we found
if (self._json.networks[self.network_id] == null) {
throw new Error(self.contract_name + " has not been deployed to detected network (network/artifact mismatch)");
}
// If we found the network but it's not deployed
if (!self.isDeployed()) {
throw new Error(self.contract_name + " has not been deployed to detected network (" + self.network_id + ")");
}
return new self(self.address);
});
},
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;
},
hasNetwork: function(network_id) {
return this._json.networks[network_id + ""] != null;
},
isDeployed: function() {
if (this.network_id == null) {
return false;
}
if (this._json.networks[this.network_id] == null) {
return false;
}
return !!this.network.address;
},
detectNetwork: function() {
var self = this;
return new Promise(function(accept, reject) {
// Try to detect the network we have artifacts for.
if (self.network_id) {
// We have a network id and a configuration, let's go with it.
if (self.networks[self.network_id] != null) {
return accept(self.network_id);
}
}
self.web3.version.getNetwork(function(err, result) {
if (err) return reject(err);
var network_id = result.toString();
// If we found the network via a number, let's use that.
if (self.hasNetwork(network_id)) {
self.setNetwork(network_id);
return accept();
}
// Otherwise, go through all the networks that are listed as
// blockchain uris and see if they match.
var uris = Object.keys(self._json.networks).filter(function(network) {
return network.indexOf("blockchain://") == 0;
});
var matches = uris.map(function(uri) {
return BlockchainUtils.matches.bind(BlockchainUtils, uri, self.web3.currentProvider);
});
Utils.parallel(matches, function(err, results) {
if (err) return reject(err);
for (var i = 0; i < results.length; i++) {
if (results[i]) {
self.setNetwork(uris[i]);
return accept();
}
}
// We found nothing. Set the network id to whatever the provider states.
self.setNetwork(network_id);
accept();
});
});
});
},
setNetwork: function(network_id) {
if (!network_id) return;
this.network_id = network_id + "";
},
// Overrides the deployed address to null.
// You must call this explicitly so you don't inadvertently do this otherwise.
resetAddress: function() {
delete this.network.address;
},
link: function(name, address) {
var self = this;
if (typeof name == "function") {
var contract = name;
if (contract.isDeployed() == false) {
throw new Error("Cannot link contract without an address.");
}
this.link(contract.contract_name, contract.address);
// Merge events so this contract knows about library's events
Object.keys(contract.events).forEach(function(topic) {
self.network.events[topic] = contract.events[topic];
});
return;
}
if (typeof name == "object") {
var obj = name;
Object.keys(obj).forEach(function(name) {
var a = obj[name];
self.link(name, a);
});
return;
}
if (this._json.networks[this.network_id] == null) {
this._json.networks[this.network_id] = {
events: {},
links: {}
};
}
this.network.links[name] = address;
},
clone: function(options) {
var self = this;
var temp = function TruffleContract() {
this.constructor = temp;
return Contract.apply(this, arguments);
};
var json = options;
var network_id;
if (typeof options != "object") {
json = self._json;
network_id = options;
options = {};
}
temp.prototype = Object.create(self.prototype);
temp._static_methods = this._static_methods;
temp._properties = this._properties;
temp._property_values = {};
temp._json = json || {};
Utils.bootstrap(temp);
temp.web3 = new Web3();
temp.class_defaults = temp.prototype.defaults || {};
if (network_id) {
temp.setNetwork(network_id);
}
// Copy over custom options
Object.keys(options).forEach(function(key) {
if (key.indexOf("x-") != 0) return;
temp[key] = options[key];
});
return temp;
},
addProp: function(key, fn) {
var self = this;
var getter = function() {
if (fn.get != null) {
return fn.get.call(self);
}
return self._property_values[key] || fn.call(self);
}
var setter = function(val) {
if (fn.set != null) {
fn.set.call(self, val);
return;
}
// If there's not a setter, then the property is immutable.
throw new Error(key + " property is immutable");
};
var definition = {};
definition.enumerable = false;
definition.configurable = false;
definition.get = getter;
definition.set = setter;
Object.defineProperty(this, key, definition);
},
toJSON: function() {
return this._json;
}
};
// Getter functions are scoped to Contract object.
Contract._properties = {
contract_name: {
get: function() {
return this._json.contract_name;
},
set: function(val) {
this._json.contract_name = val;
}
},
abi: {
get: function() {
return this._json.abi;
},
set: function(val) {
this._json.abi = val;
}
},
network: function() {
var network_id = this.network_id;
if (network_id == null) {
throw new Error(this.contract_name + " has no network id set, cannot lookup artifact data. Either set the network manually using " + this.contract_name + ".setNetwork(), run " + this.contract_name + ".detectNetwork(), or use new(), at() or deployed() as a thenable which will detect the network automatically.");
}
// TODO: this might be bad; setting a value on a get.
if (this._json.networks[network_id] == null) {
throw new Error(this.contract_name + " has no network configuration for its current network id (" + network_id + ").");
}
return this._json.networks[network_id];
},
networks: function() {
return this._json.networks;
},
address: {
get: function() {
var address = this.network.address;
if (address == null) {
throw new Error("Cannot find deployed address: " + this.contract_name + " not deployed or address not set.");
}
return address;
},
set: function(val) {
if (val == null) {
throw new Error("Cannot set deployed address; malformed value: " + val);
}
var network_id = this.network_id;
if (network_id == null) {
throw new Error(this.contract_name + " has no network id set, cannot lookup artifact data. Either set the network manually using " + this.contract_name + ".setNetwork(), run " + this.contract_name + ".detectNetwork(), or use new(), at() or deployed() as a thenable which will detect the network automatically.");
}
// Create a network if we don't have one.
if (this._json.networks[network_id] == null) {
this._json.networks[network_id] = {
events: {},
links: {}
};
}
// Finally, set the address.
this.network.address = val;
}
},
links: function() {
if (this._json.networks[this.network_id] == null) {
return {};
}
return this.network.links || {};
},
events: function() {
// helper web3; not used for provider
var web3 = new Web3();
var events;
if (this._json.networks[this.network_id] == null) {
events = {};
} else {
events = this.network.events || {};
}
// Merge abi events with whatever's returned.
var abi = this.abi;
abi.forEach(function(item) {
if (item.type != "event") return;
var signature = item.name + "(";
item.inputs.forEach(function(input, index) {
signature += input.type;
if (index < item.inputs.length - 1) {
signature += ",";
}
});
signature += ")";
var topic = web3.sha3(signature);
events[topic] = item;
});
return events;
},
binary: function() {
var self = this;
var binary = this.unlinked_binary;
Object.keys(this.links).forEach(function(library_name) {
var library_address = self.links[library_name];
var regex = new RegExp("__" + library_name + "_+", "g");
binary = binary.replace(regex, library_address.replace("0x", ""));
});
return binary;
},
unlinked_binary: {
get: function() {
return this._json.unlinked_binary;
},
set: function(val) {
// TODO: Ensure 0x prefix.
this._json.unlinked_binary = val;
}
},
schema_version: function() {
return this._json.schema_version;
},
updated_at: function() {
try {
return this.network.updated_at || this._json.updated_at;
} catch (e) {
return this._json.updated_at;
}
}
};
Utils.bootstrap(Contract);
module.exports = Contract;
return Contract;
})(module || {});