-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathuseFetchPopularTokens.ts
More file actions
116 lines (105 loc) · 3.57 KB
/
useFetchPopularTokens.ts
File metadata and controls
116 lines (105 loc) · 3.57 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import { useCallback, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import type { CaipChainId } from '@metamask/utils';
import { BridgeClientId, getClientHeaders } from '@metamask/bridge-controller';
import { BRIDGE_API_BASE_URL } from '../../../../constants/bridge';
import Engine from '../../../../core/Engine';
import { selectBasicFunctionalityEnabled } from '../../../../selectors/settings';
import { getBaseSemVerVersion } from '../../../../util/version';
import type { IncludeAsset, PopularToken } from '../types';
import {
cleanupExpiredEntries,
getCacheKey,
isCacheValid,
popularTokensCache,
setPopularTokensCache,
} from '../utils/cacheUtils';
export interface FetchPopularTokensParams {
chainIds: CaipChainId[];
includeAssets?: IncludeAsset[];
signal?: AbortSignal;
}
/**
* Lightweight fetcher hook for the Bridge `/getTokens/popular` endpoint.
* @returns A callback that performs the cached fetch for the supplied
*/
export const useFetchPopularTokens = () => {
const [bearerToken, setBearerToken] = useState<string | null>(null);
const isBasicFunctionalityEnabled = useSelector(
selectBasicFunctionalityEnabled,
);
useEffect(() => {
if (!isBasicFunctionalityEnabled) {
return;
}
Engine.context.AuthenticationController.getBearerToken()
.then((token) => {
setBearerToken(token);
})
.catch((error) => {
console.warn(
'Failed to get bearer token for /getTokens/popular',
error,
);
});
}, [isBasicFunctionalityEnabled]);
return useCallback(
async ({
chainIds,
includeAssets = [],
signal,
}: FetchPopularTokensParams): Promise<PopularToken[] | undefined> => {
cleanupExpiredEntries();
const cacheKey = getCacheKey(chainIds, includeAssets);
const cachedEntry = popularTokensCache.get(cacheKey);
if (cachedEntry && isCacheValid(cachedEntry)) {
return cachedEntry.data;
}
try {
const response = await fetch(
`${BRIDGE_API_BASE_URL}/getTokens/popular`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getClientHeaders({
clientId: BridgeClientId.MOBILE,
clientVersion: getBaseSemVerVersion(),
jwt: bearerToken ?? '',
}),
},
body: JSON.stringify({ chainIds, includeAssets }),
signal,
},
);
if (response.ok === false) {
console.error(
`Failed to fetch popular tokens with status ${response.status}`,
);
return undefined;
}
const popularAssetsResponse: PopularToken[] = await response.json();
const isValidTopLevelPayload = Array.isArray(popularAssetsResponse);
if (isValidTopLevelPayload && popularAssetsResponse.length > 0) {
// Cache only valid top-level API payloads so malformed responses do
// not suppress retries for the full cache TTL.
setPopularTokensCache({
includeAssets,
chainIds,
popularTokens: popularAssetsResponse,
});
return popularAssetsResponse;
}
return undefined;
} catch (error) {
// Ignore abort errors - request was intentionally cancelled
if (error instanceof Error && error.name === 'AbortError') {
return undefined;
}
console.error('Error fetching popular tokens:', error);
return undefined;
}
},
[bearerToken],
);
};