UNPKG

coingecko-tokens

Version:

Aggregated list of Token Lists from CoinGecko

64 lines (63 loc) 2.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.tokenValidator = exports.tokenListValidator = exports.ethers = void 0; exports.rebuildTokenList = rebuildTokenList; exports.getTokenList = getTokenList; const ethers_1 = require("ethers"); const token_lists_1 = require("@uniswap/token-lists"); const ajv_1 = require("./ajv"); exports.ethers = globalThis?.ethers || ethers_1.ethers; exports.tokenListValidator = ajv_1.ajv.compile(token_lists_1.schema); exports.tokenValidator = (() => { const tokenSchema = JSON.parse(JSON.stringify(token_lists_1.schema)); delete tokenSchema.type; delete tokenSchema.properties; delete tokenSchema.required; tokenSchema['$id'] = 'Uniswap Token Schema'; tokenSchema['$ref'] = '#/definitions/TokenInfo'; return ajv_1.ajv.compile(tokenSchema); })(); // Rebuild tokenlist in case if remote list is incorrect ( in case of coingecko ) async function rebuildTokenList(url, tokenList) { const newList = JSON.parse(JSON.stringify(tokenList)); if (newList.tokens.length > 1) { newList.tokens.length = 1; } if (!(0, exports.tokenListValidator)(newList)) { throw new Error(`${url} validation failed: ${JSON.stringify(exports.tokenListValidator.errors, null, 2)}`); } newList.tokens = tokenList.tokens // Filter out invalid token objects (sometimes happen with coingecko lists) .filter((token) => { return (0, exports.tokenValidator)(token); }) // Format token addresses to checksummed format .map((token) => { token.address = exports.ethers.getAddress(token.address); return token; }); // Double check list if (!(0, exports.tokenListValidator)(newList)) { throw new Error(`${url} validation failed: ${JSON.stringify(exports.tokenListValidator.errors, null, 2)}`); } return newList; } // eslint-disable-next-line @typescript-eslint/no-explicit-any async function getTokenList(url, fetchParams) { const resp = await fetch(url, { ...(fetchParams || {}), method: 'GET', signal: fetchParams?.signal || AbortSignal.timeout(60 * 1000), }); if (!resp.ok) { throw new Error(resp.statusText); } const list = (await resp.json()); if (fetchParams?.rebuildList) { return rebuildTokenList(url, list); } if (!(0, exports.tokenListValidator)(list)) { throw new Error(`${url} validation failed: ${JSON.stringify(exports.tokenListValidator.errors, null, 2)}`); } return list; }