-
Notifications
You must be signed in to change notification settings - Fork 2
/
Account.js
452 lines (429 loc) · 13.6 KB
/
Account.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
/*!
* @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 { randomBytes } = require('crypto');
const bigInt = require('big-integer');
/**
* Account constructor. Create an instance of an account, which can then be used to interact with the network.
*
* ```js
* // Create an empty account
* let account = new Dispatch.Account().init();
* ```
*
* ```js
* // Create an account using a known address
* let account = new Dispatch.Account('fa61c18114f8ff8aafbeb5d32e1b108e3f6cf30d');
* ```
*
* ```js
* // Create an account using a private key. The address and public key are automatically added
* let account = new Dispatch.Account({
* name: 'MyAccount',
* privateKey: '472ba91402425b58a2eebf932812f20c6d7f6297bba1f83d9a58116ae6512d9e'
* });
* ```
*
* @name constructor
* @constructor
* @returns {Object} instance of `Account`
* @api public
*/
const Account = module.exports = class Account {
constructor(data) {
// Object argument is a full account
if (Object.prototype.toString.call(data) === '[object Object]') {
this.name = data.name;
this.privateKey = data.privateKey;
this.balance = data.balance;
this.availableHertz = data.availableHertz;
this.address = data.address;
// String argument is assumed to be an address
} else if (Object.prototype.toString.call(data) === '[object String]') {
this.address = data;
}
}
set name(name) {
if (name !== undefined) {
assert.isString(name, messages.ACCOUNT_NAME_ISSTRING);
assert.isLengthGTZero(name, messages.ACCOUNT_NAME_ISSTRING);
this._name = name;
}
}
get name() {
return this._name;
}
set privateKey(privateKey) {
if (privateKey !== undefined) {
assert.isString(privateKey, messages.ACCOUNT_PRIVATEKEY_ISSTRING);
assert.isLengthEqualTo(new Buffer.from(privateKey, 'hex'), 32, messages.ACCOUNT_PRIVATEKEY_ISSTRING);
this._privateKey = privateKey;
}
}
get privateKey() {
return this._privateKey;
}
set balance(balance) {
balance = bigInt(balance);
//assert.isGTEZero(balance, messages.ACCOUNT_BALANCE_ISGTEZERO);
this._balance = balance;
}
get balance() {
return bigInt(this._balance);
}
set availableHertz(availableHertz) {
this._availableHertz = bigInt(availableHertz);
}
get availableHertz() {
return bigInt(this._availableHertz);
}
set publicKey(publicKey) {
if (publicKey !== undefined) {
assert.isString(publicKey, messages.ACCOUNT_PUBLICKEY_ISSTRING);
assert.isLengthEqualTo(new Buffer.from(publicKey, 'hex'), 32, messages.ACCOUNT_PUBLICKEY_ISSTRING);
this._publicKey = publicKey;
}
}
get publicKey() {
if (this._publicKey !== undefined) {
return this._publicKey;
}
if (this._privateKey) {
this._publicKey = secp256k1.publicKeyCreate(new Buffer.from(this._privateKey, 'hex'), false).toString('hex');
return this._publicKey;
}
}
set address(address) {
if (address !== undefined) {
assert.isString(address, messages.ACCOUNT_ADDRESS_ISSTRING);
this._address = address;
}
}
get address() {
if (this._address !== undefined) {
return this._address;
}
if (this.publicKey) {
const hash = keccak('keccak256').update(new Buffer.from(this.publicKey, 'hex').slice(1)).digest();
this._address = hash.slice(12,32).toString('hex');
return this._address;
}
}
get abi() {
if (this.transaction !== undefined) {
return this.transaction.abi;
}
}
toJSON() {
return {
name: this.name,
address: this.address,
privateKey: this.privateKey,
publicKey: this.publicKey,
balance: this.balance.toString(),
availableHertz: this.availableHertz.toString(),
transaction: this.transaction,
created: this.created,
updated: this.updated
};
}
toString() {
return JSON.stringify(this);
}
inspect() {
return this.toString();
}
/**
* Refreshes the account balance and access info (created and updated dates) from a delegate.
*
* ```js
* let account = new Dispatch.Account('fa61c18114f8ff8aafbeb5d32e1b108e3f6cf30d');
* account.refresh()
* .then(() => {
* console.log(account);
* })
* .catch((err) => {
* console.error(err);
* });
* ```
*
* @name refresh
* @returns {Promise} Promise that will return the result of the Delegate request after updating account object.
* @api public
*/
refresh() {
assert.isString(this.address, messages.ACCOUNT_ADDRESS_ISSTRING);
if (!this._refreshCall) {
this._refreshCall = new Promise((resolve, reject) => {
const network = new Network();
network.getFromDelegate(
{
path: '/' + network.config.apiVersion + network.config.routes.accountStatus + this.address
}
).then((d) => {
if (d.status === 'Ok') {
this.balance = d.data.balance;
this.availableHertz = d.data.availableHertz;
this.created = new Date(d.data.created);
this.updated = new Date(d.data.updated);
if (d.data.transactionHash !== undefined) {
this.transaction = new Transaction(d.data.transactionHash);
this.transaction.status()
.then((tData) => {
resolve(d.data);
}, (err) => {
process.env.DEBUG ? console.log('Account.transaction.status() error: ' + err) : null;
resolve(d.data);
});
} else {
resolve(d.data);
}
} else {
reject(d);
}
delete this._refreshCall;
})
.catch((e) => {
reject(e);
delete this._refreshCall;
});
});
}
return this._refreshCall;
}
/**
* Generaes a new private key for the account object (replacing one if present).
*
* ```js
* let account = new Dispatch.Account();
* account.init();
* console.log(account);
* ```
*
* @name init
* @returns {Account} Returns the account object for use in chaining.
* @api public
*/
init() {
let privateKey;
do {
privateKey = randomBytes(32);
} while (!secp256k1.privateKeyVerify(privateKey));
this.privateKey = privateKey.toString('hex');
delete this._publicKey;
delete this._address;
delete this._balance;
delete this._availableHertz;
delete this.created;
delete this.updated;
return this;
}
/**
* Creates and sends a transaction that will transfer tokens from the source account, to the target account.
*
* ```js
* let account = new Dispatch.Account('fa61c18114f8ff8aafbeb5d32e1b108e3f6cf30d');
* // Send one (1) token
* let tx = account.sendTokens(new Dispatch.Account().init(), 1);
* ```
*
* @name sendTokens
* @param {string|Account} to - The address or Account to send the tokens to.
* @param {number} The number of Divitos to send. 1 Divvy = 100,000,000 Divitos
* @returns {Transaction} Returns a transaction which has already been sent.
* @api public
*/
sendTokens(to, value) {
assert.isAccountable(to, messages.TRANSACTION_TO_ISACCOUNTABLE);
value = bigInt(value);
assert.isPositiveNumber(value, messages.TRANSACTION_VALUE_ISPOSITIVENUMBER);
const tx = new Transaction({
from: this,
to: to,
value: value.toString(),
time: +(new Date())-10
});
tx.send()
.then((d) => {
})
.catch((e) => {
console.log("send() returned an error")
console.error(e);
});
return tx;
}
/**
* Creates and sends a transaction from the account that will create a new Smart Contract.
*
* ```js
* let account = new Dispatch.Account({
* name: 'MyAccount',
* privateKey: '472ba91402425b58a2eebf932812f20c6d7f6297bba1f83d9a58116ae6512d9e'
* });
* let compiled = Dispatch.Transaction.compileSource('contract x { function g() { } }');
* let contract = account.createContract(compiled.contracts[0].bytecode, compiled.contracts[0].abi, 5);
* ```
*
* @name createContract
* @param {string} code - Bytecode of a compiled contract.
* @param {string|array} code - The ABI of the contract.
* @returns {Transaction} Returns a transaction which has already been sent.
* @api public
*/
createContract(code, abi, value) {
assert.isString(code, messages.TRANSACTION_CODE_ISSTRING);
assert.isLengthGTZero(code, messages.TRANSACTION_CODE_ISSTRING);
assert.isArray(abi, messages.TRANSACTION_ABI_ISARRAY);
value = bigInt(value);
const tx = new Transaction({
type: 1,
from: this,
value: value.toString(),
code: code,
abi: abi,
time: +(new Date())-10
});
tx.send()
.then((d) => {
// console.log(d);
value !== undefined ? this._balance = this._balance.minus(value) : null;
})
.catch((e) => {
console.error(e);
});
return tx;
}
/* supports the old API name of executeContract; Now forwards functionality to executeWrite.
*
* @name executeContract
* @param {string|Account|Transaction} to - The address of an existing contract, an Account representing the contract, or the contract creation Transaction.
* @param {string} method - The method in the contract to call.
* @param {array} params - The parameters to use during the method call.
* @returns {Transaction} Returns a transaction which has already been sent.
* @api public
*/
executeContract(to, method, params, value) {
return executeWrite(to, method, params, value)
}
/**
* Creates and sends a transaction from the account that will execute a method on an existing Smart Contract, and be written to the ledger.
*
* ```js
* let account = new Dispatch.Account({
* name: 'MyAccount',
* privateKey: '472ba91402425b58a2eebf932812f20c6d7f6297bba1f83d9a58116ae6512d9e'
* });
* let compiled = Dispatch.Transaction.compileSource('contract x { function g() { } }');
* let contract = account.createContract(compiled.contracts[0].bytecode, compiled.contracts[0].abi, 5);
* contract.whenStatusEquals('Ok')
* .then(() => {
* account.executeWrite(contract, 'g', [], 5);
* })
* .catch((err) => {
* console.error(err);
* });
* ```
*
* @name executeWrite
* @param {string|Account|Transaction} to - The address of an existing contract, an Account representing the contract, or the contract creation Transaction.
* @param {string} method - The method in the contract to call.
* @param {array} params - The parameters to use during the method call.
* @returns {Transaction} Returns a transaction which has already been sent.
* @api public
*/
executeWrite(to, method, params, value) {
assert.isAccountable(to, messages.TRANSACTION_TO_ISACCOUNTABLE);
assert.isString(method, messages.TRANSACTION_METHOD_ISSTRING);
assert.isArray(params, messages.TRANSACTION_PARAMS_ISARRAY);
value = bigInt(value);
if (to.constructor.name === 'Transaction') {
to = new Account(to.address);
} else if (Object.prototype.toString.call(to) === '[object String]') {
to = new Account(to);
}
const tx = new Transaction({
type: 2,
from: this,
to: to,
value: value.toString(),
method: method,
params: params,
time: +(new Date())-10
});
tx.send()
.then((d) => {
this._balance = this._balance.subtract(value);
})
.catch((e) => {
console.error(e);
});
return tx;
}
/**
* Creates and sends a transaction from the account that will read the state of an existing Smart Contract wihtout writing to the ledger.
*
* ```js
* let account = new Dispatch.Account({
* name: 'MyAccount',
* privateKey: '472ba91402425b58a2eebf932812f20c6d7f6297bba1f83d9a58116ae6512d9e'
* });
* let compiled = Dispatch.Transaction.compileSource('contract x { function g() { } }');
* let contract = account.createContract(compiled.contracts[0].bytecode, compiled.contracts[0].abi, 5);
* contract.whenStatusEquals('Ok')
* .then(() => {
* account.executeRead(contract, 'g', [], 5);
* })
* .catch((err) => {
* console.error(err);
* });
* ```
*
* @name executeRead
* @param {string|Account|Transaction} to - The address of an existing contract, an Account representing the contract, or the contract creation Transaction.
* @param {string} method - The method in the contract to call.
* @param {array} params - The parameters to use during the method call.
* @returns {Promise} Returns a promise of the result of the transaction call.
* @api public
*/
executeRead(to, method, params, value) {
assert.isAccountable(to, messages.TRANSACTION_TO_ISACCOUNTABLE);
assert.isString(method, messages.TRANSACTION_METHOD_ISSTRING);
assert.isArray(params, messages.TRANSACTION_PARAMS_ISARRAY);
value = bigInt(value);
if (to.constructor.name === 'Transaction') {
to = new Account(to.address);
} else if (Object.prototype.toString.call(to) === '[object String]') {
to = new Account(to);
}
const tx = new Transaction({
type: 3,
from: this,
to: to,
value: value.toString(),
method: method,
params: params,
time: +(new Date())-10
});
return new Promise((resolve, reject) => {
tx.send()
.then((d) => {
this._balance = this._balance.subtract(value);
resolve(d);
})
.catch((e) => {
console.error(e);
reject(e)
});
});
}
};
const Transaction = require('./Transaction');