forked from Uniswap/interface
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidateTokenList.ts
More file actions
61 lines (55 loc) · 1.74 KB
/
Copy pathvalidateTokenList.ts
File metadata and controls
61 lines (55 loc) · 1.74 KB
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
import type { TokenInfo, TokenList } from '@uniswap/token-lists'
import type { ValidateFunction } from 'ajv'
enum ValidationSchema {
LIST = 'list',
TOKENS = 'tokens',
}
function getValidationErrors(validate: ValidateFunction | undefined): string {
return (
validate?.errors?.map((error) => [error.instancePath, error.message].filter(Boolean).join(' ')).join('; ') ??
'unknown error'
)
}
async function validate(schema: ValidationSchema, data: unknown): Promise<unknown> {
let validatorImport
switch (schema) {
case ValidationSchema.LIST:
validatorImport = import('utils/__generated__/validateTokenList')
break
case ValidationSchema.TOKENS:
validatorImport = import('utils/__generated__/validateTokens')
break
default:
throw new Error('No validation function specified for token list schema')
}
const [, validatorModule] = await Promise.all([import('ajv'), validatorImport])
const validator = (await validatorModule.default) as ValidateFunction
if (validator?.(data)) {
return data
}
throw new Error(getValidationErrors(validator))
}
/**
* Validates an array of tokens.
* @param json the TokenInfo[] to validate
*/
export async function validateTokens(json: TokenInfo[]): Promise<TokenInfo[]> {
try {
await validate(ValidationSchema.TOKENS, { tokens: json })
return json
} catch (error) {
throw new Error(`Tokens failed validation: ${error.message}`)
}
}
/**
* Validates a token list.
* @param json the TokenList to validate
*/
export async function validateTokenList(json: TokenList): Promise<TokenList> {
try {
await validate(ValidationSchema.LIST, json)
return json
} catch (error) {
throw new Error(`Token list failed validation: ${error.message}`)
}
}