forked from tronprotocol/tronweb
-
Notifications
You must be signed in to change notification settings - Fork 11
/
method.js
365 lines (284 loc) · 12.2 KB
/
method.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
import utils from 'utils';
import {ADDRESS_PREFIX_REGEX} from 'utils/address';
const getFunctionSelector = abi => {
return abi.name + '(' + getParamTypes(abi.inputs || []).join(',') + ')';
}
const getParamTypes = params => {
return params.map(({type}) => type);
}
const decodeOutput = (abi, output) => {
const names = abi.map(({name}) => name).filter(name => !!name);
const types = abi.map(({type}) => type);
return utils.abi.decodeParams(names, types, output);
};
export default class Method {
constructor(contract, abi) {
this.tronWeb = contract.tronWeb;
this.contract = contract;
this.abi = abi;
this.name = abi.name || (abi.name = abi.type);
this.inputs = abi.inputs || [];
this.outputs = abi.outputs || [];
this.functionSelector = getFunctionSelector(abi);
this.signature = this.tronWeb.sha3(this.functionSelector, false).slice(0, 8);
this.injectPromise = utils.promiseInjector(this);
this.defaultOptions = {
feeLimit: 1000000000,
callValue: 0,
userFeePercentage: 100,
shouldPollResponse: false // Only used for sign()
};
}
decodeInput(data) {
return decodeOutput(this.inputs, '0x' + data);
}
onMethod(...args) {
const types = getParamTypes(this.inputs);
args.forEach((arg, index) => {
if (types[index] == 'address')
args[index] = this.tronWeb.address.toHex(arg).replace(ADDRESS_PREFIX_REGEX, '0x')
if (types[index] == 'address[]') {
args[index] = args[index].map(address => {
return this.tronWeb.address.toHex(address).replace(ADDRESS_PREFIX_REGEX, '0x')
})
}
});
return {
call: (...methodArgs) => this._call(types, args, ...methodArgs),
send: (...methodArgs) => this._send(types, args, ...methodArgs),
watch: (...methodArgs) => this._watch(...methodArgs)
}
}
async _call(types, args, options = {}, callback = false) {
if (utils.isFunction(options)) {
callback = options;
options = {};
}
if (!callback)
return this.injectPromise(this._call, types, args, options);
if (types.length !== args.length)
return callback('Invalid argument count provided');
if (!this.contract.address)
return callback('Smart contract is missing address');
if (!this.contract.deployed)
return callback('Calling smart contracts requires you to load the contract first');
const {stateMutability} = this.abi;
if (!['pure', 'view'].includes(stateMutability.toLowerCase()))
return callback(`Methods with state mutability "${stateMutability}" must use send()`);
options = {
...this.defaultOptions,
from: this.tronWeb.defaultAddress.hex,
...options,
};
const parameters = args.map((value, index) => ({
type: types[index],
value
}));
this.tronWeb.transactionBuilder.triggerSmartContract(
this.contract.address,
this.functionSelector,
options,
parameters,
options.from ? this.tronWeb.address.toHex(options.from) : false,
(err, transaction) => {
if (err)
return callback(err);
if (!utils.hasProperty(transaction, 'constant_result'))
return callback('Failed to execute');
try {
const len = transaction.constant_result[0].length
if (len === 0 || len % 64 === 8) {
let msg = 'The call has been reverted or has thrown an error.'
if (len !== 0) {
msg += ' Error message: '
let msg2 = ''
let chunk = transaction.constant_result[0].substring(8)
for (let i = 0; i < len - 8; i += 64) {
msg2 += this.tronWeb.toUtf8(chunk.substring(i, i + 64))
}
msg += msg2.replace(/(\u0000|\u000b|\f)+/g, ' ').replace(/ +/g, ' ').replace(/\s+$/g, '');
}
return callback(msg)
}
let output = decodeOutput(this.outputs, '0x' + transaction.constant_result[0]);
if (output.length === 1)
output = output[0];
return callback(null, output);
} catch (ex) {
return callback(ex);
}
});
}
async _send(types, args, options = {}, privateKey = this.tronWeb.defaultPrivateKey, callback = false) {
if (utils.isFunction(privateKey)) {
callback = privateKey;
privateKey = this.tronWeb.defaultPrivateKey;
}
if (utils.isFunction(options)) {
callback = options;
options = {};
}
if (!callback)
return this.injectPromise(this._send, types, args, options, privateKey);
if (types.length !== args.length)
throw new Error('Invalid argument count provided');
if (!this.contract.address)
return callback('Smart contract is missing address');
if (!this.contract.deployed)
return callback('Calling smart contracts requires you to load the contract first');
const {stateMutability} = this.abi;
if (['pure', 'view'].includes(stateMutability.toLowerCase()))
return callback(`Methods with state mutability "${stateMutability}" must use call()`);
// If a function isn't payable, dont provide a callValue.
if (!['payable'].includes(stateMutability.toLowerCase()))
options.callValue = 0;
options = {
...this.defaultOptions,
from: this.tronWeb.defaultAddress.hex,
...options,
};
const parameters = args.map((value, index) => ({
type: types[index],
value
}));
try {
const address = privateKey ? this.tronWeb.address.fromPrivateKey(privateKey) : this.tronWeb.defaultAddress.base58;
const transaction = await this.tronWeb.transactionBuilder.triggerSmartContract(
this.contract.address,
this.functionSelector,
options,
parameters,
this.tronWeb.address.toHex(address)
);
if (!transaction.result || !transaction.result.result)
return callback('Unknown error: ' + JSON.stringify(transaction, null, 2));
// If privateKey is false, this won't be signed here. We assume sign functionality will be replaced.
const signedTransaction = await this.tronWeb.trx.sign(transaction.transaction, privateKey);
if (!signedTransaction.signature) {
if (!privateKey)
return callback('Transaction was not signed properly');
return callback('Invalid private key provided');
}
const broadcast = await this.tronWeb.trx.sendRawTransaction(signedTransaction);
if (broadcast.code)
return callback({
error: broadcast.code,
message: this.tronWeb.toUtf8(broadcast.message)
})
if (!options.shouldPollResponse)
return callback(null, signedTransaction.txID);
const checkResult = async (index = 0) => {
if (index == 20) {
return callback({
error: 'Cannot find result in solidity node',
transaction: signedTransaction
});
}
const output = await this.tronWeb.trx.getTransactionInfo(signedTransaction.txID);
if (!Object.keys(output).length) {
return setTimeout(() => {
checkResult(index + 1);
}, 3000);
}
if (output.result && output.result == 'FAILED') {
return callback({
error: this.tronWeb.toUtf8(output.resMessage),
transaction: signedTransaction,
output
});
}
if (!utils.hasProperty(output, 'contractResult')) {
return callback({
error: 'Failed to execute: ' + JSON.stringify(output, null, 2),
transaction: signedTransaction,
output
});
}
if (options.rawResponse)
return callback(null, output);
let decoded = decodeOutput(this.outputs, '0x' + output.contractResult[0]);
if (decoded.length === 1)
decoded = decoded[0];
return callback(null, decoded);
}
checkResult();
} catch (ex) {
return callback(ex);
}
}
async _watch(options = {}, callback = false) {
if (utils.isFunction(options)) {
callback = options;
options = {};
}
if (!utils.isFunction(callback))
throw new Error('Expected callback to be provided');
if (!this.contract.address)
return callback('Smart contract is missing address');
if (!this.abi.type || !/event/i.test(this.abi.type))
return callback('Invalid method type for event watching');
if (!this.tronWeb.eventServer)
return callback('No event server configured');
let listener = false;
let lastBlock = false;
let since = Date.now() - 1000;
const getEvents = async () => {
try {
const params = {
since,
eventName: this.name,
sort: 'block_timestamp',
blockNumber: 'latest',
filters: options.filters
}
if (options.resourceNode) {
if (/full/i.test(options.resourceNode))
params.onlyUnconfirmed = true
else
params.onlyConfirmed = true
}
const events = await this.tronWeb.event.getEventsByContractAddress(this.contract.address, params);
const [latestEvent] = events.sort((a, b) => b.block - a.block);
const newEvents = events.filter((event, index) => {
if (options.resourceNode && event.resourceNode &&
options.resourceNode.toLowerCase() !== event.resourceNode.toLowerCase()) {
return false
}
const duplicate = events.slice(0, index).some(priorEvent => (
JSON.stringify(priorEvent) == JSON.stringify(event)
));
if (duplicate)
return false;
if (!lastBlock)
return true;
return event.block > lastBlock;
});
if (latestEvent)
lastBlock = latestEvent.block;
return newEvents;
} catch (ex) {
return Promise.reject(ex);
}
};
const bindListener = () => {
if (listener)
clearInterval(listener);
listener = setInterval(() => {
getEvents().then(events => events.forEach(event => {
callback(null, utils.parseEvent(event, this.abi))
})).catch(err => callback(err));
}, 3000);
};
await getEvents();
bindListener();
return {
start: bindListener(),
stop: () => {
if (!listener)
return;
clearInterval(listener);
listener = false;
}
}
}
}