forked from Uniswap/interface
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetTokenList.ts
More file actions
69 lines (65 loc) · 2.34 KB
/
Copy pathgetTokenList.ts
File metadata and controls
69 lines (65 loc) · 2.34 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
62
63
64
65
66
67
68
69
import { TokenList } from '@uniswap/token-lists'
import schema from '@uniswap/token-lists/src/tokenlist.schema.json'
import Ajv from 'ajv'
import contenthashToUri from './contenthashToUri'
import { parseENSAddress } from './parseENSAddress'
import uriToHttp from './uriToHttp'
const tokenListValidator = new Ajv({ allErrors: true }).compile(schema)
/**
* Contains the logic for resolving a list URL to a validated token list
* @param listUrl list url
* @param resolveENSContentHash resolves an ens name to a contenthash
*/
export default async function getTokenList(
listUrl: string,
resolveENSContentHash: (ensName: string) => Promise<string>
): Promise<TokenList> {
const parsedENS = parseENSAddress(listUrl)
let urls: string[]
if (parsedENS) {
let contentHashUri
try {
contentHashUri = await resolveENSContentHash(parsedENS.ensName)
} catch (error) {
console.debug(`Failed to resolve ENS name: ${parsedENS.ensName}`, error)
throw new Error(`Failed to resolve ENS name: ${parsedENS.ensName}`)
}
let translatedUri
try {
translatedUri = contenthashToUri(contentHashUri)
} catch (error) {
console.debug('Failed to translate contenthash to URI', contentHashUri)
throw new Error(`Failed to translate contenthash to URI: ${contentHashUri}`)
}
urls = uriToHttp(`${translatedUri}${parsedENS.ensPath ?? ''}`)
} else {
urls = uriToHttp(listUrl)
}
for (let i = 0; i < urls.length; i++) {
const url = urls[i]
const isLast = i === urls.length - 1
let response
try {
response = await fetch(url)
} catch (error) {
console.debug('Failed to fetch list', listUrl, error)
if (isLast) throw new Error(`Failed to download list ${listUrl}`)
continue
}
if (!response.ok) {
if (isLast) throw new Error(`Failed to download list ${listUrl}`)
continue
}
const json = await response.json()
if (!tokenListValidator(json)) {
const validationErrors: string =
tokenListValidator.errors?.reduce<string>((memo, error) => {
const add = `${error.dataPath} ${error.message ?? ''}`
return memo.length > 0 ? `${memo}; ${add}` : `${add}`
}, '') ?? 'unknown error'
throw new Error(`Token list failed validation: ${validationErrors}`)
}
return json
}
throw new Error('Unrecognized list URL protocol.')
}