-
Notifications
You must be signed in to change notification settings - Fork 2
/
Transaction.js
603 lines (569 loc) · 16.7 KB
/
Transaction.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
/*!
* @dispatchlabs/dispatch-js <https://github.com/dispatchlabs/disnode_sdk>
*
* Copyright © 2018, [Dispatch Labs](http://dispatchlabs.io).
* Released under the LGPL v3 License.
*/
'use strict';
const assert = require('./../assert');
const messages = require('./../messages.json');
const Network = require('./Network');
const secp256k1 = require('secp256k1');
const keccak = require('keccak');
const solc = require('solc');
const bigInt = require('big-integer');
function numberToBuffer(value) {
let bytes = [0, 0, 0, 0, 0, 0, 0, 0],
i = 0;
for (; i < bytes.length; i++) {
const byte = value & 0xff;
bytes[i] = byte;
value = (value - byte) / 256;
}
return new Buffer.from(bytes);
}
/**
* Transaction constructor. Create an instance of a transaction, which can then be sent to a delegate.
*
* ```js
* // Create a new transaction
* let account = new Dispatch.Account().init();
* let tx = new Dispatch.Transaction({from: account});
* ```
*
* @name constructor
* @constructor
* @returns {Object} instance of `Transaction`
* @api public
*/
const Transaction = module.exports = class Transaction {
constructor(data) {
// Object argument is a full transaction
if (Object.prototype.toString.call(data) === '[object Object]') {
this.type = data.type !== undefined ? data.type : 0; // default to token transfer
this.from = data.from;
this.to = data.to || '';
this.value = data.value;
this.time = data.time !== undefined ? data.time : new Date();
this.code = data.code;
this.abi = data.abi;
this.method = data.method;
this.params = data.params;
this.hash = data.hash;
this.signature = data.signature;
this.address = data.address;
this.gossip = data.gossip;
this._id = data.id;
this.hertz = data.hertz;
// String argument is assumed to be a hash
} else if (Object.prototype.toString.call(data) === '[object String]') {
this.hash = data;
}
}
set type(type) {
if (type !== undefined) {
assert.isNumber(type, messages.TRANSACTION_TYPE_ISNUMBERINRANGE);
assert.isNumberInRange(type, 0, 3, messages.TRANSACTION_TYPE_ISNUMBERINRANGE);
this._type = type;
}
}
get type() {
return this._type || 0;
}
get typeBuffer() {
return new Buffer.from(('0' + this.type).slice(-2), 'hex');
}
set from(from) {
if (from !== undefined) {
assert.isAccountable(from, messages.TRANSACTION_FROM_ISACCOUNTABLE);
if (from.constructor.name !== 'Account') {
this._from = new Account(from);
} else {
this._from = from;
}
}
}
get from() {
return this._from;
}
set to(to) {
if (to !== undefined) {
assert.isAccountable(to, messages.TRANSACTION_TO_ISACCOUNTABLE);
if (to.constructor.name !== 'Account') {
this._to = new Account(to);
} else {
this._to = to;
}
}
}
get to() {
if (this._to === undefined) {
this._to = new Account();
}
return this._to;
}
set value(value) {
value = bigInt(value);
assert.isGTEZero(value, messages.TRANSACTION_VALUE_ISPOSITIVENUMBER);
this._value = value;
}
get value() {
return this._value;
}
set hertz(hertz) {
hertz = bigInt(hertz);
assert.isGTEZero(hertz, messages.TRANSACTION_HERTZ_ISPOSITIVENUMBER);
this._hertz = hertz;
}
get hertz() {
return this._hertz;
}
set time(time) {
try {
time = new Date(time);
if (isNaN(time)) {
throw Error();
}
} catch(e) {
throw TypeError(messages.TRANSACTION_TIME_ISDATE);
}
this._time = time;
}
get time() {
return this._time;
}
get timeBuffer() {
return numberToBuffer(+(this._time));
}
set code(code) {
if (code !== undefined) {
assert.isString(code, messages.TRANSACTION_CODE_ISSTRING);
assert.isLengthGTZero(code, messages.TRANSACTION_CODE_ISSTRING);
this._code = code;
}
}
get code() {
return this._code || '';
}
set abi(abi) {
if (abi !== undefined) {
if (Object.prototype.toString.call(abi) === '[object String]') {
try {
abi = JSON.parse(abi);
} catch (e) {
abi = undefined;
}
}
if (abi !== undefined) {
assert.isArray(abi, messages.TRANSACTION_ABI_ISARRAY);
this._abi = abi;
}
}
}
get abi() {
return this._abi || [];
}
get abiString() {
if (this.type === 2) {
return new Buffer.from(JSON.stringify(this.abi)).toString('hex');
}
return JSON.stringify(this.abi);
}
set method(method) {
if (method !== undefined) {
assert.isString(method, messages.TRANSACTION_METHOD_ISSTRING);
this._method = method;
}
}
get method() {
return this._method || '';
}
set params(params) {
if (params !== undefined) {
if (Object.prototype.toString.call(params) === '[object String]') {
params = JSON.parse(params);
}
assert.isArray(params, messages.TRANSACTION_PARAMS_ISARRAY);
this._params = params;
}
}
get params() {
return this._params || [];
}
set hash(hash) {
if (hash !== undefined) {
assert.isString(hash, messages.TRANSACTION_HASH_ISSTRING);
this._hash = hash;
}
}
get hash() {
if (this._hash !== undefined) {
return this._hash;
}
if (this.from !== undefined) {
assert.isString(this.from.address, messages.TRANSACTION_FROMACCOUNT_ISVALID);
this._hash = keccak('keccak256').update(Buffer.concat([
this.typeBuffer,
new Buffer.from(this.from.address, 'hex'),
new Buffer.from(this.to.address !== null ? this.to.address : '', 'hex'),
new Buffer.from(this.value.toString()),
new Buffer.from(this.code, 'hex'),
new Buffer.from(this.method),
new Buffer.from(JSON.stringify(this.params)),
this.timeBuffer
])).digest().toString('hex');
}
return this._hash;
}
get id() {
return this._id !== undefined ? this._id : this.hash;
}
set signature(signature) {
if (signature !== undefined) {
assert.isString(signature, messages.TRANSACTION_SIGNATURE_ISSTRING);
this._signature = signature;
}
}
get signature() {
if (this._signature !== undefined) {
return this._signature;
}
if (this.from !== undefined && this.from.privateKey !== undefined) {
const sig = secp256k1.sign(Buffer.from(this.hash, 'hex'), Buffer.from(this.from.privateKey, 'hex'));
const signatureBytes = new Uint8Array(65);
for (let i = 0; i < 64; i++) {
signatureBytes[i] = sig.signature[i];
}
signatureBytes[64] = sig.recovery;
this._signature = new Buffer.from(signatureBytes).toString('hex');
}
return this._signature;
}
set address(address) {
if (address !== undefined) {
assert.isString(address, messages.TRANSACTION_ADDRESS_ISSTRING);
this._address = address;
}
}
get address() {
if (this._address === undefined && this.signature !== undefined) {
// TODO - Fix this...
// const publicKey = secp256k1.recover(Buffer.from(this.hash, 'hex'), Buffer.from(this.signature, 'hex').slice(0,64), 0);
// const hash = keccak('keccak256').update(publicKey.slice(1)).digest();
// this._address = hash.slice(12,32).toString('hex');
}
return this._address;
}
toJSON() {
return {
hash: this.hash,
type: this.type,
from: this.from !== undefined ? this.from.address : null,
to: this.to !== undefined ? this.to.address : null,
value: this.value.toString(),
code: this.code,
abi: this.abiString,
method: this.method,
params: JSON.stringify(this.params),
time: +(this.time),
signature: this.signature,
hertz: this.hertz.toString(),
fromName: this.from !== undefined ? this.from.name : null,
toName: this.to !== undefined ? this.to.name : null,
address: this.address,
gossip: this.gossip
};
}
toString() {
return JSON.stringify(this);
}
inspect() {
return this.toString();
}
/**
* Sends the transaction to a delegate.
*
* ```js
* let account = new Dispatch.Account().init();
* let tx = new Dispatch.Transaction({from: account});
* tx.send()
* .then((result) => {
* console.log(result);
* })
* .catch((err) => {
* console.error(err);
* });
* ```
*
* @name send
* @returns {Promise} Promise that will return the result of the Delegate request.
* @api public
*/
send() {
if (!this._sendCall) {
assert.exists(this.from, messages.TRANSACTION_FROM_ISACCOUNTABLE);
let network = new Network();
this._sendCall = network.postToDelegate(
{
path: '/' + network.config.apiVersion + network.config.routes.transactionSend
},
this
);
this._sendCall.then((data) => {
this._id = data.id;
process.env.DEBUG ? console.log('Transaction.send result: ' + JSON.stringify(data)) : null;
}, (err) => {
this._sendError = err;
process.env.DEBUG ? console.log('Transaction.send error: ' + err) : null;
});
}
return this._sendCall;
}
/**
* Requests the current status of the transaction from a delegate.
*
* ```js
* let account = new Dispatch.Account().init();
* let tx = new Dispatch.Transaction({from: account});
* tx.send();
* tx.status()
* .then((result) => {
* console.log(result);
* })
* .catch((err) => {
* console.error(err);
* });
* ```
*
* @name status
* @returns {Promise} Promise that will return the result of the status check.
* @api public
*/
status() {
if (!this._statusCall) {
this._statusCall = new Promise((resolve, reject) => {
let network = new Network();
const getStatus = () => {
network.getFromDelegate(
{
path: '/' + network.config.apiVersion + network.config.routes.transactionStatus + this.id
}
).then((d) => {
if (d.status === undefined || d.status !== 'Ok') {
reject(d);
} else {
if (d.data && d.data.receipt && d.data.receipt.status === 'Ok') {
if (d.data.receipt.contractAddress) {
this.address = d.data.receipt.contractAddress;
}
}
if (d.data.abi) {
this.abi = d.data.abi;
}
if (d.data.gossip) {
this.gossip = d.data.gossip;
}
resolve(d.data);
}
delete this._statusCall;
}, (e) => {
reject(e);
delete this._statusCall;
});
}
if (this._sendCall) {
this._sendCall.then((data) => {
getStatus();
}, (e) => {
reject(e);
delete this._statusCall;
});
} else if (this._sendError) {
reject(this._sendError);
} else {
getStatus();
}
});
}
return this._statusCall;
}
/**
* Waits until the status of the transaction matches the value provided, then resolves. Rejects after 5 seconds or when the transaction hits a non-matching final state.
*
* ```js
* let account = new Dispatch.Account().init();
* let tx = new Dispatch.Transaction({from: account});
* tx.send();
* tx.whenStatusEquals('Ok')
* .then((result) => {
* console.log(result);
* })
* .catch((err) => {
* console.error(err);
* });
* ```
*
* @name whenStatusEquals
* @param {string} status - Desired status for the transaction to acheive.
* @returns {Promise} Promise that will return the result of the status check. If a timeout occured, the returned data will be the latest known state along with a key of `SDKTimeout: true`.
* @api public
*/
whenStatusEquals(status) {
const self = this;
return new Promise((resolve, reject) => {
const maxTries = 20;
let currentTry = 0,
currentDelay = 400,
last;
function getStatus() {
currentTry++;
if (currentTry > maxTries) {
if (last !== undefined) {
last.SDKTimeout = true;
}
reject(last);
return;
}
self.status()
.then((data) => {
if (data.receipt.status === status) {
resolve(data);
} else {
if (['Pending','NotFound'].indexOf(data.receipt.status) > -1) {
last = data;
setTimeout(getStatus, currentDelay);
currentDelay += 100;
} else {
reject(data);
}
}
})
.catch((e) => {
if (['NotFound'].indexOf(e.status) > -1) {
last = e;
setTimeout(getStatus, currentDelay);
currentDelay += 100;
} else {
reject(e);
}
});
}
getStatus();
});
}
/**
* @typedef {Object} compiledContract
* @property {string} contract The name of the contract.
* @property {string} bytecode The bytecode of the contract.
* @property {Array} abi The ABI structure for the contract.
*/
/**
* @typedef {Object} compiledSource
* @property {compiledContract[]} contracts The compiled contracts from the source provided.
* @property {Object[]} errors Any fatal errors thrown during compilation.
* @property {Object[]} warnings Any warnings thrown during compilation.
*/
/**
* Static method to compile Solidity code directly.
*
* ```js
* let account = new Dispatch.Account().init();
* let compiled = Dispatch.Transaction.compileSource('contract x { function g() { } }');
* if (compiled.errors.length > 0) {
* // Errors are fatal
* console.error(compiled.errors);
* } else {
* // Warnings are non-fatal
* if (compiled.warnings.length > 0) {
* console.log(compiled.warnings);
* }
* // compiled.contracts contains the name, bytecode, and abi for each contract contained within the source
* const contract = account.createContract(compiled.contracts[0].bytecode, compiled.contracts[0].abi);
* }
* ```
*
* @name compileSource
* @memberOf Transaction
* @param {string} source - Solidity source code containing one or more contracts.
* @returns {compiledSource} Compiled output JSON.
* @api public
*/
static compileSource(source) {
if (solc && solc.compileStandardWrapper) {
assert.isString(source, messages.TRANSACTION_COMPILESOURCE_ISSTRING);
assert.isLengthGTZero(source, messages.TRANSACTION_COMPILESOURCE_ISSTRING);
let input = {
language: 'Solidity',
sources: {
source: {
content: source
}
}
};
let compiled = this.compile(input);
let ret = {
contracts: [],
errors: [],
warnings: []
};
if (compiled.contracts !== undefined && compiled.contracts.source !== undefined) {
Object.keys(compiled.contracts.source).forEach((k) => {
ret.contracts.push({
contract: k,
bytecode: compiled.contracts.source[k].evm.bytecode.object,
abi: compiled.contracts.source[k].abi
});
});
}
(compiled.errors || []).forEach((e) => {
if (e.severity === 'warning') {
ret.warnings.push(e);
} else {
ret.errors.push(e);
}
});
return ret;
} else {
throw new Error('Contract compilation is not available in the browser.');
}
}
/**
* Static method to compile complex Solidity JSON structures.
*
* ```js
* let compiled = Dispatch.Transaction.compile({language: 'Solidity', sources: { source: { content: 'contract x { function g() { } }' }}});
* ```
*
* @name compile
* @memberOf Transaction
* @param {object} input - Full Solidity JSON structure. See [Compiler Input and Output JSON Description](https://solidity.readthedocs.io/en/develop/using-the-compiler.html#compiler-input-and-output-json-description).
* @returns {object} Compiled output JSON.
* @api public
*/
static compile(input, findImports) {
if (solc && solc.compileStandardWrapper) {
assert.isObject(input, messages.TRANSACTION_COMPILE_ISOBJECT);
const find = (path) => {
if (findImports === undefined) {
return { error: 'Files not supported' };
} else {
return findImports(path);
}
};
input.language = 'Solidity';
input.settings = Object.assign({
optimizer: { enabled: true },
outputSelection: {
'*': {
'*': ['abi', 'evm.bytecode.object']
}
}
}, input.settings || {});
const ret = solc.compileStandardWrapper(JSON.stringify(input), find);
return JSON.parse(ret);
} else {
throw new Error('Contract compilation is not available in the browser.');
}
}
};
const Account = require('./Account');