-
Notifications
You must be signed in to change notification settings - Fork 5k
/
index.js
451 lines (385 loc) · 13.5 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
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
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file index.js
* @author Marek Kotewicz <marek@parity.io>
* @author Fabian Vogelsteller <fabian@frozeman.de>
* @date 2018
*/
var Buffer = require('buffer').Buffer;
var utils = require('web3-utils');
var EthersAbiCoder = require('@ethersproject/abi').AbiCoder;
var ParamType = require('@ethersproject/abi').ParamType;
var ethersAbiCoder = new EthersAbiCoder(function (type, value) {
if (type.match(/^u?int/) && !Array.isArray(value) && (!(!!value && typeof value === 'object') || value.constructor.name !== 'BN')) {
return value.toString();
}
return value;
});
// result method
function Result() {
}
/**
* ABICoder prototype should be used to encode/decode solidity params of any type
*/
var ABICoder = function () {
};
/**
* Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including types.
*
* @method encodeFunctionSignature
* @param {String|Object} functionName
* @return {String} encoded function name
*/
ABICoder.prototype.encodeFunctionSignature = function (functionName) {
if (typeof functionName === 'function' || typeof functionName === 'object' && functionName) {
functionName = utils._jsonInterfaceMethodToString(functionName);
}
return utils.sha3(functionName).slice(0, 10);
};
/**
* Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including types.
*
* @method encodeEventSignature
* @param {String|Object} functionName
* @return {String} encoded function name
*/
ABICoder.prototype.encodeEventSignature = function (functionName) {
if (typeof functionName === 'function' || typeof functionName === 'object' && functionName) {
functionName = utils._jsonInterfaceMethodToString(functionName);
}
return utils.sha3(functionName);
};
/**
* Should be used to encode plain param
*
* @method encodeParameter
*
* @param {String|Object} type
* @param {any} param
*
* @return {String} encoded plain param
*/
ABICoder.prototype.encodeParameter = function (type, param) {
return this.encodeParameters([type], [param]);
};
/**
* Should be used to encode list of params
*
* @method encodeParameters
*
* @param {Array<String|Object>} types
* @param {Array<any>} params
*
* @return {String} encoded list of params
*/
ABICoder.prototype.encodeParameters = function (types, params) {
var self = this;
types = self.mapTypes(types);
params = params.map(function (param, index) {
let type = types[index];
if (typeof type === 'object' && type.type) {
// We may get a named type of shape {name, type}
type = type.type;
}
param = self.formatParam(type, param);
// Format params for tuples
if (typeof type === 'string' && type.includes('tuple')) {
const coder = ethersAbiCoder._getCoder(ParamType.from(type));
const modifyParams = (coder, param) => {
if (coder.name === 'array') {
if (!coder.type.match(/\[(\d+)\]/)) {
return param.map(p => modifyParams(ethersAbiCoder._getCoder(ParamType.from(coder.type.replace('[]', ''))), p));
}
const arrayLength = parseInt(coder.type.match(/\[(\d+)\]/)[1]);
if (param.length !== arrayLength) {
throw new Error('Array length does not matches with the given input');
}
return param.map(p => modifyParams(ethersAbiCoder._getCoder(ParamType.from(coder.type.replace(/\[\d+\]/, ''))), p));
}
coder.coders.forEach((c, i) => {
if (c.name === 'tuple') {
modifyParams(c, param[i]);
} else {
param[i] = self.formatParam(c.name, param[i]);
}
});
};
modifyParams(coder, param);
}
return param;
});
return ethersAbiCoder.encode(types, params);
};
/**
* Map types if simplified format is used
*
* @method mapTypes
* @param {Array} types
* @return {Array}
*/
ABICoder.prototype.mapTypes = function (types) {
var self = this;
var mappedTypes = [];
types.forEach(function (type) {
// Remap `function` type params to bytes24 since Ethers does not
// recognize former type. Solidity docs say `Function` is a bytes24
// encoding the contract address followed by the function selector hash.
if (typeof type === 'object' && type.type === 'function'){
type = Object.assign({}, type, { type: "bytes24" });
}
if (self.isSimplifiedStructFormat(type)) {
var structName = Object.keys(type)[0];
mappedTypes.push(
Object.assign(
self.mapStructNameAndType(structName),
{
components: self.mapStructToCoderFormat(type[structName])
}
)
);
return;
}
mappedTypes.push(type);
});
return mappedTypes;
};
/**
* Check if type is simplified struct format
*
* @method isSimplifiedStructFormat
* @param {string | Object} type
* @returns {boolean}
*/
ABICoder.prototype.isSimplifiedStructFormat = function (type) {
return typeof type === 'object' && typeof type.components === 'undefined' && typeof type.name === 'undefined';
};
/**
* Maps the correct tuple type and name when the simplified format in encode/decodeParameter is used
*
* @method mapStructNameAndType
* @param {string} structName
* @return {{type: string, name: *}}
*/
ABICoder.prototype.mapStructNameAndType = function (structName) {
var type = 'tuple';
if (structName.indexOf('[]') > -1) {
type = 'tuple[]';
structName = structName.slice(0, -2);
}
return {type: type, name: structName};
};
/**
* Maps the simplified format in to the expected format of the ABICoder
*
* @method mapStructToCoderFormat
* @param {Object} struct
* @return {Array}
*/
ABICoder.prototype.mapStructToCoderFormat = function (struct) {
var self = this;
var components = [];
Object.keys(struct).forEach(function (key) {
if (typeof struct[key] === 'object') {
components.push(
Object.assign(
self.mapStructNameAndType(key),
{
components: self.mapStructToCoderFormat(struct[key])
}
)
);
return;
}
components.push({
name: key,
type: struct[key]
});
});
return components;
};
/**
* Handle some formatting of params for backwards compatability with Ethers V4
*
* @method formatParam
* @param {String} - type
* @param {any} - param
* @return {any} - The formatted param
*/
ABICoder.prototype.formatParam = function (type, param) {
const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/);
const paramTypeBytesArray = new RegExp(/^bytes([0-9]*)\[\]$/);
const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/);
const paramTypeNumberArray = new RegExp(/^(u?int)([0-9]*)\[\]$/);
// Format BN to string
if (utils.isBN(param) || utils.isBigNumber(param)) {
return param.toString(10);
}
if (type.match(paramTypeBytesArray) || type.match(paramTypeNumberArray)) {
return param.map(p => this.formatParam(type.replace('[]', ''), p));
}
// Format correct width for u?int[0-9]*
let match = type.match(paramTypeNumber);
if (match) {
let size = parseInt(match[2] || "256");
if (size / 8 < param.length) {
param = param.startsWith("-")
// pad to correct bit width, with - at the beginning
? `-${utils.leftPad(param.substring(1), size)}`
// pad to correct bit width
: utils.leftPad(param, size);
}
}
// Format correct length for bytes[0-9]+
match = type.match(paramTypeBytes);
if (match) {
if (Buffer.isBuffer(param)) {
param = utils.toHex(param);
}
// format to correct length
let size = parseInt(match[1]);
if (size) {
let maxSize = size * 2;
if (param.substring(0, 2) === '0x') {
maxSize += 2;
}
if (param.length < maxSize) {
// pad to correct length
param = utils.rightPad(param, size * 2);
}
}
// format odd-length bytes to even-length
if (param.length % 2 === 1) {
param = '0x0' + param.substring(2);
}
}
return param;
};
/**
* Encodes a function call from its json interface and parameters.
*
* @method encodeFunctionCall
* @param {Array} jsonInterface
* @param {Array} params
* @return {String} The encoded ABI for this function call
*/
ABICoder.prototype.encodeFunctionCall = function (jsonInterface, params) {
return this.encodeFunctionSignature(jsonInterface) + this.encodeParameters(jsonInterface.inputs, params).replace('0x', '');
};
/**
* Should be used to decode bytes to plain param
*
* @method decodeParameter
* @param {String} type
* @param {String} bytes
* @return {Object} plain param
*/
ABICoder.prototype.decodeParameter = function (type, bytes) {
return this.decodeParameters([type], bytes)[0];
};
/**
* Should be used to decode list of params
*
* @method decodeParameter
* @param {Array} outputs
* @param {String} bytes
* @return {Array} array of plain params
*/
ABICoder.prototype.decodeParameters = function (outputs, bytes) {
return this.decodeParametersWith(outputs, bytes, false);
}
/**
* Should be used to decode list of params
*
* @method decodeParameter
* @param {Array} outputs
* @param {String} bytes
* @param {Boolean} loose
* @return {Array} array of plain params
*/
ABICoder.prototype.decodeParametersWith = function (outputs, bytes, loose) {
if (outputs.length > 0 && (!bytes || bytes === '0x' || bytes === '0X')) {
throw new Error(
'Returned values aren\'t valid, did it run Out of Gas? ' +
'You might also see this error if you are not using the ' +
'correct ABI for the contract you are retrieving data from, ' +
'requesting data from a block number that does not exist, ' +
'or querying a node which is not fully synced.'
);
}
var res = ethersAbiCoder.decode(this.mapTypes(outputs), '0x' + bytes.replace(/0x/i, ''), loose);
var returnValue = new Result();
returnValue.__length__ = 0;
outputs.forEach(function (output, i) {
var decodedValue = res[returnValue.__length__];
const isStringObject = typeof output === 'object' && output.type && output.type === 'string';
const isStringType = typeof output === 'string' && output === 'string';
// only convert `0x` to null if it's not string value
decodedValue = (decodedValue === '0x' && !isStringObject && !isStringType) ? null : decodedValue;
returnValue[i] = decodedValue;
if ((typeof output === 'function' || !!output && typeof output === 'object') && output.name) {
returnValue[output.name] = decodedValue;
}
returnValue.__length__++;
});
return returnValue;
};
/**
* Decodes events non- and indexed parameters.
*
* @method decodeLog
* @param {Object} inputs
* @param {String} data
* @param {Array} topics
* @return {Array} array of plain params
*/
ABICoder.prototype.decodeLog = function (inputs, data, topics) {
var _this = this;
topics = Array.isArray(topics) ? topics : [topics];
data = data || '';
var notIndexedInputs = [];
var indexedParams = [];
var topicCount = 0;
// TODO check for anonymous logs?
inputs.forEach(function (input, i) {
if (input.indexed) {
indexedParams[i] = (['bool', 'int', 'uint', 'address', 'fixed', 'ufixed'].find(function (staticType) {
return input.type.indexOf(staticType) !== -1;
})) ? _this.decodeParameter(input.type, topics[topicCount]) : topics[topicCount];
topicCount++;
} else {
notIndexedInputs[i] = input;
}
});
var nonIndexedData = data;
var notIndexedParams = (nonIndexedData) ? this.decodeParametersWith(notIndexedInputs, nonIndexedData, true) : [];
var returnValue = new Result();
returnValue.__length__ = 0;
inputs.forEach(function (res, i) {
returnValue[i] = (res.type === 'string') ? '' : null;
if (typeof notIndexedParams[i] !== 'undefined') {
returnValue[i] = notIndexedParams[i];
}
if (typeof indexedParams[i] !== 'undefined') {
returnValue[i] = indexedParams[i];
}
if (res.name) {
returnValue[res.name] = returnValue[i];
}
returnValue.__length__++;
});
return returnValue;
};
var coder = new ABICoder();
module.exports = coder;