forked from gitter-badger/etheropt.github.io
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathutility.js
588 lines (543 loc) · 17.3 KB
/
utility.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
var config = (typeof(global.config) == 'undefined' && typeof(config) == 'undefined') ? require('./config.js') : global.config;
var fs = require('fs');
var request = require('request');
var async = (typeof(window) === 'undefined') ? require('async') : require('async/dist/async.min.js');
var Web3 = require('web3');
var SolidityFunction = require('web3/lib/web3/function.js');
var coder = require('web3/lib/solidity/coder.js');
var utils = require('web3/lib/utils/utils.js');
var sha3 = require('web3/lib/utils/sha3.js');
var Tx = require('ethereumjs-tx');
var keythereum = require('keythereum');
var ethUtil = require('ethereumjs-util');
var BigNumber = require('bignumber.js');
function roundToNearest(numToRound, numToRoundTo) {
numToRoundTo = 1 / (numToRoundTo);
return Math.round(numToRound * numToRoundTo) / numToRoundTo;
}
function weiToEth(wei) {
return (wei/1000000000000000000).toFixed(3);
}
function ethToWei(eth) {
return eth*1000000000000000000;
}
function roundTo(numToRound, numToRoundTo) {
return numToRound.toFixed(numToRoundTo);
}
function readFile(filename, callback) {
if (callback) {
try {
if (typeof(window) === 'undefined') {
fs.readFile(filename,{ encoding: 'utf8' }, function(err, data) {
if (callback) {
callback(data);
}
});
} else {
request.get(config.home_url+"/"+filename, function(err, httpResponse, body){
callback(body);
});
}
} catch (err) {
callback(undefined);
}
} else {
try {
return fs.readFileSync(filename,{ encoding: 'utf8' });
} catch (err) {
return undefined;
}
}
}
function writeFile(filename, data) {
fs.writeFile(filename, data, function(err) {
if(err) {
console.error("Could not write file: %s", err);
}
});
}
function proxyGetBalance(web3, address, callback) {
function proxy(){
var url = 'http://'+(config.eth_testnet ? 'testnet' : 'api')+'.etherscan.io/api?module=account&action=balance&address='+address+'&tag=latest';
request.get(url, function(err, httpResponse, body){
if (!err) {
result = JSON.parse(body);
callback(result['result']);
}
});
}
try {
if (web3.currentProvider) {
callback(web3.eth.getBalance(address));
} else {
proxy();
}
} catch(err) {
proxy();
}
}
function testCall(web3, contract, address, functionName, args, callback) {
var options = {};
options.data = contract[functionName].getData.apply(null, args);
options.to = address;
web3.eth.call(options, function(err, result) {
if (!err) {
var functionAbi = contract.abi.find(function(element, index, array) {return element.name==functionName});
var solidityFunction = new SolidityFunction(web3._eth, functionAbi, address);
callback(err, solidityFunction.unpackOutput(result));
} else {
callback(err, result);
}
});
}
function proxyCall(web3, contract, address, functionName, args, callback) {
function proxy() {
var web3 = new Web3();
var data = contract[functionName].getData.apply(null, args);
var result = undefined;
var url = 'http://'+(config.eth_testnet ? 'testnet' : 'api')+'.etherscan.io/api?module=proxy&action=eth_call&to='+address+'&data='+data;
request.get(url, function(err, httpResponse, body){
if (!err) {
result = JSON.parse(body);
var functionAbi = contract.abi.find(function(element, index, array) {return element.name==functionName});
var solidityFunction = new SolidityFunction(web3._eth, functionAbi, address);
callback(solidityFunction.unpackOutput(result['result']));
}
});
}
try {
if (web3.currentProvider) {
callback(contract[functionName].call.apply(null, args));
} else {
proxy();
}
} catch(err) {
proxy();
}
}
function testSend(web3, contract, address, functionName, args, fromAddress, privateKey, nonce, callback) {
args = Array.prototype.slice.call(args).filter(function (a) {return a !== undefined; });
var options = {};
var functionAbi = contract.abi.find(function(element, index, array) {return element.name==functionName});
var inputTypes = functionAbi.inputs.map(function(x) {return x.type});
if (typeof(args[args.length-1])=='object' && args[args.length-1].gas!=undefined) {
args[args.length-1].gasPrice = 50000000000;
args[args.length-1].gasLimit = args[args.length-1].gas;
delete args[args.length-1].gas;
}
if (args.length > inputTypes.length && utils.isObject(args[args.length -1])) {
options = args[args.length - 1];
}
var typeName = inputTypes.join();
options.data = '0x' + sha3(functionName+'('+typeName+')').slice(0, 8) + coder.encodeParams(inputTypes, args);
options.to = address;
options.from = fromAddress;
web3.eth.sendTransaction(options, function(err, result) {
callback(err, result);
});
}
function proxySend(web3, contract, address, functionName, args, fromAddress, privateKey, nonce, callback) {
function proxy(){
if (privateKey && privateKey.substring(0,2)=='0x') {
privateKey = privateKey.substring(2,privateKey.length);
}
var web3 = new Web3();
args = Array.prototype.slice.call(args).filter(function (a) {return a !== undefined; });
var options = {};
var functionAbi = contract.abi.find(function(element, index, array) {return element.name==functionName});
var inputTypes = functionAbi.inputs.map(function(x) {return x.type});
if (typeof(args[args.length-1])=='object' && args[args.length-1].gas!=undefined) {
args[args.length-1].gasPrice = 50000000000;
args[args.length-1].gasLimit = args[args.length-1].gas;
delete args[args.length-1].gas;
}
if (args.length > inputTypes.length && utils.isObject(args[args.length -1])) {
options = args[args.length - 1];
}
if (nonce==undefined) {
var url = 'http://'+(config.eth_testnet ? 'testnet' : 'api')+'.etherscan.io/api?module=account&action=txlist&address='+fromAddress+'&sort=desc';
request.get(url, function(err, httpResponse, body){
if (!err) {
var result = JSON.parse(body);
try {
for (var i=0; i<result['result'].length; i++) {
if (nonce==undefined && result['result'][i]['from']==fromAddress) {
nonce = parseInt(result['result'][i]['nonce']);
}
}
if (nonce==undefined) {
nonce = -1;
}
} catch (err) {
nonce = -1;
}
}
});
}
async.whilst(
function () { return nonce==undefined; },
function (callback) {
setTimeout(function () {
callback(null);
}, 1000);
},
function (err) {
if (!err) {
if (nonce==undefined || nonce<0){
nonce = config.eth_testnet ? 1048576 : 0; //initial nonce is 2^20 for testnet, 0 for livenet
} else {
nonce = nonce + 1;
}
console.log("Nonce:", nonce);
options.nonce = nonce;
options.to = address;
var typeName = inputTypes.join();
options.data = '0x' + sha3(functionName+'('+typeName+')').slice(0, 8) + coder.encodeParams(inputTypes, args);
var tx = new Tx(options);
tx.sign(new Buffer(privateKey, 'hex'));
var serializedTx = tx.serialize().toString('hex');
var result = undefined;
var url = 'http://'+(config.eth_testnet ? 'testnet' : 'api')+'.etherscan.io/api?module=proxy&action=eth_sendRawTransaction&hex='+serializedTx;
request.get(url, function(err, httpResponse, body){
if (!err) {
result = JSON.parse(body);
if (result['result']) {
callback([result['result'], nonce]);
} else if (result['error']) {
console.log(result['error']['message']);
callback([undefined, nonce]);
}
} else {
console.log(err);
callback([undefined, nonce]);
}
});
}
}
);
}
try {
if (web3.currentProvider) {
web3.eth.defaultAccount = fromAddress;
callback([contract[functionName].sendTransaction.apply(null, args),0]);
} else {
proxy();
}
} catch(err) {
console.log(err);
console.log('Attempting to send transaction through the proxy.');
proxy();
}
}
function blockNumber(web3, callback) {
function proxy() {
var url = 'http://'+(config.eth_testnet ? 'testnet' : 'api')+'.etherscan.io/api?module=proxy&action=eth_blockNumber';
request.get(url, function(err, httpResponse, body){
if (!err) {
var result = JSON.parse(body);
callback(Number(hex_to_dec(result['result'])));
}
});
}
if (web3.currentProvider) {
web3.eth.getBlockNumber(function(err, blockNumber){
if (!err) {
callback(Number(blockNumber));
} else {
proxy();
}
});
} else {
proxy();
}
}
function sign(web3, address, value, privateKey, callback) {
if (typeof(privateKey) != 'undefined') {
if (privateKey.substring(0,2)=='0x') privateKey = privateKey.substring(2,privateKey.length);
if (value.substring(0,2)=='0x') value = value.substring(2,value.length);
try {
var sig = ethUtil.ecsign(new Buffer(value, 'hex'), new Buffer(privateKey, 'hex'));
var r = '0x'+sig.r.toString('hex');
var s = '0x'+sig.s.toString('hex');
var v = sig.v;
var result = {r: r, s: s, v: v};
callback(result);
} catch (err) {
callback(undefined);
}
} else {
web3.eth.sign(address, value, function(err, sig) {
try {
var r = sig.slice(0, 66);
var s = '0x' + sig.slice(66, 130);
var v = web3.toDecimal('0x' + sig.slice(130, 132));
if (v!=27 && v!=28) v+=27;
callback({r: r, s: s, v: v});
} catch (err) {
console.log(err);
callback(undefined);
}
});
}
}
function verify(web3, address, v, r, s, value, callback) {
if (r.substring(0,2)=='0x') r=r.substring(2,r.length);
if (s.substring(0,2)=='0x') s=s.substring(2,s.length);
if (value.substring(0,2)=='0x') value=value.substring(2,value.length);
var pubKey = ethUtil.ecrecover(new Buffer(value, 'hex'), Number(v), new Buffer(r, 'hex'), new Buffer(s, 'hex'));
var result = address == '0x'+ethUtil.pubToAddress(new Buffer(pubKey, 'hex')).toString('hex');
if (callback) {
callback(result);
} else {
return result;
}
}
function createAddress() {
var dk = keythereum.create();
var pk = dk.privateKey;
var addr = ethUtil.privateToAddress(pk);
return [addr, pk];
}
function verifyPrivateKey(addr, privateKey) {
if (privateKey && privateKey.substring(0,2)!='0x') {
privateKey = '0x'+privateKey;
}
return addr == '0x'+ethUtil.privateToAddress(privateKey).toString('hex');
}
function diffs(data) {
var result = [];
for (var i=1; i<data.length; i++) {
result.push(data[i]-data[i-1]);
}
return result;
}
function rets(data) {
var result = [];
for (var i=1; i<data.length; i++) {
result.push((data[i]-data[i-1])/data[i-1]);
}
return result;
}
function mean(data){
return data.reduce(function(sum, value){ return sum + value; }, 0) / data.length;
}
function std_zero(data){
return Math.sqrt(mean(data.map(function(value){ return Math.pow(value, 2) })));
}
function std(data){
var avg = mean(data);
return Math.sqrt(mean(data.map(function(value){ return Math.pow(value - avg, 2) })));
}
function random_hex(n) {
var text = "";
var possible = "ABCDEF0123456789";
for( var i=0; i < n; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function zero_pad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
function dec_to_hex(decStr, length) {
if (typeof(length)==='undefined') length = 32;
if (decStr < 0) {
// return convert_base((Math.pow(2, length) + decStr).toString(), 10, 16);
return (new BigNumber(2)).pow(length).add(new BigNumber(decStr)).toString(16);
} else {
return convert_base(decStr.toString(), 10, 16);
}
}
function hex_to_dec(hexStr, length) { //length implies this is a two's complement number
if (hexStr.substring(0, 2) === '0x') hexStr = hexStr.substring(2);
hexStr = hexStr.toLowerCase();
if (typeof(length)==='undefined'){
return convert_base(hexStr, 16, 10);
} else {
var max = Math.pow(2, length);
var answer = convert_base(hexStr, 16, 10);
if (answer>max/2) {
answer -= max;
}
return answer;
}
}
function pack(data, lengths) {
packed = "";
for (var i=0; i<lengths.length; i++) {
packed += zero_pad(dec_to_hex(data[i], lengths[i]), lengths[i]/4);
}
return packed;
}
function unpack(str, lengths) {
var data = [];
var length = 0;
for (var i=0; i<lengths.length; i++) {
data[i] = parseInt(hex_to_dec(str.substr(length,lengths[i]/4), lengths[i]));
length += lengths[i]/4;
}
return data;
}
function convert_base(str, fromBase, toBase) {
var digits = parse_to_digits_array(str, fromBase);
if (digits === null) return null;
var outArray = [];
var power = [1];
for (var i = 0; i < digits.length; i++) {
if (digits[i]) {
outArray = add(outArray, multiply_by_number(digits[i], power, toBase), toBase);
}
power = multiply_by_number(fromBase, power, toBase);
}
var out = '';
for (var i = outArray.length - 1; i >= 0; i--) {
out += outArray[i].toString(toBase);
}
return out;
}
function parse_to_digits_array(str, base) {
var digits = str.split('');
var ary = [];
for (var i = digits.length - 1; i >= 0; i--) {
var n = parseInt(digits[i], base);
if (isNaN(n)) return null;
ary.push(n);
}
return ary;
}
function add(x, y, base) {
var z = [];
var n = Math.max(x.length, y.length);
var carry = 0;
var i = 0;
while (i < n || carry) {
var xi = i < x.length ? x[i] : 0;
var yi = i < y.length ? y[i] : 0;
var zi = carry + xi + yi;
z.push(zi % base);
carry = Math.floor(zi / base);
i++;
}
return z;
}
function multiply_by_number(num, x, base) {
if (num < 0) return null;
if (num == 0) return [];
var result = [];
var power = x;
while (true) {
if (num & 1) {
result = add(result, power, base);
}
num = num >> 1;
if (num === 0) break;
power = add(power, power, base);
}
return result;
}
if (!Array.prototype.find) {
Array.prototype.find = function(predicate) {
if (this === null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
}
if (typeof Object.assign != 'function') {
(function () {
Object.assign = function (target) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
})();
}
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
Array.prototype.min = function() {
return Math.min.apply(null, this);
};
Array.prototype.equals = function(b) {
if (this === b) return true;
if (this == null || b == null) return false;
if (this.length != b.length) return false;
// If you don't care about the order of the elements inside
// the array, you should sort both arrays here.
for (var i = 0; i < this.length; ++i) {
if (this[i] !== b[i]) return false;
}
return true;
}
exports.add = add;
exports.multiply_by_number = multiply_by_number;
exports.parse_to_digits_array = parse_to_digits_array;
exports.convert_base = convert_base;
exports.zero_pad = zero_pad;
exports.hex_to_dec = hex_to_dec;
exports.dec_to_hex = dec_to_hex;
exports.pack = pack;
exports.unpack = unpack;
exports.getRandomInt = getRandomInt;
exports.random_hex = random_hex;
exports.rets = rets;
exports.diffs = diffs;
exports.std = std;
exports.std_zero = std_zero;
exports.mean = mean;
exports.proxyGetBalance = proxyGetBalance;
exports.proxySend = proxySend;
exports.proxyCall = proxyCall;
exports.testSend = testSend;
exports.testCall = testCall;
exports.blockNumber = blockNumber;
exports.sign = sign;
exports.verify = verify;
exports.createAddress = createAddress;
exports.verifyPrivateKey = verifyPrivateKey;
exports.readFile = readFile;
exports.writeFile = writeFile;
exports.roundTo = roundTo;
exports.weiToEth = weiToEth;
exports.ethToWei = ethToWei;
exports.roundToNearest = roundToNearest;