This repository has been archived by the owner on Jun 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 56
/
useDexTokenList.ts
60 lines (55 loc) 路 2 KB
/
useDexTokenList.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
import { TokenInfo, TokenList } from '@uniswap/token-lists';
import isEqual from 'lodash.isequal';
import { useQuery } from 'react-query';
import { useBlockNumberContext } from '~~/context';
import { mergeDefaultUpdateOptions, processQueryOptions, TRequiredKeys } from '~~/functions';
import { useEthersUpdater } from '~~/hooks/useEthersUpdater';
import { THookResult, TUpdateOptions } from '~~/models';
import { keyNamespace } from '~~/models/constants';
const queryKey: TRequiredKeys = { namespace: keyNamespace.signer, key: 'useDexTokenList' } as const;
/**
* #### Summary
* Gets a tokenlist from uniswap ipfs tokenlist
*
* ##### 鉁忥笍 Notes
* - you can also point it to another URI
*
* @category Hooks
*
* @param tokenListUri
* @param chainId optional, you can filter by a particular chainId
* @returns (TokenInfo[]) from '@uniswap/token-lists'
*/
export const useDexTokenList = (
tokenListUri: string = 'https://gateway.ipfs.io/ipns/tokens.uniswap.org',
chainId?: number,
options: TUpdateOptions = mergeDefaultUpdateOptions()
): THookResult<TokenInfo[]> => {
const keys = [{ ...queryKey }, { tokenListUri, chainId }] as const;
const { data, refetch, status } = useQuery(
keys,
async (keys): Promise<TokenInfo[]> => {
const { tokenListUri, chainId } = keys.queryKey[1];
let tokenInfo: TokenInfo[] = [];
const response = await fetch(tokenListUri);
const tokenList: TokenList = (await response.json()) as TokenList;
if (tokenList != null) {
if (chainId) {
tokenInfo = tokenList.tokens.filter((t: TokenInfo) => {
return t.chainId === chainId;
});
} else {
tokenInfo = tokenList.tokens;
}
}
return tokenInfo;
},
{
...processQueryOptions<TokenInfo[]>(options),
isDataEqual: (oldResult, newResult) => isEqual(oldResult, newResult),
}
);
const blockNumber = useBlockNumberContext();
useEthersUpdater(refetch, blockNumber, options);
return [data ?? [], refetch, status];
};