-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
utils.ts
458 lines (394 loc) · 12.5 KB
/
utils.ts
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
453
454
455
456
457
458
/*
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/>.
*/
import { InvalidBytesError, InvalidNumberError } from 'web3-errors';
import { VALID_ETH_BASE_TYPES } from './constants.js';
import {
FullValidationSchema,
JsonSchema,
ShortValidationSchema,
ValidationSchemaInput,
ValidInputTypes,
} from './types.js';
import { isAbiParameterSchema } from './validation/abi.js';
import { isHexStrict } from './validation/string.js';
import { Web3ValidatorError } from './errors.js';
const extraTypes = ['hex', 'number', 'blockNumber', 'blockNumberOrTag', 'filter', 'bloom'];
export const parseBaseType = <T = typeof VALID_ETH_BASE_TYPES[number]>(
type: string,
): {
baseType?: T;
baseTypeSize: number | undefined;
arraySizes: number[];
isArray: boolean;
} => {
// Remove all empty spaces to avoid any parsing issue.
let strippedType = type.replace(/ /, '');
let baseTypeSize: number | undefined;
let isArray = false;
let arraySizes: number[] = [];
if (type.includes('[')) {
// Extract the array type
strippedType = strippedType.slice(0, strippedType.indexOf('['));
// Extract array indexes
arraySizes = [...type.matchAll(/(?:\[(\d*)\])/g)]
.map(match => parseInt(match[1], 10))
.map(size => (Number.isNaN(size) ? -1 : size));
isArray = arraySizes.length > 0;
}
if (VALID_ETH_BASE_TYPES.includes(strippedType)) {
return { baseType: strippedType as unknown as T, isArray, baseTypeSize, arraySizes };
}
if (strippedType.startsWith('int')) {
baseTypeSize = parseInt(strippedType.substring(3), 10);
strippedType = 'int';
} else if (strippedType.startsWith('uint')) {
baseTypeSize = parseInt(type.substring(4), 10);
strippedType = 'uint';
} else if (strippedType.startsWith('bytes')) {
baseTypeSize = parseInt(strippedType.substring(5), 10);
strippedType = 'bytes';
} else {
return { baseType: undefined, isArray: false, baseTypeSize: undefined, arraySizes };
}
return { baseType: strippedType as unknown as T, isArray, baseTypeSize, arraySizes };
};
const convertEthType = (
type: string,
parentSchema: JsonSchema = {},
): { format?: string; required?: boolean } => {
const typePropertyPresent = Object.keys(parentSchema).includes('type');
if (typePropertyPresent) {
throw new Web3ValidatorError([
{
keyword: 'eth',
message: 'Either "eth" or "type" can be presented in schema',
params: { eth: type },
instancePath: '',
schemaPath: '',
},
]);
}
const { baseType, baseTypeSize } = parseBaseType(type);
if (!baseType && !extraTypes.includes(type)) {
throw new Web3ValidatorError([
{
keyword: 'eth',
message: `Eth data type "${type}" is not valid`,
params: { eth: type },
instancePath: '',
schemaPath: '',
},
]);
}
if (baseType) {
if (baseType === 'tuple') {
throw new Error('"tuple" type is not implemented directly.');
}
return { format: `${baseType}${baseTypeSize ?? ''}`, required: true };
}
if (type) {
return { format: type, required: true };
}
return {};
};
export const abiSchemaToJsonSchema = (
abis: ShortValidationSchema | FullValidationSchema,
level = '/0',
) => {
const schema: JsonSchema = {
type: 'array',
items: [],
maxItems: abis.length,
minItems: abis.length,
};
for (const [index, abi] of abis.entries()) {
// eslint-disable-next-line no-nested-ternary
let abiType!: string;
let abiName!: string;
let abiComponents: ShortValidationSchema | FullValidationSchema | undefined = [];
// If it's a complete Abi Parameter
// e.g. {name: 'a', type: 'uint'}
if (isAbiParameterSchema(abi)) {
abiType = abi.type;
abiName = abi.name;
abiComponents = abi.components as FullValidationSchema;
// If its short form string value e.g. ['uint']
} else if (typeof abi === 'string') {
abiType = abi;
abiName = `${level}/${index}`;
// If it's provided in short form of tuple e.g. [['uint', 'string']]
} else if (Array.isArray(abi)) {
// If its custom tuple e.g. ['tuple[2]', ['uint', 'string']]
if (
abi[0] &&
typeof abi[0] === 'string' &&
abi[0].startsWith('tuple') &&
!Array.isArray(abi[0]) &&
abi[1] &&
Array.isArray(abi[1])
) {
// eslint-disable-next-line prefer-destructuring
abiType = abi[0];
abiName = `${level}/${index}`;
abiComponents = abi[1] as ReadonlyArray<ShortValidationSchema>;
} else {
abiType = 'tuple';
abiName = `${level}/${index}`;
abiComponents = abi;
}
}
const { baseType, isArray, arraySizes } = parseBaseType(abiType);
let childSchema: JsonSchema;
let lastSchema = schema;
for (let i = arraySizes.length - 1; i > 0; i -= 1) {
childSchema = {
type: 'array',
items: [],
maxItems: arraySizes[i],
minItems: arraySizes[i],
};
if (arraySizes[i] < 0) {
delete childSchema.maxItems;
delete childSchema.minItems;
}
lastSchema.items = childSchema;
lastSchema = childSchema;
}
if (baseType === 'tuple' && !isArray) {
const nestedTuple = abiSchemaToJsonSchema(abiComponents, abiName);
nestedTuple.$id = abiName;
(lastSchema.items as JsonSchema[]).push(nestedTuple);
} else if (baseType === 'tuple' && isArray) {
const arraySize = arraySizes[0];
const item: JsonSchema = {
$id: abiName,
type: 'array',
items: abiSchemaToJsonSchema(abiComponents, abiName),
maxItems: arraySize,
minItems: arraySize,
};
if (arraySize < 0) {
delete item.maxItems;
delete item.minItems;
}
(lastSchema.items as JsonSchema[]).push(item);
} else if (isArray) {
const arraySize = arraySizes[0];
const item: JsonSchema = {
type: 'array',
$id: abiName,
items: convertEthType(String(baseType)),
minItems: arraySize,
maxItems: arraySize,
};
if (arraySize < 0) {
delete item.maxItems;
delete item.minItems;
}
(lastSchema.items as JsonSchema[]).push(item);
} else if (Array.isArray(lastSchema.items)) {
// Array of non-tuple items
lastSchema.items.push({ $id: abiName, ...convertEthType(abiType) });
} else {
// Nested object
((lastSchema.items as JsonSchema).items as JsonSchema[]).push({
$id: abiName,
...convertEthType(abiType),
});
}
}
return schema;
};
export const ethAbiToJsonSchema = (abis: ValidationSchemaInput) => abiSchemaToJsonSchema(abis);
export const fetchArrayElement = (data: Array<unknown>, level: number): unknown => {
if (level === 1) {
return data;
}
return fetchArrayElement(data[0] as Array<unknown>, level - 1);
};
export const transformJsonDataToAbiFormat = (
abis: FullValidationSchema,
data: ReadonlyArray<unknown> | Record<string, unknown>,
transformedData?: Array<unknown>,
): Array<unknown> => {
const newData: Array<unknown> = [];
for (const [index, abi] of abis.entries()) {
// eslint-disable-next-line no-nested-ternary
let abiType!: string;
let abiName!: string;
let abiComponents: ShortValidationSchema | FullValidationSchema | undefined = [];
// If it's a complete Abi Parameter
// e.g. {name: 'a', type: 'uint'}
if (isAbiParameterSchema(abi)) {
abiType = abi.type;
abiName = abi.name;
abiComponents = abi.components as FullValidationSchema;
// If its short form string value e.g. ['uint']
} else if (typeof abi === 'string') {
abiType = abi;
// If it's provided in short form of tuple e.g. [['uint', 'string']]
} else if (Array.isArray(abi)) {
// If its custom tuple e.g. ['tuple[2]', ['uint', 'string']]
if (abi[1] && Array.isArray(abi[1])) {
abiType = abi[0] as string;
abiComponents = abi[1] as ReadonlyArray<ShortValidationSchema>;
} else {
abiType = 'tuple';
abiComponents = abi;
}
}
const { baseType, isArray, arraySizes } = parseBaseType(abiType);
const dataItem = Array.isArray(data)
? (data as Array<unknown>)[index]
: (data as Record<string, unknown>)[abiName];
if (baseType === 'tuple' && !isArray) {
newData.push(
transformJsonDataToAbiFormat(
abiComponents as FullValidationSchema,
dataItem as Array<unknown>,
transformedData,
),
);
} else if (baseType === 'tuple' && isArray) {
const tupleData = [];
for (const tupleItem of dataItem as Array<unknown>) {
// Nested array
if (arraySizes.length > 1) {
const nestedItems = fetchArrayElement(
tupleItem as Array<unknown>,
arraySizes.length - 1,
);
const nestedData = [];
for (const nestedItem of nestedItems as Array<unknown>) {
nestedData.push(
transformJsonDataToAbiFormat(
abiComponents as FullValidationSchema,
nestedItem as Array<unknown>,
transformedData,
),
);
}
tupleData.push(nestedData);
} else {
tupleData.push(
transformJsonDataToAbiFormat(
abiComponents as FullValidationSchema,
tupleItem as Array<unknown>,
transformedData,
),
);
}
}
newData.push(tupleData);
} else {
newData.push(dataItem);
}
}
// Have to reassign before pushing to transformedData
// eslint-disable-next-line no-param-reassign
transformedData = transformedData ?? [];
transformedData.push(...newData);
return transformedData;
};
/**
* Code points to int
*/
export const codePointToInt = (codePoint: number): number => {
if (codePoint >= 48 && codePoint <= 57) {
/* ['0'..'9'] -> [0..9] */
return codePoint - 48;
}
if (codePoint >= 65 && codePoint <= 70) {
/* ['A'..'F'] -> [10..15] */
return codePoint - 55;
}
if (codePoint >= 97 && codePoint <= 102) {
/* ['a'..'f'] -> [10..15] */
return codePoint - 87;
}
throw new Error(`Invalid code point: ${codePoint}`);
};
/**
* Converts value to it's number representation
*/
export const hexToNumber = (value: string): bigint | number => {
if (!isHexStrict(value)) {
throw new Error('Invalid hex string');
}
const [negative, hexValue] = value.startsWith('-') ? [true, value.slice(1)] : [false, value];
const num = BigInt(hexValue);
if (num > Number.MAX_SAFE_INTEGER) {
return negative ? -num : num;
}
if (num < Number.MIN_SAFE_INTEGER) {
return num;
}
return negative ? -1 * Number(num) : Number(num);
};
/**
* Converts value to it's hex representation
*/
export const numberToHex = (value: ValidInputTypes): string => {
if ((typeof value === 'number' || typeof value === 'bigint') && value < 0) {
return `-0x${value.toString(16).slice(1)}`;
}
if ((typeof value === 'number' || typeof value === 'bigint') && value >= 0) {
return `0x${value.toString(16)}`;
}
if (typeof value === 'string' && isHexStrict(value)) {
const [negative, hex] = value.startsWith('-') ? [true, value.slice(1)] : [false, value];
const hexValue = hex.split(/^(-)?0(x|X)/).slice(-1)[0];
return `${negative ? '-' : ''}0x${hexValue.replace(/^0+/, '').toLowerCase()}`;
}
if (typeof value === 'string' && !isHexStrict(value)) {
return numberToHex(BigInt(value));
}
throw new InvalidNumberError(value);
};
/**
* Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string.
*/
export const padLeft = (value: ValidInputTypes, characterAmount: number, sign = '0'): string => {
if (typeof value === 'string' && !isHexStrict(value)) {
return value.padStart(characterAmount, sign);
}
const hex = typeof value === 'string' && isHexStrict(value) ? value : numberToHex(value);
const [prefix, hexValue] = hex.startsWith('-') ? ['-0x', hex.slice(3)] : ['0x', hex.slice(2)];
return `${prefix}${hexValue.padStart(characterAmount, sign)}`;
};
export function uint8ArrayToHexString(uint8Array: Uint8Array): string {
let hexString = '0x';
for (const e of uint8Array) {
const hex = e.toString(16);
hexString += hex.length === 1 ? `0${hex}` : hex;
}
return hexString;
}
export function hexToUint8Array(hex: string): Uint8Array {
let value;
if (hex.toLowerCase().startsWith('0x')) {
value = hex.slice(2);
} else {
value = hex;
}
if (value.length % 2 !== 0) {
throw new InvalidBytesError(`hex string has odd length: ${hex}`);
}
const bytes = new Uint8Array(Math.ceil(value.length / 2));
for (let i = 0; i < bytes.length; i += 1) {
const byte = parseInt(value.substring(i * 2, i * 2 + 2), 16);
bytes[i] = byte;
}
return bytes;
}