@pancakeswap/token-lists 0.0.14 → 0.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,61 +1,44 @@
1
1
  /* eslint-disable no-continue */
2
2
  /* eslint-disable no-await-in-loop */
3
- import { TokenList, TokenInfo } from '@pancakeswap/token-lists'
4
3
  import uriToHttp from '@pancakeswap/utils/uriToHttp'
5
- import remove from 'lodash/remove'
6
- import Ajv from 'ajv'
7
4
  import schema from '../schema/pancakeswap.json'
8
-
9
- export const tokenListValidator = new Ajv({ allErrors: true }).compile(schema)
5
+ import { TokenList } from '../src/types'
10
6
 
11
7
  /**
12
8
  * Contains the logic for resolving a list URL to a validated token list
13
9
  * @param listUrl list url
14
10
  */
15
- export default async function getTokenList(listUrl: string): Promise<TokenList> {
11
+ export async function getTokenList(listUrl: string): Promise<TokenList | undefined> {
16
12
  const urls: string[] = uriToHttp(listUrl)
13
+ const { default: Ajv } = await import('ajv')
14
+ const validator = new Ajv({ allErrors: true }).compile(schema)
17
15
 
18
- for (let i = 0; i < urls.length; i++) {
19
- const url = urls[i]
20
- const isLast = i === urls.length - 1
21
- let response
16
+ for (const [i, url] of urls.entries()) {
22
17
  try {
23
- response = await fetch(url)
18
+ const json = await fetchJson(url)
19
+ if (!validator(json)) {
20
+ const preFilterErrors = validator.errors
21
+ json.tokens = json.tokens.filter((token: any) => validator({ ...json, tokens: [token] }))
22
+ if (!validator(json)) {
23
+ const errors = validator.errors
24
+ throw new Error(`Validation failed after filtering: ${JSON.stringify(errors)}`)
25
+ }
26
+ console.warn(`Pre-filter validation errors: ${JSON.stringify(preFilterErrors)}`)
27
+ }
28
+ return json as TokenList
24
29
  } catch (error) {
25
- console.error('Failed to fetch list', listUrl, error)
26
- if (isLast) throw new Error(`Failed to download list ${listUrl}`)
27
- continue
28
- }
30
+ // if (i === urls.length - 1) {
31
+ // throw new Error(`Failed to download list ${listUrl}`)
32
+ // }
29
33
 
30
- if (!response.ok) {
31
- if (isLast) throw new Error(`Failed to download list ${listUrl}`)
32
- continue
34
+ return undefined
33
35
  }
34
-
35
- const json = await response.json()
36
- if (!tokenListValidator(json)) {
37
- const preFilterValidationErrors: string =
38
- tokenListValidator.errors?.reduce<string>((memo, error) => {
39
- const add = `${(error as any).dataPath} ${error.message ?? ''}`
40
- return memo.length > 0 ? `${memo}; ${add}` : `${add}`
41
- }, '') ?? 'unknown error'
42
- if (json.tokens) {
43
- remove<TokenInfo>(json.tokens, (token) => {
44
- return !tokenListValidator({ ...json, tokens: [token] })
45
- })
46
- }
47
- if (!tokenListValidator(json)) {
48
- const validationErrors: string =
49
- tokenListValidator.errors?.reduce<string>((memo, error) => {
50
- const add = `${(error as any).dataPath} ${error.message ?? ''}`
51
- return memo.length > 0 ? `${memo}; ${add}` : `${add}`
52
- }, '') ?? 'unknown error'
53
- throw new Error(`Token list ${url} failed validation: ${validationErrors}`)
54
- } else {
55
- console.warn(`Token list ${url} validation failed before token filtering: ${preFilterValidationErrors}`)
56
- }
57
- }
58
- return json as TokenList
59
36
  }
60
37
  throw new Error('Unrecognized list URL protocol.')
61
38
  }
39
+
40
+ async function fetchJson(url: string): Promise<any> {
41
+ const res = await fetch(url)
42
+ if (!res.ok) throw new Error(`Failed to fetch: ${url}`)
43
+ return res.json()
44
+ }
@@ -4,8 +4,6 @@ import * as exports from './index'
4
4
  test('exports', () => {
5
5
  expect(Object.keys(exports)).toMatchInlineSnapshot(`
6
6
  [
7
- "NEW_LIST_STATE",
8
- "createTokenListReducer",
9
7
  "fetchTokenList",
10
8
  "addList",
11
9
  "removeList",
@@ -14,7 +12,12 @@ test('exports', () => {
14
12
  "acceptListUpdate",
15
13
  "rejectVersionUpdate",
16
14
  "updateListVersion",
15
+ "getTokenList",
16
+ "findTokenByAddress",
17
+ "findTokenBySymbol",
17
18
  "createListsAtom",
19
+ "NEW_LIST_STATE",
20
+ "createTokenListReducer",
18
21
  "useFetchListCallback",
19
22
  ]
20
23
  `)
package/react/index.ts CHANGED
@@ -1,4 +1,5 @@
1
- export * from './reducer'
2
1
  export * from './actions'
2
+ export * from './getTokenList'
3
3
  export * from './lists'
4
+ export * from './reducer'
4
5
  export { default as useFetchListCallback } from './useFetchListCallback'
package/react/lists.ts CHANGED
@@ -1,7 +1,10 @@
1
+ import { nanoid } from '@reduxjs/toolkit'
1
2
  import { atom, useAtom, useAtomValue } from 'jotai'
2
- import { atomWithStorage, loadable } from 'jotai/utils'
3
+ import { atomFamily, atomWithStorage, loadable } from 'jotai/utils'
3
4
  import { type AsyncStorage } from 'jotai/vanilla/utils/atomWithStorage'
4
5
  import localForage from 'localforage'
6
+ import { fetchTokenList } from './actions'
7
+ import { getTokenList } from './getTokenList'
5
8
  import { ListsState } from './reducer'
6
9
 
7
10
  // eslint-disable-next-line @typescript-eslint/no-empty-function
@@ -16,6 +19,26 @@ const noopStorage: AsyncStorage<any> = {
16
19
  // eslint-disable-next-line symbol-description
17
20
  const EMPTY = Symbol()
18
21
 
22
+ export function findTokenByAddress(state: ListsState, chainId: number, address: string) {
23
+ const urls = state.activeListUrls ?? Object.keys(state.byUrl)
24
+ for (const url of urls) {
25
+ const list = state.byUrl[url]?.current
26
+ const token = list?.tokens.find((t) => t.chainId === chainId && t.address.toLowerCase() === address.toLowerCase())
27
+ if (token) return token
28
+ }
29
+ return undefined
30
+ }
31
+
32
+ export function findTokenBySymbol(state: ListsState, chainId: number, symbol: string) {
33
+ const urls = state.activeListUrls ?? Object.keys(state.byUrl)
34
+ for (const url of urls) {
35
+ const list = state.byUrl[url]?.current
36
+ const token = list?.tokens.find((t) => t.chainId === chainId && t.symbol.toLowerCase() === symbol.toLowerCase())
37
+ if (token) return token
38
+ }
39
+ return undefined
40
+ }
41
+
19
42
  export const createListsAtom = (storeName: string, reducer: any, initialState: any) => {
20
43
  /**
21
44
  * Persist you redux state using IndexedDB
@@ -62,6 +85,32 @@ export const createListsAtom = (storeName: string, reducer: any, initialState: a
62
85
 
63
86
  const isReadyAtom = loadable(listsStorageAtom)
64
87
 
88
+ const tokenAtom = atomFamily((key: { chainId: number; address: string }) =>
89
+ atom((get) => findTokenByAddress(get(defaultStateAtom), key.chainId, key.address)),
90
+ )
91
+
92
+ const tokenBySymbolAtom = atomFamily((key: { chainId: number; symbol: string }) =>
93
+ atom((get) => findTokenBySymbol(get(defaultStateAtom), key.chainId, key.symbol)),
94
+ )
95
+
96
+ const fetchListAtom = atom<null, [string], Promise<void>>(null, async (get, set, url) => {
97
+ const state = get(defaultStateAtom)
98
+ const listState = state.byUrl[url]
99
+ if (listState?.current || listState?.loadingRequestId) {
100
+ return
101
+ }
102
+
103
+ const requestId = nanoid()
104
+ set(defaultStateAtom, fetchTokenList.pending({ url, requestId }))
105
+
106
+ try {
107
+ const tokenList = await getTokenList(url)
108
+ set(defaultStateAtom, fetchTokenList.fulfilled({ url, tokenList: tokenList!, requestId }))
109
+ } catch (error: any) {
110
+ set(defaultStateAtom, fetchTokenList.rejected({ url, requestId, errorMessage: error.message }))
111
+ }
112
+ })
113
+
65
114
  function useListState() {
66
115
  return useAtom(defaultStateAtom)
67
116
  }
@@ -73,6 +122,9 @@ export const createListsAtom = (storeName: string, reducer: any, initialState: a
73
122
 
74
123
  return {
75
124
  listsAtom: defaultStateAtom,
125
+ tokenAtom,
126
+ tokenBySymbolAtom,
127
+ fetchListAtom,
76
128
  useListStateReady,
77
129
  useListState,
78
130
  }
@@ -1,7 +1,8 @@
1
1
  import { nanoid } from '@reduxjs/toolkit'
2
2
  import { useCallback } from 'react'
3
- import { fetchTokenList } from './actions'
4
3
  import { TokenList } from '../src/types'
4
+ import { fetchTokenList } from './actions'
5
+ import { getTokenList } from './getTokenList'
5
6
 
6
7
  function useFetchListCallback(
7
8
  dispatch: (action?: unknown) => void,
@@ -13,10 +14,12 @@ function useFetchListCallback(
13
14
  if (sendDispatch) {
14
15
  dispatch(fetchTokenList.pending({ requestId, url: listUrl }))
15
16
  }
16
- // lazy load avj and token list schema
17
- const getTokenList = (await import('./getTokenList')).default
18
17
  return getTokenList(listUrl)
19
18
  .then((tokenList) => {
19
+ if (!tokenList) {
20
+ throw new Error('Token list not found')
21
+ }
22
+
20
23
  if (sendDispatch) {
21
24
  dispatch(fetchTokenList.fulfilled({ url: listUrl, tokenList, requestId }))
22
25
  }
@@ -1,41 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __spreadValues = (a, b) => {
9
- for (var prop in b || (b = {}))
10
- if (__hasOwnProp.call(b, prop))
11
- __defNormalProp(a, prop, b[prop]);
12
- if (__getOwnPropSymbols)
13
- for (var prop of __getOwnPropSymbols(b)) {
14
- if (__propIsEnum.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- }
17
- return a;
18
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __async = (__this, __arguments, generator) => {
21
- return new Promise((resolve, reject) => {
22
- var fulfilled = (value) => {
23
- try {
24
- step(generator.next(value));
25
- } catch (e) {
26
- reject(e);
27
- }
28
- };
29
- var rejected = (value) => {
30
- try {
31
- step(generator.throw(value));
32
- } catch (e) {
33
- reject(e);
34
- }
35
- };
36
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
- step((generator = generator.apply(__this, __arguments)).next());
38
- });
39
- };
40
-
41
- export { __async, __spreadProps, __spreadValues };
@@ -1,45 +0,0 @@
1
- 'use strict';
2
-
3
- var __defProp = Object.defineProperty;
4
- var __defProps = Object.defineProperties;
5
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
9
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
- var __spreadValues = (a, b) => {
11
- for (var prop in b || (b = {}))
12
- if (__hasOwnProp.call(b, prop))
13
- __defNormalProp(a, prop, b[prop]);
14
- if (__getOwnPropSymbols)
15
- for (var prop of __getOwnPropSymbols(b)) {
16
- if (__propIsEnum.call(b, prop))
17
- __defNormalProp(a, prop, b[prop]);
18
- }
19
- return a;
20
- };
21
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
22
- var __async = (__this, __arguments, generator) => {
23
- return new Promise((resolve, reject) => {
24
- var fulfilled = (value) => {
25
- try {
26
- step(generator.next(value));
27
- } catch (e) {
28
- reject(e);
29
- }
30
- };
31
- var rejected = (value) => {
32
- try {
33
- step(generator.throw(value));
34
- } catch (e) {
35
- reject(e);
36
- }
37
- };
38
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
39
- step((generator = generator.apply(__this, __arguments)).next());
40
- });
41
- };
42
-
43
- exports.__async = __async;
44
- exports.__spreadProps = __spreadProps;
45
- exports.__spreadValues = __spreadValues;