-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathindex.js
409 lines (334 loc) · 12.1 KB
/
index.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
import providers from 'lib/providers';
import utils from 'utils';
import BigNumber from 'bignumber.js';
import EventEmitter from 'eventemitter3';
import { version } from '../package.json';
import semver from 'semver';
import injectpromise from 'injectpromise';
import TransactionBuilder from 'lib/transactionBuilder';
import Trx from 'lib/trx';
import Contract from 'lib/contract';
import Plugin from 'lib/plugin';
import Event from 'lib/event';
import SideChain from 'lib/sidechain';
import { keccak256 } from 'utils/ethersUtils';
import { ADDRESS_PREFIX } from 'utils/address';
const DEFAULT_VERSION = '3.5.0';
const FEE_LIMIT = 20000000;
export default class TronWeb extends EventEmitter {
static providers = providers;
static BigNumber = BigNumber;
static TransactionBuilder = TransactionBuilder;
static Trx = Trx;
static Contract = Contract;
static Plugin = Plugin;
static Event = Event;
static version = version;
static utils = utils;
constructor(options = false,
// for retro-compatibility:
solidityNode = false, eventServer = false, sideOptions = false, privateKey = false) {
super();
let fullNode;
if (typeof options === 'object' && (options.fullNode || options.fullHost)) {
fullNode = options.fullNode || options.fullHost;
sideOptions = solidityNode;
solidityNode = options.solidityNode || options.fullHost;
eventServer = options.eventServer || options.fullHost;
privateKey = options.privateKey;
} else {
fullNode = options;
}
if (utils.isString(fullNode))
fullNode = new providers.HttpProvider(fullNode);
if (utils.isString(solidityNode))
solidityNode = new providers.HttpProvider(solidityNode);
if (utils.isString(eventServer))
eventServer = new providers.HttpProvider(eventServer);
this.event = new Event(this);
this.transactionBuilder = new TransactionBuilder(this);
this.trx = new Trx(this);
this.plugin = new Plugin(this, options);
this.utils = utils;
this.setFullNode(fullNode);
this.setSolidityNode(solidityNode);
this.setEventServer(eventServer);
this.providers = providers;
this.BigNumber = BigNumber;
this.defaultBlock = false;
this.defaultPrivateKey = false;
this.defaultAddress = {
hex: false,
base58: false
};
[
'sha3', 'toHex', 'toUtf8', 'fromUtf8',
'toAscii', 'fromAscii', 'toDecimal', 'fromDecimal',
'toSun', 'fromSun', 'toBigNumber', 'isAddress',
'createAccount', 'address', 'version'
].forEach(key => {
this[key] = TronWeb[key];
});
// for sidechain
if (typeof sideOptions === 'object' && (sideOptions.fullNode || sideOptions.fullHost)) {
this.sidechain = new SideChain(sideOptions, TronWeb, this, privateKey);
} else {
privateKey = privateKey || sideOptions;
}
if (privateKey)
this.setPrivateKey(privateKey);
this.fullnodeVersion = DEFAULT_VERSION;
this.feeLimit = FEE_LIMIT;
this.injectPromise = injectpromise(this);
}
async getFullnodeVersion() {
try {
const nodeInfo = await this.trx.getNodeInfo()
this.fullnodeVersion = nodeInfo.configNodeInfo.codeVersion
if (this.fullnodeVersion.split('.').length === 2) {
this.fullnodeVersion += '.0';
}
} catch (err) {
this.fullnodeVersion = DEFAULT_VERSION;
}
}
setDefaultBlock(blockID = false) {
if ([false, 'latest', 'earliest', 0].includes(blockID)) {
return this.defaultBlock = blockID;
}
if (!utils.isInteger(blockID) || !blockID)
throw new Error('Invalid block ID provided');
this.defaultBlock = Math.abs(blockID);
}
setPrivateKey(privateKey) {
try {
this.setAddress(
this.address.fromPrivateKey(privateKey)
);
} catch {
throw new Error('Invalid private key provided');
}
this.defaultPrivateKey = privateKey;
this.emit('privateKeyChanged', privateKey);
}
setAddress(address) {
if (!this.isAddress(address))
throw new Error('Invalid address provided');
const hex = this.address.toHex(address);
const base58 = this.address.fromHex(address);
if (this.defaultPrivateKey && this.address.fromPrivateKey(this.defaultPrivateKey) !== base58)
this.defaultPrivateKey = false;
this.defaultAddress = {
hex,
base58
};
this.emit('addressChanged', { hex, base58 });
}
fullnodeSatisfies(version) {
return semver.satisfies(this.fullnodeVersion, version);
}
isValidProvider(provider) {
return Object.values(providers).some(knownProvider => provider instanceof knownProvider);
}
setFullNode(fullNode) {
if (utils.isString(fullNode))
fullNode = new providers.HttpProvider(fullNode);
if (!this.isValidProvider(fullNode))
throw new Error('Invalid full node provided');
this.fullNode = fullNode;
this.fullNode.setStatusPage('wallet/getnowblock');
this.getFullnodeVersion();
}
setSolidityNode(solidityNode) {
if (utils.isString(solidityNode))
solidityNode = new providers.HttpProvider(solidityNode);
if (!this.isValidProvider(solidityNode))
throw new Error('Invalid solidity node provided');
this.solidityNode = solidityNode;
this.solidityNode.setStatusPage('walletsolidity/getnowblock');
}
setEventServer(...params) {
this.event.setServer(...params)
}
currentProviders() {
return {
fullNode: this.fullNode,
solidityNode: this.solidityNode,
eventServer: this.eventServer
};
}
currentProvider() {
return this.currentProviders();
}
getEventResult(...params) {
if (typeof params[1] !== 'object') {
params[1] = {
sinceTimestamp: params[1] || 0,
eventName: params[2] || false,
blockNumber: params[3] || false,
size: params[4] || 20,
page: params[5] || 1
}
params.splice(2, 4)
// callback:
if (!utils.isFunction(params[2])) {
if (utils.isFunction(params[1].page)) {
params[2] = params[1].page;
params[1].page = 1;
} else if (utils.isFunction(params[1].size)) {
params[2] = params[1].size;
params[1].size = 20;
params[1].page = 1;
}
}
}
return this.event.getEventsByContractAddress(...params);
}
getEventByTransactionID(...params) {
return this.event.getEventsByTransactionID(...params)
}
contract(abi = [], address = false) {
return new Contract(this, abi, address);
}
static get address() {
return {
fromHex(address) {
if (!utils.isHex(address))
return address;
return utils.crypto.getBase58CheckAddress(
utils.code.hexStr2byteArray(address.replace(/^0x/, ADDRESS_PREFIX))
);
},
toHex(address) {
if (utils.isHex(address))
return address.toLowerCase().replace(/^0x/, ADDRESS_PREFIX);
return utils.code.byteArray2hexStr(
utils.crypto.decodeBase58Address(address)
).toLowerCase();
},
fromPrivateKey(privateKey) {
try {
return utils.crypto.pkToAddress(privateKey);
} catch {
return false;
}
}
}
}
static sha3(string, prefix = true) {
return (prefix ? '0x' : '') + keccak256(Buffer.from(string, 'utf-8')).toString().substring(2);
}
static toHex(val) {
if (utils.isBoolean(val))
return TronWeb.fromDecimal(+val);
if (utils.isBigNumber(val))
return TronWeb.fromDecimal(val);
if (typeof val === 'object')
return TronWeb.fromUtf8(JSON.stringify(val));
if (utils.isString(val)) {
if (/^(-|)0x/.test(val))
return val;
if ((!isFinite(val)) || /^\s*$/.test(val))
return TronWeb.fromUtf8(val);
}
let result = TronWeb.fromDecimal(val);
if (result === '0xNaN') {
throw new Error('The passed value is not convertible to a hex string');
} else {
return result;
}
}
static toUtf8(hex) {
if (utils.isHex(hex)) {
hex = hex.replace(/^0x/, '');
return Buffer.from(hex, 'hex').toString('utf8');
} else {
throw new Error('The passed value is not a valid hex string');
}
}
static fromUtf8(string) {
if (!utils.isString(string)) {
throw new Error('The passed value is not a valid utf-8 string')
}
return '0x' + Buffer.from(string, 'utf8').toString('hex');
}
static toAscii(hex) {
if (utils.isHex(hex)) {
let str = "";
let i = 0, l = hex.length;
if (hex.substring(0, 2) === '0x') {
i = 2;
}
for (; i < l; i += 2) {
let code = parseInt(hex.substr(i, 2), 16);
str += String.fromCharCode(code);
}
return str;
} else {
throw new Error('The passed value is not a valid hex string');
}
}
static fromAscii(string, padding) {
if (!utils.isString(string)) {
throw new Error('The passed value is not a valid utf-8 string')
}
return '0x' + Buffer.from(string, 'ascii').toString('hex').padEnd(padding, '0');
}
static toDecimal(value) {
return TronWeb.toBigNumber(value).toNumber();
}
static fromDecimal(value) {
const number = TronWeb.toBigNumber(value);
const result = number.toString(16);
return number.isLessThan(0) ? '-0x' + result.substr(1) : '0x' + result;
}
static fromSun(sun) {
const trx = TronWeb.toBigNumber(sun).div(1_000_000);
return utils.isBigNumber(sun) ? trx : trx.toString(10);
}
static toSun(trx) {
const sun = TronWeb.toBigNumber(trx).times(1_000_000);
return utils.isBigNumber(trx) ? sun : sun.toString(10);
}
static toBigNumber(amount = 0) {
if (utils.isBigNumber(amount))
return amount;
if (utils.isString(amount) && /^(-|)0x/.test(amount))
return new BigNumber(amount.replace('0x', ''), 16);
return new BigNumber(amount.toString(10), 10);
}
static isAddress(address = false) {
if (!utils.isString(address))
return false;
// Convert HEX to Base58
if (address.length === 42) {
try {
return TronWeb.isAddress(
utils.crypto.getBase58CheckAddress(
utils.code.hexStr2byteArray(address) // it throws an error if the address starts with 0x
)
);
} catch (err) {
return false;
}
}
try {
return utils.crypto.isAddressValid(address);
} catch (err) {
return false;
}
}
static async createAccount() {
const account = utils.accounts.generateAccount();
return account;
}
async isConnected(callback = false) {
if (!callback)
return this.injectPromise(this.isConnected);
return callback(null, {
fullNode: await this.fullNode.isConnected(),
solidityNode: await this.solidityNode.isConnected(),
eventServer: this.eventServer && await this.eventServer.isConnected()
});
}
};