-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathindex.js
387 lines (331 loc) · 11.9 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
/*
Primary Attribution
Richard Moore <[email protected]>
https://github.com/ethers-io
Note, Richard is a god of ether gods. Follow and respect him, and use Ethers.io!
*/
const BN = require('bn.js');
const numberToBN = require('number-to-bn');
const keccak256 = require('js-sha3').keccak_256;
// from ethereumjs-util
function stripZeros(aInput) {
var a = aInput; // eslint-disable-line
var first = a[0]; // eslint-disable-line
while (a.length > 0 && first.toString() === '0') {
a = a.slice(1);
first = a[0];
}
return a;
}
function bnToBuffer(bnInput) {
var bn = bnInput; // eslint-disable-line
var hex = bn.toString(16); // eslint-disable-line
if (hex.length % 2) { hex = `0${hex}`; }
return stripZeros(new Buffer(hex, 'hex'));
}
function isHexString(value, length) {
if (typeof(value) !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) {
return false;
}
if (length && value.length !== 2 + 2 * length) { return false; }
return true;
}
function hexOrBuffer(valueInput, name) {
var value = valueInput; // eslint-disable-line
if (!Buffer.isBuffer(value)) {
if (!isHexString(value)) {
const error = new Error(name ? (`[ethjs-abi] invalid ${name}`) : '[ethjs-abi] invalid hex or buffer, must be a prefixed alphanumeric even length hex string');
error.reason = '[ethjs-abi] invalid hex string, hex must be prefixed and alphanumeric (e.g. 0x023..)';
error.value = value;
throw error;
}
value = value.substring(2);
if (value.length % 2) { value = `0${value}`; }
value = new Buffer(value, 'hex');
}
return value;
}
function hexlify(value) {
if (typeof(value) === 'number') {
return `0x${bnToBuffer(new BN(value)).toString('hex')}`;
} else if (value.mod || value.modulo) {
return `0x${bnToBuffer(value).toString('hex')}`;
} else { // eslint-disable-line
return `0x${hexOrBuffer(value).toString('hex')}`;
}
}
// getKeys([{a: 1, b: 2}, {a: 3, b: 4}], 'a') => [1, 3]
function getKeys(params, key, allowEmpty) {
var result = []; // eslint-disable-line
if (!Array.isArray(params)) { throw new Error(`[ethjs-abi] while getting keys, invalid params value ${JSON.stringify(params)}`); }
for (var i = 0; i < params.length; i++) { // eslint-disable-line
var value = params[i][key]; // eslint-disable-line
if (allowEmpty && !value) {
value = '';
} else if (typeof(value) !== 'string') {
throw new Error('[ethjs-abi] while getKeys found invalid ABI data structure, type value not string');
}
result.push(value);
}
return result;
}
function coderNumber(size, signed) {
return {
encode: function encodeNumber(valueInput) {
var value = valueInput; // eslint-disable-line
if (typeof value === 'object'
&& value.toString
&& (value.toTwos || value.dividedToIntegerBy)) {
value = (value.toString(10)).split('.')[0];
}
if (typeof value === 'string' || typeof value === 'number') {
value = String(value).split('.')[0];
}
value = numberToBN(value);
value = value.toTwos(size * 8).maskn(size * 8);
if (signed) {
value = value.fromTwos(size * 8).toTwos(256);
}
return value.toArrayLike(Buffer, 'be', 32);
},
decode: function decodeNumber(data, offset) {
var junkLength = 32 - size; // eslint-disable-line
var value = new BN(data.slice(offset + junkLength, offset + 32)); // eslint-disable-line
if (signed) {
value = value.fromTwos(size * 8);
} else {
value = value.maskn(size * 8);
}
return {
consumed: 32,
value: new BN(value.toString(10)),
};
},
};
}
const uint256Coder = coderNumber(32, false);
const coderBoolean = {
encode: function encodeBoolean(value) {
return uint256Coder.encode(value ? 1 : 0);
},
decode: function decodeBoolean(data, offset) {
var result = uint256Coder.decode(data, offset); // eslint-disable-line
return {
consumed: result.consumed,
value: !result.value.isZero(),
};
},
};
function coderFixedBytes(length) {
return {
encode: function encodeFixedBytes(valueInput) {
var value = valueInput; // eslint-disable-line
value = hexOrBuffer(value);
if (value.length === 32) { return value; }
var result = new Buffer(32); // eslint-disable-line
result.fill(0);
value.copy(result);
return result;
},
decode: function decodeFixedBytes(data, offset) {
if (data.length !== 0 && data.length < offset + 32) { throw new Error(`[ethjs-abi] while decoding fixed bytes, invalid bytes data length: ${length}`); }
return {
consumed: 32,
value: `0x${data.slice(offset, offset + length).toString('hex')}`,
};
},
};
}
const coderAddress = {
encode: function encodeAddress(valueInput) {
var value = valueInput; // eslint-disable-line
var result = new Buffer(32); // eslint-disable-line
if (!isHexString(value, 20)) { throw new Error('[ethjs-abi] while encoding address, invalid address value, not alphanumeric 20 byte hex string'); }
value = hexOrBuffer(value);
result.fill(0);
value.copy(result, 12);
return result;
},
decode: function decodeAddress(data, offset) {
if (data.length === 0) {
return {
consumed: 32,
value: '0x',
};
}
if (data.length !== 0 && data.length < offset + 32) { throw new Error(`[ethjs-abi] while decoding address data, invalid address data, invalid byte length ${data.length}`); }
return {
consumed: 32,
value: `0x${data.slice(offset + 12, offset + 32).toString('hex')}`,
};
},
};
function encodeDynamicBytesHelper(value) {
var dataLength = parseInt(32 * Math.ceil(value.length / 32)); // eslint-disable-line
var padding = new Buffer(dataLength - value.length); // eslint-disable-line
padding.fill(0);
return Buffer.concat([
uint256Coder.encode(value.length),
value,
padding,
]);
}
function decodeDynamicBytesHelper(data, offset) {
if (data.length !== 0 && data.length < offset + 32) { throw new Error(`[ethjs-abi] while decoding dynamic bytes data, invalid bytes length: ${data.length} should be less than ${offset + 32}`); }
var length = uint256Coder.decode(data, offset).value; // eslint-disable-line
length = length.toNumber();
if (data.length !== 0 && data.length < offset + 32 + length) { throw new Error(`[ethjs-abi] while decoding dynamic bytes data, invalid bytes length: ${data.length} should be less than ${offset + 32 + length}`); }
return {
consumed: parseInt(32 + 32 * Math.ceil(length / 32), 10),
value: data.slice(offset + 32, offset + 32 + length),
};
}
const coderDynamicBytes = {
encode: function encodeDynamicBytes(value) {
return encodeDynamicBytesHelper(hexOrBuffer(value));
},
decode: function decodeDynamicBytes(data, offset) {
var result = decodeDynamicBytesHelper(data, offset); // eslint-disable-line
result.value = `0x${result.value.toString('hex')}`;
return result;
},
dynamic: true,
};
const coderString = {
encode: function encodeString(value) {
return encodeDynamicBytesHelper(new Buffer(value, 'utf8'));
},
decode: function decodeString(data, offset) {
var result = decodeDynamicBytesHelper(data, offset); // eslint-disable-line
result.value = result.value.toString('utf8');
return result;
},
dynamic: true,
};
function coderArray(coder, lengthInput) {
return {
encode: function encodeArray(value) {
var result = new Buffer(0); // eslint-disable-line
var length = lengthInput; // eslint-disable-line
if (!Array.isArray(value)) { throw new Error('[ethjs-abi] while encoding array, invalid array data, not type Object (Array)'); }
if (length === -1) {
length = value.length;
result = uint256Coder.encode(length);
}
if (length !== value.length) { throw new Error(`[ethjs-abi] while encoding array, size mismatch array length ${length} does not equal ${value.length}`); }
value.forEach((resultValue) => {
result = Buffer.concat([
result,
coder.encode(resultValue),
]);
});
return result;
},
decode: function decodeArray(data, offsetInput) {
var length = lengthInput; // eslint-disable-line
var offset = offsetInput; // eslint-disable-line
// @TODO:
// if (data.length < offset + length * 32) { throw new Error('invalid array'); }
var consumed = 0; // eslint-disable-line
var decodeResult; // eslint-disable-line
if (length === -1) {
decodeResult = uint256Coder.decode(data, offset);
length = decodeResult.value.toNumber();
consumed += decodeResult.consumed;
offset += decodeResult.consumed;
}
var value = []; // eslint-disable-line
for (var i = 0; i < length; i++) { // eslint-disable-line
const loopResult = coder.decode(data, offset);
consumed += loopResult.consumed;
offset += loopResult.consumed;
value.push(loopResult.value);
}
return {
consumed,
value,
};
},
dynamic: (lengthInput === -1),
};
}
// Break the type up into [staticType][staticArray]*[dynamicArray]? | [dynamicType] and
// build the coder up from its parts
const paramTypePart = new RegExp(/^((u?int|bytes)([0-9]*)|(address|bool|string)|(\[([0-9]*)\]))/);
function getParamCoder(typeInput) {
var type = typeInput; // eslint-disable-line
var coder = null; // eslint-disable-line
const invalidTypeErrorMessage = `[ethjs-abi] while getting param coder (getParamCoder) type value ${JSON.stringify(type)} is either invalid or unsupported by ethjs-abi.`;
while (type) {
var part = type.match(paramTypePart); // eslint-disable-line
if (!part) { throw new Error(invalidTypeErrorMessage); }
type = type.substring(part[0].length);
var prefix = (part[2] || part[4] || part[5]); // eslint-disable-line
switch (prefix) {
case 'int': case 'uint':
if (coder) { throw new Error(invalidTypeErrorMessage); }
var intSize = parseInt(part[3] || 256); // eslint-disable-line
if (intSize === 0 || intSize > 256 || (intSize % 8) !== 0) {
throw new Error(`[ethjs-abi] while getting param coder for type ${type}, invalid ${prefix}<N> width: ${type}`);
}
coder = coderNumber(intSize / 8, (prefix === 'int'));
break;
case 'bool':
if (coder) { throw new Error(invalidTypeErrorMessage); }
coder = coderBoolean;
break;
case 'string':
if (coder) { throw new Error(invalidTypeErrorMessage); }
coder = coderString;
break;
case 'bytes':
if (coder) { throw new Error(invalidTypeErrorMessage); }
if (part[3]) {
var size = parseInt(part[3]); // eslint-disable-line
if (size === 0 || size > 32) {
throw new Error(`[ethjs-abi] while getting param coder for prefix bytes, invalid type ${type}, size ${size} should be 0 or greater than 32`);
}
coder = coderFixedBytes(size);
} else {
coder = coderDynamicBytes;
}
break;
case 'address':
if (coder) { throw new Error(invalidTypeErrorMessage); }
coder = coderAddress;
break;
case '[]':
if (!coder || coder.dynamic) { throw new Error(invalidTypeErrorMessage); }
coder = coderArray(coder, -1);
break;
// "[0-9+]"
default:
if (!coder || coder.dynamic) { throw new Error(invalidTypeErrorMessage); }
var defaultSize = parseInt(part[6]); // eslint-disable-line
coder = coderArray(coder, defaultSize);
}
}
if (!coder) { throw new Error(invalidTypeErrorMessage); }
return coder;
}
module.exports = {
BN,
bnToBuffer,
isHexString,
hexOrBuffer,
hexlify,
stripZeros,
keccak256,
getKeys,
numberToBN,
coderNumber,
uint256Coder,
coderBoolean,
coderFixedBytes,
coderAddress,
coderDynamicBytes,
coderString,
coderArray,
paramTypePart,
getParamCoder,
};