@metamask/assets-controllers 86.0.0 → 87.1.0
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.
- package/CHANGELOG.md +32 -1
- package/dist/DeFiPositionsController/DeFiPositionsController.cjs +25 -36
- package/dist/DeFiPositionsController/DeFiPositionsController.cjs.map +1 -1
- package/dist/DeFiPositionsController/DeFiPositionsController.d.cts +3 -4
- package/dist/DeFiPositionsController/DeFiPositionsController.d.cts.map +1 -1
- package/dist/DeFiPositionsController/DeFiPositionsController.d.mts +3 -4
- package/dist/DeFiPositionsController/DeFiPositionsController.d.mts.map +1 -1
- package/dist/DeFiPositionsController/DeFiPositionsController.mjs +25 -36
- package/dist/DeFiPositionsController/DeFiPositionsController.mjs.map +1 -1
- package/dist/DeFiPositionsController/fetch-positions.cjs +4 -1
- package/dist/DeFiPositionsController/fetch-positions.cjs.map +1 -1
- package/dist/DeFiPositionsController/fetch-positions.d.cts.map +1 -1
- package/dist/DeFiPositionsController/fetch-positions.d.mts.map +1 -1
- package/dist/DeFiPositionsController/fetch-positions.mjs +4 -1
- package/dist/DeFiPositionsController/fetch-positions.mjs.map +1 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.cjs +58 -0
- package/dist/MultichainAssetsController/MultichainAssetsController.cjs.map +1 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.d.cts +15 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.d.cts.map +1 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.d.mts +15 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.d.mts.map +1 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.mjs +58 -0
- package/dist/MultichainAssetsController/MultichainAssetsController.mjs.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.cjs +8 -0
- package/dist/MultichainBalancesController/MultichainBalancesController.cjs.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.d.cts.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.d.mts.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.mjs +8 -0
- package/dist/MultichainBalancesController/MultichainBalancesController.mjs.map +1 -1
- package/dist/TokensController.cjs +3 -3
- package/dist/TokensController.cjs.map +1 -1
- package/dist/TokensController.d.cts.map +1 -1
- package/dist/TokensController.d.mts.map +1 -1
- package/dist/TokensController.mjs +3 -3
- package/dist/TokensController.mjs.map +1 -1
- package/dist/index.cjs +2 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +3 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/selectors/token-selectors.cjs +1 -6
- package/dist/selectors/token-selectors.cjs.map +1 -1
- package/dist/selectors/token-selectors.d.cts +1 -1
- package/dist/selectors/token-selectors.d.cts.map +1 -1
- package/dist/selectors/token-selectors.d.mts +1 -1
- package/dist/selectors/token-selectors.d.mts.map +1 -1
- package/dist/selectors/token-selectors.mjs +1 -6
- package/dist/selectors/token-selectors.mjs.map +1 -1
- package/dist/token-service.cjs +72 -9
- package/dist/token-service.cjs.map +1 -1
- package/dist/token-service.d.cts +48 -0
- package/dist/token-service.d.cts.map +1 -1
- package/dist/token-service.d.mts +48 -0
- package/dist/token-service.d.mts.map +1 -1
- package/dist/token-service.mjs +70 -8
- package/dist/token-service.mjs.map +1 -1
- package/dist/utils/timeout-with-retry.cjs +34 -0
- package/dist/utils/timeout-with-retry.cjs.map +1 -0
- package/dist/utils/timeout-with-retry.d.cts +9 -0
- package/dist/utils/timeout-with-retry.d.cts.map +1 -0
- package/dist/utils/timeout-with-retry.d.mts +9 -0
- package/dist/utils/timeout-with-retry.d.mts.map +1 -0
- package/dist/utils/timeout-with-retry.mjs +30 -0
- package/dist/utils/timeout-with-retry.mjs.map +1 -0
- package/package.json +4 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token-service.d.cts","sourceRoot":"","sources":["../src/token-service.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,WAAW,EAAE,GAAG,EAAE,wBAAwB;AAIxD,eAAO,MAAM,mBAAmB,qCAAqC,CAAC;AACtE,eAAO,MAAM,+BAA+B,oEACuB,CAAC;
|
|
1
|
+
{"version":3,"file":"token-service.d.cts","sourceRoot":"","sources":["../src/token-service.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,WAAW,EAAE,GAAG,EAAE,wBAAwB;AAIxD,eAAO,MAAM,mBAAmB,qCAAqC,CAAC;AACtE,eAAO,MAAM,+BAA+B,oEACuB,CAAC;AA6BpE;;GAEG;AACH,MAAM,MAAM,cAAc,GACtB,aAAa,GACb,aAAa,GACb,aAAa,GACb,cAAc,CAAC;AA6DnB;;;;;;;;;GASG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,GAAG,EACZ,WAAW,EAAE,WAAW,EACxB,EAAE,OAAwB,EAAE;;CAAK,GAChC,OAAO,CAAC,OAAO,CAAC,CAclB;AAED;;;;;;;;GAQG;AACH,wBAAsB,YAAY,CAChC,QAAQ,EAAE,WAAW,EAAE,EACvB,KAAK,EAAE,MAAM,EACb,EAAE,KAAU,EAAE;;CAAK,GAClB,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,EAAE,CAAA;CAAE,CAAC,CAyB7C;AAED;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,mBAAmB,EAAE,MAAM,CAAC;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE;QACf,EAAE,CAAC,EAAE,MAAM,CAAC;QACZ,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,EAAE,CAAC,EAAE,MAAM,CAAC;QACZ,EAAE,CAAC,EAAE,MAAM,CAAC;QACZ,GAAG,CAAC,EAAE,MAAM,CAAC;KACd,CAAC;IACF,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;CACnB,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,wBAAsB,iBAAiB,CAAC,EACtC,QAAQ,EACR,MAAM,EACN,YAAY,EACZ,eAAe,EACf,eAAe,EACf,YAAY,EACZ,YAAY,GACb,EAAE;IACD,QAAQ,EAAE,WAAW,EAAE,CAAC;IACxB,MAAM,CAAC,EAAE,cAAc,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC,CA+B3B;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,kBAAkB,CAAC,CAAC,EACxC,OAAO,EAAE,GAAG,EACZ,YAAY,EAAE,MAAM,EACpB,WAAW,EAAE,WAAW,EACxB,EAAE,OAAwB,EAAE;;CAAK,GAChC,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAUxB"}
|
package/dist/token-service.d.mts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import type { CaipChainId, Hex } from "@metamask/utils";
|
|
2
2
|
export declare const TOKEN_END_POINT_API = "https://token.api.cx.metamask.io";
|
|
3
3
|
export declare const TOKEN_METADATA_NO_SUPPORT_ERROR = "TokenService Error: Network does not support fetchTokenMetadata";
|
|
4
|
+
/**
|
|
5
|
+
* The sort by field for trending tokens.
|
|
6
|
+
*/
|
|
7
|
+
export type SortTrendingBy = 'm5_trending' | 'h1_trending' | 'h6_trending' | 'h24_trending';
|
|
4
8
|
/**
|
|
5
9
|
* Fetch the list of token metadata for a given network. This request is cancellable using the
|
|
6
10
|
* abort signal passed in.
|
|
@@ -29,6 +33,50 @@ export declare function searchTokens(chainIds: CaipChainId[], query: string, { l
|
|
|
29
33
|
count: number;
|
|
30
34
|
data: unknown[];
|
|
31
35
|
}>;
|
|
36
|
+
/**
|
|
37
|
+
* The trending asset type.
|
|
38
|
+
*/
|
|
39
|
+
export type TrendingAsset = {
|
|
40
|
+
assetId: string;
|
|
41
|
+
name: string;
|
|
42
|
+
symbol: string;
|
|
43
|
+
decimals: number;
|
|
44
|
+
price: string;
|
|
45
|
+
aggregatedUsdVolume: number;
|
|
46
|
+
marketCap: number;
|
|
47
|
+
priceChangePct?: {
|
|
48
|
+
m5?: string;
|
|
49
|
+
m15?: string;
|
|
50
|
+
m30?: string;
|
|
51
|
+
h1?: string;
|
|
52
|
+
h6?: string;
|
|
53
|
+
h24?: string;
|
|
54
|
+
};
|
|
55
|
+
labels?: string[];
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Get the trending tokens for the given chains.
|
|
59
|
+
*
|
|
60
|
+
* @param options - Options for getting trending tokens.
|
|
61
|
+
* @param options.chainIds - The chains to get the trending tokens for.
|
|
62
|
+
* @param options.sortBy - The sort by field.
|
|
63
|
+
* @param options.minLiquidity - The minimum liquidity.
|
|
64
|
+
* @param options.minVolume24hUsd - The minimum volume 24h in USD.
|
|
65
|
+
* @param options.maxVolume24hUsd - The maximum volume 24h in USD.
|
|
66
|
+
* @param options.minMarketCap - The minimum market cap.
|
|
67
|
+
* @param options.maxMarketCap - The maximum market cap.
|
|
68
|
+
* @returns The trending tokens.
|
|
69
|
+
* @throws Will throw if the request fails.
|
|
70
|
+
*/
|
|
71
|
+
export declare function getTrendingTokens({ chainIds, sortBy, minLiquidity, minVolume24hUsd, maxVolume24hUsd, minMarketCap, maxMarketCap, }: {
|
|
72
|
+
chainIds: CaipChainId[];
|
|
73
|
+
sortBy?: SortTrendingBy;
|
|
74
|
+
minLiquidity?: number;
|
|
75
|
+
minVolume24hUsd?: number;
|
|
76
|
+
maxVolume24hUsd?: number;
|
|
77
|
+
minMarketCap?: number;
|
|
78
|
+
maxMarketCap?: number;
|
|
79
|
+
}): Promise<TrendingAsset[]>;
|
|
32
80
|
/**
|
|
33
81
|
* Fetch metadata for the token address provided for a given network. This request is cancellable
|
|
34
82
|
* using the abort signal passed in.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token-service.d.mts","sourceRoot":"","sources":["../src/token-service.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,WAAW,EAAE,GAAG,EAAE,wBAAwB;AAIxD,eAAO,MAAM,mBAAmB,qCAAqC,CAAC;AACtE,eAAO,MAAM,+BAA+B,oEACuB,CAAC;
|
|
1
|
+
{"version":3,"file":"token-service.d.mts","sourceRoot":"","sources":["../src/token-service.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,WAAW,EAAE,GAAG,EAAE,wBAAwB;AAIxD,eAAO,MAAM,mBAAmB,qCAAqC,CAAC;AACtE,eAAO,MAAM,+BAA+B,oEACuB,CAAC;AA6BpE;;GAEG;AACH,MAAM,MAAM,cAAc,GACtB,aAAa,GACb,aAAa,GACb,aAAa,GACb,cAAc,CAAC;AA6DnB;;;;;;;;;GASG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,GAAG,EACZ,WAAW,EAAE,WAAW,EACxB,EAAE,OAAwB,EAAE;;CAAK,GAChC,OAAO,CAAC,OAAO,CAAC,CAclB;AAED;;;;;;;;GAQG;AACH,wBAAsB,YAAY,CAChC,QAAQ,EAAE,WAAW,EAAE,EACvB,KAAK,EAAE,MAAM,EACb,EAAE,KAAU,EAAE;;CAAK,GAClB,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,EAAE,CAAA;CAAE,CAAC,CAyB7C;AAED;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG;IA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A_NO_SUPPORT_ERROR = 'TokenService Error: Network does
|
|
|
10
10
|
*/
|
|
11
11
|
function getTokensURL(chainId) {
|
|
12
12
|
const occurrenceFloor = chainId === ChainId['linea-mainnet'] ? 1 : 3;
|
|
13
|
-
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
14
|
-
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
15
13
|
return `${TOKEN_END_POINT_API}/tokens/${convertHexToDecimal(chainId)}?occurrenceFloor=${occurrenceFloor}&includeNativeAssets=false&includeTokenFees=false&includeAssetType=false&includeERC20Permit=false&includeStorage=false`;
|
|
16
14
|
}
|
|
17
15
|
/**
|
|
@@ -22,8 +20,6 @@ function getTokensURL(chainId) {
|
|
|
22
20
|
* @returns The token metadata URL.
|
|
23
21
|
*/
|
|
24
22
|
function getTokenMetadataURL(chainId, tokenAddress) {
|
|
25
|
-
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
26
|
-
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
27
23
|
return `${TOKEN_END_POINT_API}/token/${convertHexToDecimal(chainId)}?address=${tokenAddress}`;
|
|
28
24
|
}
|
|
29
25
|
/**
|
|
@@ -41,6 +37,33 @@ function getTokenSearchURL(chainIds, query, limit = 10) {
|
|
|
41
37
|
.join(',');
|
|
42
38
|
return `${TOKEN_END_POINT_API}/tokens/search?chainIds=${encodedChainIds}&query=${encodedQuery}&limit=${limit}`;
|
|
43
39
|
}
|
|
40
|
+
/**
|
|
41
|
+
* Get the trending tokens URL for the given networks and search query.
|
|
42
|
+
*
|
|
43
|
+
* @param options - Options for getting trending tokens.
|
|
44
|
+
* @param options.chainIds - Array of CAIP format chain IDs (e.g., ['eip155:1', 'eip155:137', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp']).
|
|
45
|
+
* @param options.sortBy - The sort by field.
|
|
46
|
+
* @param options.minLiquidity - The minimum liquidity.
|
|
47
|
+
* @param options.minVolume24hUsd - The minimum volume 24h in USD.
|
|
48
|
+
* @param options.maxVolume24hUsd - The maximum volume 24h in USD.
|
|
49
|
+
* @param options.minMarketCap - The minimum market cap.
|
|
50
|
+
* @param options.maxMarketCap - The maximum market cap.
|
|
51
|
+
* @returns The trending tokens URL.
|
|
52
|
+
*/
|
|
53
|
+
function getTrendingTokensURL(options) {
|
|
54
|
+
const encodedChainIds = options.chainIds
|
|
55
|
+
.map((id) => encodeURIComponent(id))
|
|
56
|
+
.join(',');
|
|
57
|
+
// Add the rest of query params if they are defined
|
|
58
|
+
const queryParams = new URLSearchParams();
|
|
59
|
+
const { chainIds, ...rest } = options;
|
|
60
|
+
Object.entries(rest).forEach(([key, value]) => {
|
|
61
|
+
if (value !== undefined) {
|
|
62
|
+
queryParams.append(key, String(value));
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
return `${TOKEN_END_POINT_API}/v3/tokens/trending?chainIds=${encodedChainIds}${queryParams.toString() ? `&${queryParams.toString()}` : ''}`;
|
|
66
|
+
}
|
|
44
67
|
const tenSecondsInMilliseconds = 10000;
|
|
45
68
|
// Token list averages 1.6 MB in size
|
|
46
69
|
// timeoutFetch by default has a 500ms timeout, which will almost always timeout given the response size.
|
|
@@ -99,6 +122,49 @@ export async function searchTokens(chainIds, query, { limit = 10 } = {}) {
|
|
|
99
122
|
return { count: 0, data: [] };
|
|
100
123
|
}
|
|
101
124
|
}
|
|
125
|
+
/**
|
|
126
|
+
* Get the trending tokens for the given chains.
|
|
127
|
+
*
|
|
128
|
+
* @param options - Options for getting trending tokens.
|
|
129
|
+
* @param options.chainIds - The chains to get the trending tokens for.
|
|
130
|
+
* @param options.sortBy - The sort by field.
|
|
131
|
+
* @param options.minLiquidity - The minimum liquidity.
|
|
132
|
+
* @param options.minVolume24hUsd - The minimum volume 24h in USD.
|
|
133
|
+
* @param options.maxVolume24hUsd - The maximum volume 24h in USD.
|
|
134
|
+
* @param options.minMarketCap - The minimum market cap.
|
|
135
|
+
* @param options.maxMarketCap - The maximum market cap.
|
|
136
|
+
* @returns The trending tokens.
|
|
137
|
+
* @throws Will throw if the request fails.
|
|
138
|
+
*/
|
|
139
|
+
export async function getTrendingTokens({ chainIds, sortBy, minLiquidity, minVolume24hUsd, maxVolume24hUsd, minMarketCap, maxMarketCap, }) {
|
|
140
|
+
if (chainIds.length === 0) {
|
|
141
|
+
console.error('No chains provided');
|
|
142
|
+
return [];
|
|
143
|
+
}
|
|
144
|
+
const trendingTokensURL = getTrendingTokensURL({
|
|
145
|
+
chainIds,
|
|
146
|
+
sortBy,
|
|
147
|
+
minLiquidity,
|
|
148
|
+
minVolume24hUsd,
|
|
149
|
+
maxVolume24hUsd,
|
|
150
|
+
minMarketCap,
|
|
151
|
+
maxMarketCap,
|
|
152
|
+
});
|
|
153
|
+
try {
|
|
154
|
+
const result = await handleFetch(trendingTokensURL);
|
|
155
|
+
// Validate that the API returned an array
|
|
156
|
+
if (Array.isArray(result)) {
|
|
157
|
+
return result;
|
|
158
|
+
}
|
|
159
|
+
// Handle non-expected responses
|
|
160
|
+
console.error('Trending tokens API returned non-array response:', result);
|
|
161
|
+
return [];
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
console.error('Trending tokens request failed:', error);
|
|
165
|
+
return [];
|
|
166
|
+
}
|
|
167
|
+
}
|
|
102
168
|
/**
|
|
103
169
|
* Fetch metadata for the token address provided for a given network. This request is cancellable
|
|
104
170
|
* using the abort signal passed in.
|
|
@@ -110,8 +176,6 @@ export async function searchTokens(chainIds, query, { limit = 10 } = {}) {
|
|
|
110
176
|
* @param options.timeout - The fetch timeout.
|
|
111
177
|
* @returns The token metadata, or `undefined` if the request was either aborted or failed.
|
|
112
178
|
*/
|
|
113
|
-
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
114
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
115
179
|
export async function fetchTokenMetadata(chainId, tokenAddress, abortSignal, { timeout = defaultTimeout } = {}) {
|
|
116
180
|
if (!isTokenListSupportedForNetwork(chainId)) {
|
|
117
181
|
throw new Error(TOKEN_METADATA_NO_SUPPORT_ERROR);
|
|
@@ -163,8 +227,6 @@ async function parseJsonResponse(apiResponse) {
|
|
|
163
227
|
const responseObj = await apiResponse.json();
|
|
164
228
|
// api may return errors as json without setting an error http status code
|
|
165
229
|
if (responseObj?.error) {
|
|
166
|
-
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
167
|
-
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
168
230
|
throw new Error(`TokenService Error: ${responseObj.error}`);
|
|
169
231
|
}
|
|
170
232
|
return responseObj;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token-service.mjs","sourceRoot":"","sources":["../src/token-service.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,WAAW,EACX,YAAY,EACb,mCAAmC;AAGpC,OAAO,EAAE,8BAA8B,EAAE,yBAAqB;AAE9D,MAAM,CAAC,MAAM,mBAAmB,GAAG,kCAAkC,CAAC;AACtE,MAAM,CAAC,MAAM,+BAA+B,GAC1C,iEAAiE,CAAC;AAEpE;;;;;GAKG;AACH,SAAS,YAAY,CAAC,OAAY;IAChC,MAAM,eAAe,GAAG,OAAO,KAAK,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACrE,gFAAgF;IAChF,4EAA4E;IAC5E,OAAO,GAAG,mBAAmB,WAAW,mBAAmB,CACzD,OAAO,CACR,oBAAoB,eAAe,wHAAwH,CAAC;AAC/J,CAAC;AAED;;;;;;GAMG;AACH,SAAS,mBAAmB,CAAC,OAAY,EAAE,YAAoB;IAC7D,gFAAgF;IAChF,4EAA4E;IAC5E,OAAO,GAAG,mBAAmB,UAAU,mBAAmB,CACxD,OAAO,CACR,YAAY,YAAY,EAAE,CAAC;AAC9B,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,iBAAiB,CAAC,QAAuB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handleFetch,\n timeoutFetch,\n} from '@metamask/controller-utils';\nimport type { CaipChainId, Hex } from '@metamask/utils';\n\nimport { isTokenListSupportedForNetwork } from './assetsUtil';\n\nexport const TOKEN_END_POINT_API = 'https://token.api.cx.metamask.io';\nexport const TOKEN_METADATA_NO_SUPPORT_ERROR =\n 'TokenService Error: Network does not support fetchTokenMetadata';\n\n/**\n * Get the tokens URL for a specific network.\n *\n * @param chainId - The chain ID of the network the tokens requested are on.\n * @returns The tokens URL.\n */\nfunction getTokensURL(chainId: Hex) {\n const occurrenceFloor = chainId === ChainId['linea-mainnet'] ? 1 : 3;\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n return `${TOKEN_END_POINT_API}/tokens/${convertHexToDecimal(\n chainId,\n )}?occurrenceFloor=${occurrenceFloor}&includeNativeAssets=false&includeTokenFees=false&includeAssetType=false&includeERC20Permit=false&includeStorage=false`;\n}\n\n/**\n * Get the token metadata URL for the given network and token.\n *\n * @param chainId - The chain ID of the network the token is on.\n * @param tokenAddress - The token address.\n * @returns The token metadata URL.\n */\nfunction getTokenMetadataURL(chainId: Hex, tokenAddress: string) {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n return `${TOKEN_END_POINT_API}/token/${convertHexToDecimal(\n chainId,\n )}?address=${tokenAddress}`;\n}\n\n/**\n * Get the token search URL for the given networks and search query.\n *\n * @param chainIds - Array of CAIP format chain IDs (e.g., 'eip155:1', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp').\n * @param query - The search query (token name, symbol, or address).\n * @param limit - Optional limit for the number of results (defaults to 10).\n * @returns The token search URL.\n */\nfunction getTokenSearchURL(chainIds: CaipChainId[], query: string, limit = 10) {\n const encodedQuery = encodeURIComponent(query);\n const encodedChainIds = chainIds\n .map((id) => encodeURIComponent(id))\n .join(',');\n return `${TOKEN_END_POINT_API}/tokens/search?chainIds=${encodedChainIds}&query=${encodedQuery}&limit=${limit}`;\n}\n\nconst tenSecondsInMilliseconds = 10_000;\n\n// Token list averages 1.6 MB in size\n// timeoutFetch by default has a 500ms timeout, which will almost always timeout given the response size.\nconst defaultTimeout = tenSecondsInMilliseconds;\n\n/**\n * Fetch the list of token metadata for a given network. This request is cancellable using the\n * abort signal passed in.\n *\n * @param chainId - The chain ID of the network the requested tokens are on.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param options - Additional fetch options.\n * @param options.timeout - The fetch timeout.\n * @returns The token list, or `undefined` if the request was cancelled.\n */\nexport async function fetchTokenListByChainId(\n chainId: Hex,\n abortSignal: AbortSignal,\n { timeout = defaultTimeout } = {},\n): Promise<unknown> {\n const tokenURL = getTokensURL(chainId);\n const response = await queryApi(tokenURL, abortSignal, timeout);\n if (response) {\n const result = await parseJsonResponse(response);\n if (Array.isArray(result) && chainId === ChainId['linea-mainnet']) {\n return result.filter(\n (elm) =>\n elm.aggregators.includes('lineaTeam') || elm.aggregators.length >= 3,\n );\n }\n return result;\n }\n return undefined;\n}\n\n/**\n * Search for tokens across one or more networks by query string using CAIP format chain IDs.\n *\n * @param chainIds - Array of CAIP format chain IDs (e.g., ['eip155:1', 'eip155:137', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp']).\n * @param query - The search query (token name, symbol, or address).\n * @param options - Additional fetch options.\n * @param options.limit - The maximum number of results to return.\n * @returns Object containing count and data array. Returns { count: 0, data: [] } if request fails.\n */\nexport async function searchTokens(\n chainIds: CaipChainId[],\n query: string,\n { limit = 10 } = {},\n): Promise<{ count: number; data: unknown[] }> {\n if (chainIds.length === 0) {\n return { count: 0, data: [] };\n }\n\n const tokenSearchURL = getTokenSearchURL(chainIds, query, limit);\n\n try {\n const result = await handleFetch(tokenSearchURL);\n\n // The API returns an object with structure: { count: number, data: array, pageInfo: object }\n if (result && typeof result === 'object' && Array.isArray(result.data)) {\n return {\n count: result.count || result.data.length,\n data: result.data,\n };\n }\n\n // Handle non-expected responses\n return { count: 0, data: [] };\n } catch (error) {\n // Handle 400 errors and other failures by returning count 0 and empty array\n console.log('Search request failed:', error);\n return { count: 0, data: [] };\n }\n}\n\n/**\n * Fetch metadata for the token address provided for a given network. This request is cancellable\n * using the abort signal passed in.\n *\n * @param chainId - The chain ID of the network the token is on.\n * @param tokenAddress - The address of the token to fetch metadata for.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param options - Additional fetch options.\n * @param options.timeout - The fetch timeout.\n * @returns The token metadata, or `undefined` if the request was either aborted or failed.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport async function fetchTokenMetadata<T>(\n chainId: Hex,\n tokenAddress: string,\n abortSignal: AbortSignal,\n { timeout = defaultTimeout } = {},\n): Promise<T | undefined> {\n if (!isTokenListSupportedForNetwork(chainId)) {\n throw new Error(TOKEN_METADATA_NO_SUPPORT_ERROR);\n }\n const tokenMetadataURL = getTokenMetadataURL(chainId, tokenAddress);\n const response = await queryApi(tokenMetadataURL, abortSignal, timeout);\n if (response) {\n return parseJsonResponse(response) as Promise<T>;\n }\n return undefined;\n}\n\n/**\n * Perform fetch request against the api.\n *\n * @param apiURL - The URL of the API to fetch.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param timeout - The fetch timeout.\n * @returns Promise resolving request response.\n */\nasync function queryApi(\n apiURL: string,\n abortSignal: AbortSignal,\n timeout: number,\n): Promise<Response | undefined> {\n const fetchOptions: RequestInit = {\n referrer: apiURL,\n referrerPolicy: 'no-referrer-when-downgrade',\n method: 'GET',\n mode: 'cors',\n signal: abortSignal,\n cache: 'default',\n };\n fetchOptions.headers = new window.Headers();\n fetchOptions.headers.set('Content-Type', 'application/json');\n try {\n return await timeoutFetch(apiURL, fetchOptions, timeout);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n console.log('Request is aborted');\n }\n }\n return undefined;\n}\n\n/**\n * Parse an API response and return the response JSON data.\n *\n * @param apiResponse - The API response to parse.\n * @returns The response JSON data.\n * @throws Will throw if the response includes an error.\n */\nasync function parseJsonResponse(apiResponse: Response): Promise<unknown> {\n const responseObj = await apiResponse.json();\n // api may return errors as json without setting an error http status code\n if (responseObj?.error) {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n throw new Error(`TokenService Error: ${responseObj.error}`);\n }\n return responseObj;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"token-service.mjs","sourceRoot":"","sources":["../src/token-service.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,WAAW,EACX,YAAY,EACb,mCAAmC;AAGpC,OAAO,EAAE,8BAA8B,EAAE,yBAAqB;AAE9D,MAAM,CAAC,MAAM,mBAAmB,GAAG,kCAAkC,CAAC;AACtE,MAAM,CAAC,MAAM,+BAA+B,GAC1C,iEAAiE,CAAC;AAEpE;;;;;GAKG;AACH,SAAS,YAAY,CAAC,OAAY;IAChC,MAAM,eAAe,GAAG,OAAO,KAAK,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAErE,OAAO,GAAG,mBAAmB,WAAW,mBAAmB,CACzD,OAAO,CACR,oBAAoB,eAAe,wHAAwH,CAAC;AAC/J,CAAC;AAED;;;;;;GAMG;AACH,SAAS,mBAAmB,CAAC,OAAY,EAAE,YAAoB;IAC7D,OAAO,GAAG,mBAAmB,UAAU,mBAAmB,CACxD,OAAO,CACR,YAAY,YAAY,EAAE,CAAC;AAC9B,CAAC;AAWD;;;;;;;GAOG;AACH,SAAS,iBAAiB,CAAC,QAAuB,EAAE,KAAa,EAAE,KAAK,GAAG,EAAE;IAC3E,MAAM,YAAY,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC/C,MAAM,eAAe,GAAG,QAAQ;SAC7B,GAAG,CAAC,CAAC,EAAE,EAAE,EA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M,IAAI,KAAK,CAAC,uBAAuB,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC;KAC7D;IACD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import {\n ChainId,\n convertHexToDecimal,\n handleFetch,\n timeoutFetch,\n} from '@metamask/controller-utils';\nimport type { CaipChainId, Hex } from '@metamask/utils';\n\nimport { isTokenListSupportedForNetwork } from './assetsUtil';\n\nexport const TOKEN_END_POINT_API = 'https://token.api.cx.metamask.io';\nexport const TOKEN_METADATA_NO_SUPPORT_ERROR =\n 'TokenService Error: Network does not support fetchTokenMetadata';\n\n/**\n * Get the tokens URL for a specific network.\n *\n * @param chainId - The chain ID of the network the tokens requested are on.\n * @returns The tokens URL.\n */\nfunction getTokensURL(chainId: Hex) {\n const occurrenceFloor = chainId === ChainId['linea-mainnet'] ? 1 : 3;\n\n return `${TOKEN_END_POINT_API}/tokens/${convertHexToDecimal(\n chainId,\n )}?occurrenceFloor=${occurrenceFloor}&includeNativeAssets=false&includeTokenFees=false&includeAssetType=false&includeERC20Permit=false&includeStorage=false`;\n}\n\n/**\n * Get the token metadata URL for the given network and token.\n *\n * @param chainId - The chain ID of the network the token is on.\n * @param tokenAddress - The token address.\n * @returns The token metadata URL.\n */\nfunction getTokenMetadataURL(chainId: Hex, tokenAddress: string) {\n return `${TOKEN_END_POINT_API}/token/${convertHexToDecimal(\n chainId,\n )}?address=${tokenAddress}`;\n}\n\n/**\n * The sort by field for trending tokens.\n */\nexport type SortTrendingBy =\n | 'm5_trending'\n | 'h1_trending'\n | 'h6_trending'\n | 'h24_trending';\n\n/**\n * Get the token search URL for the given networks and search query.\n *\n * @param chainIds - Array of CAIP format chain IDs (e.g., 'eip155:1', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp').\n * @param query - The search query (token name, symbol, or address).\n * @param limit - Optional limit for the number of results (defaults to 10).\n * @returns The token search URL.\n */\nfunction getTokenSearchURL(chainIds: CaipChainId[], query: string, limit = 10) {\n const encodedQuery = encodeURIComponent(query);\n const encodedChainIds = chainIds\n .map((id) => encodeURIComponent(id))\n .join(',');\n return `${TOKEN_END_POINT_API}/tokens/search?chainIds=${encodedChainIds}&query=${encodedQuery}&limit=${limit}`;\n}\n\n/**\n * Get the trending tokens URL for the given networks and search query.\n *\n * @param options - Options for getting trending tokens.\n * @param options.chainIds - Array of CAIP format chain IDs (e.g., ['eip155:1', 'eip155:137', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp']).\n * @param options.sortBy - The sort by field.\n * @param options.minLiquidity - The minimum liquidity.\n * @param options.minVolume24hUsd - The minimum volume 24h in USD.\n * @param options.maxVolume24hUsd - The maximum volume 24h in USD.\n * @param options.minMarketCap - The minimum market cap.\n * @param options.maxMarketCap - The maximum market cap.\n * @returns The trending tokens URL.\n */\nfunction getTrendingTokensURL(options: {\n chainIds: CaipChainId[];\n sortBy?: SortTrendingBy;\n minLiquidity?: number;\n minVolume24hUsd?: number;\n maxVolume24hUsd?: number;\n minMarketCap?: number;\n maxMarketCap?: number;\n}): string {\n const encodedChainIds = options.chainIds\n .map((id) => encodeURIComponent(id))\n .join(',');\n // Add the rest of query params if they are defined\n const queryParams = new URLSearchParams();\n const { chainIds, ...rest } = options;\n Object.entries(rest).forEach(([key, value]) => {\n if (value !== undefined) {\n queryParams.append(key, String(value));\n }\n });\n\n return `${TOKEN_END_POINT_API}/v3/tokens/trending?chainIds=${encodedChainIds}${queryParams.toString() ? `&${queryParams.toString()}` : ''}`;\n}\n\nconst tenSecondsInMilliseconds = 10_000;\n\n// Token list averages 1.6 MB in size\n// timeoutFetch by default has a 500ms timeout, which will almost always timeout given the response size.\nconst defaultTimeout = tenSecondsInMilliseconds;\n\n/**\n * Fetch the list of token metadata for a given network. This request is cancellable using the\n * abort signal passed in.\n *\n * @param chainId - The chain ID of the network the requested tokens are on.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param options - Additional fetch options.\n * @param options.timeout - The fetch timeout.\n * @returns The token list, or `undefined` if the request was cancelled.\n */\nexport async function fetchTokenListByChainId(\n chainId: Hex,\n abortSignal: AbortSignal,\n { timeout = defaultTimeout } = {},\n): Promise<unknown> {\n const tokenURL = getTokensURL(chainId);\n const response = await queryApi(tokenURL, abortSignal, timeout);\n if (response) {\n const result = await parseJsonResponse(response);\n if (Array.isArray(result) && chainId === ChainId['linea-mainnet']) {\n return result.filter(\n (elm) =>\n elm.aggregators.includes('lineaTeam') || elm.aggregators.length >= 3,\n );\n }\n return result;\n }\n return undefined;\n}\n\n/**\n * Search for tokens across one or more networks by query string using CAIP format chain IDs.\n *\n * @param chainIds - Array of CAIP format chain IDs (e.g., ['eip155:1', 'eip155:137', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp']).\n * @param query - The search query (token name, symbol, or address).\n * @param options - Additional fetch options.\n * @param options.limit - The maximum number of results to return.\n * @returns Object containing count and data array. Returns { count: 0, data: [] } if request fails.\n */\nexport async function searchTokens(\n chainIds: CaipChainId[],\n query: string,\n { limit = 10 } = {},\n): Promise<{ count: number; data: unknown[] }> {\n if (chainIds.length === 0) {\n return { count: 0, data: [] };\n }\n\n const tokenSearchURL = getTokenSearchURL(chainIds, query, limit);\n\n try {\n const result = await handleFetch(tokenSearchURL);\n\n // The API returns an object with structure: { count: number, data: array, pageInfo: object }\n if (result && typeof result === 'object' && Array.isArray(result.data)) {\n return {\n count: result.count || result.data.length,\n data: result.data,\n };\n }\n\n // Handle non-expected responses\n return { count: 0, data: [] };\n } catch (error) {\n // Handle 400 errors and other failures by returning count 0 and empty array\n console.log('Search request failed:', error);\n return { count: 0, data: [] };\n }\n}\n\n/**\n * The trending asset type.\n */\nexport type TrendingAsset = {\n assetId: string;\n name: string;\n symbol: string;\n decimals: number;\n price: string;\n aggregatedUsdVolume: number;\n marketCap: number;\n priceChangePct?: {\n m5?: string;\n m15?: string;\n m30?: string;\n h1?: string;\n h6?: string;\n h24?: string;\n };\n labels?: string[];\n};\n\n/**\n * Get the trending tokens for the given chains.\n *\n * @param options - Options for getting trending tokens.\n * @param options.chainIds - The chains to get the trending tokens for.\n * @param options.sortBy - The sort by field.\n * @param options.minLiquidity - The minimum liquidity.\n * @param options.minVolume24hUsd - The minimum volume 24h in USD.\n * @param options.maxVolume24hUsd - The maximum volume 24h in USD.\n * @param options.minMarketCap - The minimum market cap.\n * @param options.maxMarketCap - The maximum market cap.\n * @returns The trending tokens.\n * @throws Will throw if the request fails.\n */\nexport async function getTrendingTokens({\n chainIds,\n sortBy,\n minLiquidity,\n minVolume24hUsd,\n maxVolume24hUsd,\n minMarketCap,\n maxMarketCap,\n}: {\n chainIds: CaipChainId[];\n sortBy?: SortTrendingBy;\n minLiquidity?: number;\n minVolume24hUsd?: number;\n maxVolume24hUsd?: number;\n minMarketCap?: number;\n maxMarketCap?: number;\n}): Promise<TrendingAsset[]> {\n if (chainIds.length === 0) {\n console.error('No chains provided');\n return [];\n }\n\n const trendingTokensURL = getTrendingTokensURL({\n chainIds,\n sortBy,\n minLiquidity,\n minVolume24hUsd,\n maxVolume24hUsd,\n minMarketCap,\n maxMarketCap,\n });\n\n try {\n const result = await handleFetch(trendingTokensURL);\n\n // Validate that the API returned an array\n if (Array.isArray(result)) {\n return result;\n }\n\n // Handle non-expected responses\n console.error('Trending tokens API returned non-array response:', result);\n return [];\n } catch (error) {\n console.error('Trending tokens request failed:', error);\n return [];\n }\n}\n\n/**\n * Fetch metadata for the token address provided for a given network. This request is cancellable\n * using the abort signal passed in.\n *\n * @param chainId - The chain ID of the network the token is on.\n * @param tokenAddress - The address of the token to fetch metadata for.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param options - Additional fetch options.\n * @param options.timeout - The fetch timeout.\n * @returns The token metadata, or `undefined` if the request was either aborted or failed.\n */\nexport async function fetchTokenMetadata<T>(\n chainId: Hex,\n tokenAddress: string,\n abortSignal: AbortSignal,\n { timeout = defaultTimeout } = {},\n): Promise<T | undefined> {\n if (!isTokenListSupportedForNetwork(chainId)) {\n throw new Error(TOKEN_METADATA_NO_SUPPORT_ERROR);\n }\n const tokenMetadataURL = getTokenMetadataURL(chainId, tokenAddress);\n const response = await queryApi(tokenMetadataURL, abortSignal, timeout);\n if (response) {\n return parseJsonResponse(response) as Promise<T>;\n }\n return undefined;\n}\n\n/**\n * Perform fetch request against the api.\n *\n * @param apiURL - The URL of the API to fetch.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param timeout - The fetch timeout.\n * @returns Promise resolving request response.\n */\nasync function queryApi(\n apiURL: string,\n abortSignal: AbortSignal,\n timeout: number,\n): Promise<Response | undefined> {\n const fetchOptions: RequestInit = {\n referrer: apiURL,\n referrerPolicy: 'no-referrer-when-downgrade',\n method: 'GET',\n mode: 'cors',\n signal: abortSignal,\n cache: 'default',\n };\n fetchOptions.headers = new window.Headers();\n fetchOptions.headers.set('Content-Type', 'application/json');\n try {\n return await timeoutFetch(apiURL, fetchOptions, timeout);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n console.log('Request is aborted');\n }\n }\n return undefined;\n}\n\n/**\n * Parse an API response and return the response JSON data.\n *\n * @param apiResponse - The API response to parse.\n * @returns The response JSON data.\n * @throws Will throw if the response includes an error.\n */\nasync function parseJsonResponse(apiResponse: Response): Promise<unknown> {\n const responseObj = await apiResponse.json();\n // api may return errors as json without setting an error http status code\n if (responseObj?.error) {\n throw new Error(`TokenService Error: ${responseObj.error}`);\n }\n return responseObj;\n}\n"]}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.timeoutWithRetry = void 0;
|
|
4
|
+
const utils_1 = require("@metamask/utils");
|
|
5
|
+
const TIMEOUT_ERROR = new Error('timeout');
|
|
6
|
+
/**
|
|
7
|
+
*
|
|
8
|
+
* @param call - The async function to call.
|
|
9
|
+
* @param timeout - Timeout in milliseconds for each call attempt.
|
|
10
|
+
* @param maxRetries - Maximum number of retries on timeout.
|
|
11
|
+
* @returns The resolved value of the call, or throws the last error if not a timeout or retries exhausted.
|
|
12
|
+
*/
|
|
13
|
+
// eslint-disable-next-line consistent-return
|
|
14
|
+
async function timeoutWithRetry(call, timeout, maxRetries) {
|
|
15
|
+
(0, utils_1.assert)(maxRetries >= 0, 'maxRetries must be greater than or equal to 0');
|
|
16
|
+
let attempt = 0;
|
|
17
|
+
while (attempt <= maxRetries) {
|
|
18
|
+
try {
|
|
19
|
+
return (await Promise.race([
|
|
20
|
+
call(),
|
|
21
|
+
new Promise((_resolve, reject) => setTimeout(() => reject(TIMEOUT_ERROR), timeout)),
|
|
22
|
+
]));
|
|
23
|
+
}
|
|
24
|
+
catch (err) {
|
|
25
|
+
if (err === TIMEOUT_ERROR && attempt < maxRetries) {
|
|
26
|
+
attempt += 1;
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
throw err;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
exports.timeoutWithRetry = timeoutWithRetry;
|
|
34
|
+
//# sourceMappingURL=timeout-with-retry.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"timeout-with-retry.cjs","sourceRoot":"","sources":["../../src/utils/timeout-with-retry.ts"],"names":[],"mappings":";;;AAAA,2CAAyC;AAEzC,MAAM,aAAa,GAAG,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;AAE3C;;;;;;GAMG;AACH,6CAA6C;AACtC,KAAK,UAAU,gBAAgB,CACpC,IAAO,EACP,OAAe,EACf,UAAkB;IAGlB,IAAA,cAAM,EAAC,UAAU,IAAI,CAAC,EAAE,+CAA+C,CAAC,CAAC;IAEzE,IAAI,OAAO,GAAG,CAAC,CAAC;IAEhB,OAAO,OAAO,IAAI,UAAU,EAAE;QAC5B,IAAI;YACF,OAAO,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC;gBACzB,IAAI,EAAE;gBACN,IAAI,OAAO,CAAC,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,CAC/B,UAAU,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,OAAO,CAAC,CACjD;aACF,CAAC,CAA2B,CAAC;SAC/B;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,KAAK,aAAa,IAAI,OAAO,GAAG,UAAU,EAAE;gBACjD,OAAO,IAAI,CAAC,CAAC;gBACb,SAAS;aACV;YACD,MAAM,GAAG,CAAC;SACX;KACF;AACH,CAAC;AA1BD,4CA0BC","sourcesContent":["import { assert } from '@metamask/utils';\n\nconst TIMEOUT_ERROR = new Error('timeout');\n\n/**\n *\n * @param call - The async function to call.\n * @param timeout - Timeout in milliseconds for each call attempt.\n * @param maxRetries - Maximum number of retries on timeout.\n * @returns The resolved value of the call, or throws the last error if not a timeout or retries exhausted.\n */\n// eslint-disable-next-line consistent-return\nexport async function timeoutWithRetry<T extends () => Promise<unknown>>(\n call: T,\n timeout: number,\n maxRetries: number,\n // @ts-expect-error TS2366: Assertion guarantees loop executes\n): Promise<Awaited<ReturnType<T>>> {\n assert(maxRetries >= 0, 'maxRetries must be greater than or equal to 0');\n\n let attempt = 0;\n\n while (attempt <= maxRetries) {\n try {\n return (await Promise.race([\n call(),\n new Promise((_resolve, reject) =>\n setTimeout(() => reject(TIMEOUT_ERROR), timeout),\n ),\n ])) as Awaited<ReturnType<T>>;\n } catch (err) {\n if (err === TIMEOUT_ERROR && attempt < maxRetries) {\n attempt += 1;\n continue;\n }\n throw err;\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
*
|
|
3
|
+
* @param call - The async function to call.
|
|
4
|
+
* @param timeout - Timeout in milliseconds for each call attempt.
|
|
5
|
+
* @param maxRetries - Maximum number of retries on timeout.
|
|
6
|
+
* @returns The resolved value of the call, or throws the last error if not a timeout or retries exhausted.
|
|
7
|
+
*/
|
|
8
|
+
export declare function timeoutWithRetry<T extends () => Promise<unknown>>(call: T, timeout: number, maxRetries: number): Promise<Awaited<ReturnType<T>>>;
|
|
9
|
+
//# sourceMappingURL=timeout-with-retry.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"timeout-with-retry.d.cts","sourceRoot":"","sources":["../../src/utils/timeout-with-retry.ts"],"names":[],"mappings":"AAIA;;;;;;GAMG;AAEH,wBAAsB,gBAAgB,CAAC,CAAC,SAAS,MAAM,OAAO,CAAC,OAAO,CAAC,EACrE,IAAI,EAAE,CAAC,EACP,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,MAAM,GAEjB,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAqBjC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
*
|
|
3
|
+
* @param call - The async function to call.
|
|
4
|
+
* @param timeout - Timeout in milliseconds for each call attempt.
|
|
5
|
+
* @param maxRetries - Maximum number of retries on timeout.
|
|
6
|
+
* @returns The resolved value of the call, or throws the last error if not a timeout or retries exhausted.
|
|
7
|
+
*/
|
|
8
|
+
export declare function timeoutWithRetry<T extends () => Promise<unknown>>(call: T, timeout: number, maxRetries: number): Promise<Awaited<ReturnType<T>>>;
|
|
9
|
+
//# sourceMappingURL=timeout-with-retry.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"timeout-with-retry.d.mts","sourceRoot":"","sources":["../../src/utils/timeout-with-retry.ts"],"names":[],"mappings":"AAIA;;;;;;GAMG;AAEH,wBAAsB,gBAAgB,CAAC,CAAC,SAAS,MAAM,OAAO,CAAC,OAAO,CAAC,EACrE,IAAI,EAAE,CAAC,EACP,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,MAAM,GAEjB,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAqBjC"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { assert } from "@metamask/utils";
|
|
2
|
+
const TIMEOUT_ERROR = new Error('timeout');
|
|
3
|
+
/**
|
|
4
|
+
*
|
|
5
|
+
* @param call - The async function to call.
|
|
6
|
+
* @param timeout - Timeout in milliseconds for each call attempt.
|
|
7
|
+
* @param maxRetries - Maximum number of retries on timeout.
|
|
8
|
+
* @returns The resolved value of the call, or throws the last error if not a timeout or retries exhausted.
|
|
9
|
+
*/
|
|
10
|
+
// eslint-disable-next-line consistent-return
|
|
11
|
+
export async function timeoutWithRetry(call, timeout, maxRetries) {
|
|
12
|
+
assert(maxRetries >= 0, 'maxRetries must be greater than or equal to 0');
|
|
13
|
+
let attempt = 0;
|
|
14
|
+
while (attempt <= maxRetries) {
|
|
15
|
+
try {
|
|
16
|
+
return (await Promise.race([
|
|
17
|
+
call(),
|
|
18
|
+
new Promise((_resolve, reject) => setTimeout(() => reject(TIMEOUT_ERROR), timeout)),
|
|
19
|
+
]));
|
|
20
|
+
}
|
|
21
|
+
catch (err) {
|
|
22
|
+
if (err === TIMEOUT_ERROR && attempt < maxRetries) {
|
|
23
|
+
attempt += 1;
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
throw err;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=timeout-with-retry.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"timeout-with-retry.mjs","sourceRoot":"","sources":["../../src/utils/timeout-with-retry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,wBAAwB;AAEzC,MAAM,aAAa,GAAG,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;AAE3C;;;;;;GAMG;AACH,6CAA6C;AAC7C,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,IAAO,EACP,OAAe,EACf,UAAkB;IAGlB,MAAM,CAAC,UAAU,IAAI,CAAC,EAAE,+CAA+C,CAAC,CAAC;IAEzE,IAAI,OAAO,GAAG,CAAC,CAAC;IAEhB,OAAO,OAAO,IAAI,UAAU,EAAE;QAC5B,IAAI;YACF,OAAO,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC;gBACzB,IAAI,EAAE;gBACN,IAAI,OAAO,CAAC,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,CAC/B,UAAU,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,OAAO,CAAC,CACjD;aACF,CAAC,CAA2B,CAAC;SAC/B;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,KAAK,aAAa,IAAI,OAAO,GAAG,UAAU,EAAE;gBACjD,OAAO,IAAI,CAAC,CAAC;gBACb,SAAS;aACV;YACD,MAAM,GAAG,CAAC;SACX;KACF;AACH,CAAC","sourcesContent":["import { assert } from '@metamask/utils';\n\nconst TIMEOUT_ERROR = new Error('timeout');\n\n/**\n *\n * @param call - The async function to call.\n * @param timeout - Timeout in milliseconds for each call attempt.\n * @param maxRetries - Maximum number of retries on timeout.\n * @returns The resolved value of the call, or throws the last error if not a timeout or retries exhausted.\n */\n// eslint-disable-next-line consistent-return\nexport async function timeoutWithRetry<T extends () => Promise<unknown>>(\n call: T,\n timeout: number,\n maxRetries: number,\n // @ts-expect-error TS2366: Assertion guarantees loop executes\n): Promise<Awaited<ReturnType<T>>> {\n assert(maxRetries >= 0, 'maxRetries must be greater than or equal to 0');\n\n let attempt = 0;\n\n while (attempt <= maxRetries) {\n try {\n return (await Promise.race([\n call(),\n new Promise((_resolve, reject) =>\n setTimeout(() => reject(TIMEOUT_ERROR), timeout),\n ),\n ])) as Awaited<ReturnType<T>>;\n } catch (err) {\n if (err === TIMEOUT_ERROR && attempt < maxRetries) {\n attempt += 1;\n continue;\n }\n throw err;\n }\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/assets-controllers",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "87.1.0",
|
|
4
4
|
"description": "Controllers which manage interactions involving ERC-20, ERC-721, and ERC-1155 tokens (including NFTs)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
],
|
|
37
37
|
"scripts": {
|
|
38
38
|
"build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
|
|
39
|
+
"build:all": "ts-bridge --project tsconfig.build.json --verbose --clean",
|
|
39
40
|
"build:docs": "typedoc",
|
|
40
41
|
"changelog:update": "../../scripts/update-changelog.sh @metamask/assets-controllers",
|
|
41
42
|
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/assets-controllers",
|
|
@@ -90,7 +91,7 @@
|
|
|
90
91
|
"@metamask/keyring-controller": "^24.0.0",
|
|
91
92
|
"@metamask/keyring-internal-api": "^9.0.0",
|
|
92
93
|
"@metamask/keyring-snap-client": "^8.0.0",
|
|
93
|
-
"@metamask/multichain-account-service": "^2.
|
|
94
|
+
"@metamask/multichain-account-service": "^2.1.0",
|
|
94
95
|
"@metamask/network-controller": "^25.0.0",
|
|
95
96
|
"@metamask/permission-controller": "^12.1.0",
|
|
96
97
|
"@metamask/phishing-controller": "^15.0.0",
|
|
@@ -98,6 +99,7 @@
|
|
|
98
99
|
"@metamask/providers": "^22.1.0",
|
|
99
100
|
"@metamask/snaps-controllers": "^14.0.1",
|
|
100
101
|
"@metamask/transaction-controller": "^61.1.0",
|
|
102
|
+
"@ts-bridge/cli": "^0.6.4",
|
|
101
103
|
"@types/jest": "^27.4.1",
|
|
102
104
|
"@types/lodash": "^4.14.191",
|
|
103
105
|
"@types/node": "^16.18.54",
|