@metamask/assets-controller 11.0.0 → 11.1.1
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 +40 -1
- package/dist/AssetsController-method-action-types.cjs.map +1 -1
- package/dist/AssetsController-method-action-types.d.cts +23 -1
- package/dist/AssetsController-method-action-types.d.cts.map +1 -1
- package/dist/AssetsController-method-action-types.d.mts +23 -1
- package/dist/AssetsController-method-action-types.d.mts.map +1 -1
- package/dist/AssetsController-method-action-types.mjs.map +1 -1
- package/dist/AssetsController.cjs +99 -51
- package/dist/AssetsController.cjs.map +1 -1
- package/dist/AssetsController.d.cts +21 -1
- package/dist/AssetsController.d.cts.map +1 -1
- package/dist/AssetsController.d.mts +21 -1
- package/dist/AssetsController.d.mts.map +1 -1
- package/dist/AssetsController.mjs +99 -51
- package/dist/AssetsController.mjs.map +1 -1
- package/dist/data-sources/AccountsApiDataSource.cjs +95 -9
- package/dist/data-sources/AccountsApiDataSource.cjs.map +1 -1
- package/dist/data-sources/AccountsApiDataSource.d.cts +8 -1
- package/dist/data-sources/AccountsApiDataSource.d.cts.map +1 -1
- package/dist/data-sources/AccountsApiDataSource.d.mts +8 -1
- package/dist/data-sources/AccountsApiDataSource.d.mts.map +1 -1
- package/dist/data-sources/AccountsApiDataSource.mjs +95 -9
- package/dist/data-sources/AccountsApiDataSource.mjs.map +1 -1
- package/dist/data-sources/TokenDataSource.cjs +97 -15
- package/dist/data-sources/TokenDataSource.cjs.map +1 -1
- package/dist/data-sources/TokenDataSource.d.cts +10 -1
- package/dist/data-sources/TokenDataSource.d.cts.map +1 -1
- package/dist/data-sources/TokenDataSource.d.mts +10 -1
- package/dist/data-sources/TokenDataSource.d.mts.map +1 -1
- package/dist/data-sources/TokenDataSource.mjs +97 -15
- package/dist/data-sources/TokenDataSource.mjs.map +1 -1
- package/dist/data-sources/evm-rpc-services/clients/TokensApiClient.cjs +86 -27
- package/dist/data-sources/evm-rpc-services/clients/TokensApiClient.cjs.map +1 -1
- package/dist/data-sources/evm-rpc-services/clients/TokensApiClient.d.cts +4 -3
- package/dist/data-sources/evm-rpc-services/clients/TokensApiClient.d.cts.map +1 -1
- package/dist/data-sources/evm-rpc-services/clients/TokensApiClient.d.mts +4 -3
- package/dist/data-sources/evm-rpc-services/clients/TokensApiClient.d.mts.map +1 -1
- package/dist/data-sources/evm-rpc-services/clients/TokensApiClient.mjs +86 -27
- package/dist/data-sources/evm-rpc-services/clients/TokensApiClient.mjs.map +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/utils/formatExchangeRatesForBridge.cjs +36 -7
- package/dist/utils/formatExchangeRatesForBridge.cjs.map +1 -1
- package/dist/utils/formatExchangeRatesForBridge.d.cts +20 -14
- package/dist/utils/formatExchangeRatesForBridge.d.cts.map +1 -1
- package/dist/utils/formatExchangeRatesForBridge.d.mts +20 -14
- package/dist/utils/formatExchangeRatesForBridge.d.mts.map +1 -1
- package/dist/utils/formatExchangeRatesForBridge.mjs +34 -5
- package/dist/utils/formatExchangeRatesForBridge.mjs.map +1 -1
- package/dist/utils/formatStateForTransactionPay.cjs +56 -9
- package/dist/utils/formatStateForTransactionPay.cjs.map +1 -1
- package/dist/utils/formatStateForTransactionPay.d.cts +23 -17
- package/dist/utils/formatStateForTransactionPay.d.cts.map +1 -1
- package/dist/utils/formatStateForTransactionPay.d.mts +23 -17
- package/dist/utils/formatStateForTransactionPay.d.mts.map +1 -1
- package/dist/utils/formatStateForTransactionPay.mjs +54 -7
- package/dist/utils/formatStateForTransactionPay.mjs.map +1 -1
- package/dist/utils/index.cjs +4 -1
- package/dist/utils/index.cjs.map +1 -1
- package/dist/utils/index.d.cts +5 -5
- package/dist/utils/index.d.cts.map +1 -1
- package/dist/utils/index.d.mts +5 -5
- package/dist/utils/index.d.mts.map +1 -1
- package/dist/utils/index.mjs +3 -3
- package/dist/utils/index.mjs.map +1 -1
- package/dist/utils/normalizeAssetId.cjs +17 -3
- package/dist/utils/normalizeAssetId.cjs.map +1 -1
- package/dist/utils/normalizeAssetId.d.cts +10 -1
- package/dist/utils/normalizeAssetId.d.cts.map +1 -1
- package/dist/utils/normalizeAssetId.d.mts +10 -1
- package/dist/utils/normalizeAssetId.d.mts.map +1 -1
- package/dist/utils/normalizeAssetId.mjs +19 -1
- package/dist/utils/normalizeAssetId.mjs.map +1 -1
- package/package.json +12 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TokensApiClient.d.cts","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/clients/TokensApiClient.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,2BAAiB;
|
|
1
|
+
{"version":3,"file":"TokensApiClient.d.cts","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/clients/TokensApiClient.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,2BAAiB;AAgFxD;;;;;GAKG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE;QACzB,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAC;QAC7B,OAAO,EAAE,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;QAC9B,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG;IAClC,qDAAqD;IACrD,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;IAChC;;;;OAIG;IACH,WAAW,CAAC,EAAE,oBAAoB,CAAC;CACpC,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,eAAe;;gBA2Bd,MAAM,CAAC,EAAE,qBAAqB;IAK1C;;;;;;;;;;OAUG;IACG,cAAc,CAAC,UAAU,EAAE,OAAO,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;CA0MrE"}
|
|
@@ -28,9 +28,10 @@ export type TokensApiClientConfig = {
|
|
|
28
28
|
*
|
|
29
29
|
* Fetches the per-chain ERC-20 token list from the same endpoint that
|
|
30
30
|
* `TokenListController` uses (`token.api.cx.metamask.io/tokens/{chainId}`),
|
|
31
|
-
* with the same query parameters
|
|
32
|
-
*
|
|
33
|
-
*
|
|
31
|
+
* with the same query parameters. The `occurrenceFloor` query param comes from
|
|
32
|
+
* Token API `/v1/suggestedOccurrenceFloors` (fallback {@link DEFAULT_OCCURRENCE_FLOOR}),
|
|
33
|
+
* matching `TokenDataSource` spam filtering. Linea's post-response aggregator
|
|
34
|
+
* filter is still applied client-side.
|
|
34
35
|
*
|
|
35
36
|
* Before fetching a chain's token list, the client checks
|
|
36
37
|
* `/v2/supportedNetworks` and returns `[]` immediately for chains that are
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TokensApiClient.d.mts","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/clients/TokensApiClient.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,2BAAiB;
|
|
1
|
+
{"version":3,"file":"TokensApiClient.d.mts","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/clients/TokensApiClient.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,2BAAiB;AAgFxD;;;;;GAKG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE;QACzB,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAC;QAC7B,OAAO,EAAE,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;QAC9B,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG;IAClC,qDAAqD;IACrD,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;IAChC;;;;OAIG;IACH,WAAW,CAAC,EAAE,oBAAoB,CAAC;CACpC,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,eAAe;;gBA2Bd,MAAM,CAAC,EAAE,qBAAqB;IAK1C;;;;;;;;;;OAUG;IACG,cAAc,CAAC,UAAU,EAAE,OAAO,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;CA0MrE"}
|
|
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
|
-
var _TokensApiClient_instances, _TokensApiClient_fetch, _TokensApiClient_queryClient, _TokensApiClient_supportedChainIds, _TokensApiClient_supportedChainIdsCachedAt, _TokensApiClient_supportedChainIdsRefreshPromise, _TokensApiClient_isSupportedChain, _TokensApiClient_refreshSupportedChainIds, _TokensApiClient_fetchTokenListUncached;
|
|
12
|
+
var _TokensApiClient_instances, _TokensApiClient_fetch, _TokensApiClient_queryClient, _TokensApiClient_supportedChainIds, _TokensApiClient_supportedChainIdsCachedAt, _TokensApiClient_supportedChainIdsRefreshPromise, _TokensApiClient_suggestedOccurrenceFloors, _TokensApiClient_suggestedOccurrenceFloorsCachedAt, _TokensApiClient_suggestedOccurrenceFloorsRefreshPromise, _TokensApiClient_isSupportedChain, _TokensApiClient_refreshSupportedChainIds, _TokensApiClient_getOccurrenceFloor, _TokensApiClient_refreshSuggestedOccurrenceFloors, _TokensApiClient_fetchTokenListUncached;
|
|
13
13
|
import { ChainId as ControllerChainId, convertHexToDecimal } from "@metamask/controller-utils";
|
|
14
14
|
/**
|
|
15
15
|
* Same host + path that `TokenListController` (assets-controllers) uses
|
|
@@ -24,6 +24,17 @@ const TOKEN_END_POINT_API = 'https://token.api.cx.metamask.io';
|
|
|
24
24
|
* that are not in the supported-networks list.
|
|
25
25
|
*/
|
|
26
26
|
const SUPPORTED_NETWORKS_URL = `${TOKEN_END_POINT_API}/v2/supportedNetworks`;
|
|
27
|
+
/**
|
|
28
|
+
* Per-chain suggested occurrence floors used as the `occurrenceFloor` query
|
|
29
|
+
* param when fetching token lists (and aligned with TokenDataSource spam
|
|
30
|
+
* filtering). Keys are decimal chain IDs.
|
|
31
|
+
*/
|
|
32
|
+
const SUGGESTED_OCCURRENCE_FLOORS_URL = `${TOKEN_END_POINT_API}/v1/suggestedOccurrenceFloors`;
|
|
33
|
+
/**
|
|
34
|
+
* Fallback `occurrenceFloor` when `/v1/suggestedOccurrenceFloors` has no entry
|
|
35
|
+
* for the chain, or the floors request fails.
|
|
36
|
+
*/
|
|
37
|
+
const DEFAULT_OCCURRENCE_FLOOR = 3;
|
|
27
38
|
/**
|
|
28
39
|
* How long to keep the supported-networks response in the instance-level
|
|
29
40
|
* cache before refreshing it. One hour is sufficient — the list rarely
|
|
@@ -32,27 +43,10 @@ const SUPPORTED_NETWORKS_URL = `${TOKEN_END_POINT_API}/v2/supportedNetworks`;
|
|
|
32
43
|
*/
|
|
33
44
|
const SUPPORTED_NETWORKS_CACHE_TTL_MS = 60 * 60000;
|
|
34
45
|
/**
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
* `TokenListController` does (see `token-service.ts:getTokensURL`).
|
|
38
|
-
*/
|
|
39
|
-
const TEMPO_MAINNET_CHAIN_ID = '0x1079';
|
|
40
|
-
/**
|
|
41
|
-
* Per-chain occurrence floor, mirroring `TokenListController.getTokensURL`:
|
|
42
|
-
* Linea mainnet, MegaETH mainnet, and Tempo mainnet have thinner aggregator
|
|
43
|
-
* coverage so we lower the floor; everything else uses the default 3.
|
|
44
|
-
*
|
|
45
|
-
* @param hexChainId - Hex chain ID.
|
|
46
|
-
* @returns The occurrence floor to send to the Tokens API.
|
|
46
|
+
* How long to keep suggested occurrence floors cached. Same TTL as supported
|
|
47
|
+
* networks — floors change infrequently.
|
|
47
48
|
*/
|
|
48
|
-
|
|
49
|
-
if (hexChainId === ControllerChainId['linea-mainnet'] ||
|
|
50
|
-
hexChainId === ControllerChainId['megaeth-mainnet'] ||
|
|
51
|
-
hexChainId === TEMPO_MAINNET_CHAIN_ID) {
|
|
52
|
-
return 1;
|
|
53
|
-
}
|
|
54
|
-
return 3;
|
|
55
|
-
}
|
|
49
|
+
const SUGGESTED_OCCURRENCE_FLOORS_CACHE_TTL_MS = 60 * 60000;
|
|
56
50
|
/**
|
|
57
51
|
* TanStack-Query cache config for the cached `fetchTokenList` path.
|
|
58
52
|
*
|
|
@@ -69,9 +63,10 @@ const TOKEN_LIST_GC_TIME_MS = 60 * 60000;
|
|
|
69
63
|
*
|
|
70
64
|
* Fetches the per-chain ERC-20 token list from the same endpoint that
|
|
71
65
|
* `TokenListController` uses (`token.api.cx.metamask.io/tokens/{chainId}`),
|
|
72
|
-
* with the same query parameters
|
|
73
|
-
*
|
|
74
|
-
*
|
|
66
|
+
* with the same query parameters. The `occurrenceFloor` query param comes from
|
|
67
|
+
* Token API `/v1/suggestedOccurrenceFloors` (fallback {@link DEFAULT_OCCURRENCE_FLOOR}),
|
|
68
|
+
* matching `TokenDataSource` spam filtering. Linea's post-response aggregator
|
|
69
|
+
* filter is still applied client-side.
|
|
75
70
|
*
|
|
76
71
|
* Before fetching a chain's token list, the client checks
|
|
77
72
|
* `/v2/supportedNetworks` and returns `[]` immediately for chains that are
|
|
@@ -97,6 +92,12 @@ export class TokensApiClient {
|
|
|
97
92
|
* calls arrive before the first one resolves.
|
|
98
93
|
*/
|
|
99
94
|
_TokensApiClient_supportedChainIdsRefreshPromise.set(this, void 0);
|
|
95
|
+
/** Decimal chain ID → suggested occurrence floor from Token API. */
|
|
96
|
+
_TokensApiClient_suggestedOccurrenceFloors.set(this, void 0);
|
|
97
|
+
/** Timestamp of the last successful floors fetch. */
|
|
98
|
+
_TokensApiClient_suggestedOccurrenceFloorsCachedAt.set(this, 0);
|
|
99
|
+
/** In-flight floors request shared across concurrent callers. */
|
|
100
|
+
_TokensApiClient_suggestedOccurrenceFloorsRefreshPromise.set(this, void 0);
|
|
100
101
|
__classPrivateFieldSet(this, _TokensApiClient_fetch, config?.fetch ?? globalThis.fetch.bind(globalThis), "f");
|
|
101
102
|
__classPrivateFieldSet(this, _TokensApiClient_queryClient, config?.queryClient, "f");
|
|
102
103
|
}
|
|
@@ -136,7 +137,7 @@ export class TokensApiClient {
|
|
|
136
137
|
});
|
|
137
138
|
}
|
|
138
139
|
}
|
|
139
|
-
_TokensApiClient_fetch = new WeakMap(), _TokensApiClient_queryClient = new WeakMap(), _TokensApiClient_supportedChainIds = new WeakMap(), _TokensApiClient_supportedChainIdsCachedAt = new WeakMap(), _TokensApiClient_supportedChainIdsRefreshPromise = new WeakMap(), _TokensApiClient_instances = new WeakSet(), _TokensApiClient_isSupportedChain =
|
|
140
|
+
_TokensApiClient_fetch = new WeakMap(), _TokensApiClient_queryClient = new WeakMap(), _TokensApiClient_supportedChainIds = new WeakMap(), _TokensApiClient_supportedChainIdsCachedAt = new WeakMap(), _TokensApiClient_supportedChainIdsRefreshPromise = new WeakMap(), _TokensApiClient_suggestedOccurrenceFloors = new WeakMap(), _TokensApiClient_suggestedOccurrenceFloorsCachedAt = new WeakMap(), _TokensApiClient_suggestedOccurrenceFloorsRefreshPromise = new WeakMap(), _TokensApiClient_instances = new WeakSet(), _TokensApiClient_isSupportedChain =
|
|
140
141
|
/**
|
|
141
142
|
* Check whether the given chain is present in the supported-networks list.
|
|
142
143
|
*
|
|
@@ -185,10 +186,68 @@ async function _TokensApiClient_refreshSupportedChainIds(now) {
|
|
|
185
186
|
}
|
|
186
187
|
})(), "f");
|
|
187
188
|
return __classPrivateFieldGet(this, _TokensApiClient_supportedChainIdsRefreshPromise, "f");
|
|
189
|
+
}, _TokensApiClient_getOccurrenceFloor =
|
|
190
|
+
/**
|
|
191
|
+
* Resolve the `occurrenceFloor` query param for a chain from Token API
|
|
192
|
+
* `/v1/suggestedOccurrenceFloors`. Falls back to
|
|
193
|
+
* {@link DEFAULT_OCCURRENCE_FLOOR} when the chain is missing or the request
|
|
194
|
+
* fails.
|
|
195
|
+
*
|
|
196
|
+
* @param hexChainId - Hex chain ID.
|
|
197
|
+
* @returns Occurrence floor to send to `/tokens/{chainId}`.
|
|
198
|
+
*/
|
|
199
|
+
async function _TokensApiClient_getOccurrenceFloor(hexChainId) {
|
|
200
|
+
const now = Date.now();
|
|
201
|
+
if (__classPrivateFieldGet(this, _TokensApiClient_suggestedOccurrenceFloors, "f") === undefined ||
|
|
202
|
+
now - __classPrivateFieldGet(this, _TokensApiClient_suggestedOccurrenceFloorsCachedAt, "f") >=
|
|
203
|
+
SUGGESTED_OCCURRENCE_FLOORS_CACHE_TTL_MS) {
|
|
204
|
+
await __classPrivateFieldGet(this, _TokensApiClient_instances, "m", _TokensApiClient_refreshSuggestedOccurrenceFloors).call(this, now);
|
|
205
|
+
}
|
|
206
|
+
const decimalChainId = String(convertHexToDecimal(hexChainId));
|
|
207
|
+
return (__classPrivateFieldGet(this, _TokensApiClient_suggestedOccurrenceFloors, "f")?.[decimalChainId] ??
|
|
208
|
+
DEFAULT_OCCURRENCE_FLOOR);
|
|
209
|
+
}, _TokensApiClient_refreshSuggestedOccurrenceFloors =
|
|
210
|
+
/**
|
|
211
|
+
* Fetch `/v1/suggestedOccurrenceFloors` and update the instance cache.
|
|
212
|
+
* Concurrent callers share the in-flight Promise. Failures leave the cache
|
|
213
|
+
* empty so {@link #getOccurrenceFloor} falls back to the default.
|
|
214
|
+
*
|
|
215
|
+
* @param now - Current timestamp used to stamp the cache entry.
|
|
216
|
+
* @returns A promise that resolves once the cache has been refreshed.
|
|
217
|
+
*/
|
|
218
|
+
async function _TokensApiClient_refreshSuggestedOccurrenceFloors(now) {
|
|
219
|
+
if (__classPrivateFieldGet(this, _TokensApiClient_suggestedOccurrenceFloorsRefreshPromise, "f") !== undefined) {
|
|
220
|
+
return __classPrivateFieldGet(this, _TokensApiClient_suggestedOccurrenceFloorsRefreshPromise, "f");
|
|
221
|
+
}
|
|
222
|
+
__classPrivateFieldSet(this, _TokensApiClient_suggestedOccurrenceFloorsRefreshPromise, (async () => {
|
|
223
|
+
try {
|
|
224
|
+
const response = await __classPrivateFieldGet(this, _TokensApiClient_fetch, "f").call(this, SUGGESTED_OCCURRENCE_FLOORS_URL);
|
|
225
|
+
if (response.ok) {
|
|
226
|
+
const data = (await response.json());
|
|
227
|
+
__classPrivateFieldSet(this, _TokensApiClient_suggestedOccurrenceFloors, data && typeof data === 'object' && !Array.isArray(data)
|
|
228
|
+
? data
|
|
229
|
+
: {}, "f");
|
|
230
|
+
__classPrivateFieldSet(this, _TokensApiClient_suggestedOccurrenceFloorsCachedAt, now, "f");
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
__classPrivateFieldSet(this, _TokensApiClient_suggestedOccurrenceFloors, {}, "f");
|
|
234
|
+
__classPrivateFieldSet(this, _TokensApiClient_suggestedOccurrenceFloorsCachedAt, now, "f");
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
__classPrivateFieldSet(this, _TokensApiClient_suggestedOccurrenceFloors, {}, "f");
|
|
239
|
+
__classPrivateFieldSet(this, _TokensApiClient_suggestedOccurrenceFloorsCachedAt, now, "f");
|
|
240
|
+
}
|
|
241
|
+
finally {
|
|
242
|
+
__classPrivateFieldSet(this, _TokensApiClient_suggestedOccurrenceFloorsRefreshPromise, undefined, "f");
|
|
243
|
+
}
|
|
244
|
+
})(), "f");
|
|
245
|
+
return __classPrivateFieldGet(this, _TokensApiClient_suggestedOccurrenceFloorsRefreshPromise, "f");
|
|
188
246
|
}, _TokensApiClient_fetchTokenListUncached = async function _TokensApiClient_fetchTokenListUncached(hexChainId) {
|
|
189
247
|
const decimalChainId = convertHexToDecimal(hexChainId);
|
|
190
|
-
const occurrenceFloor =
|
|
191
|
-
//
|
|
248
|
+
const occurrenceFloor = await __classPrivateFieldGet(this, _TokensApiClient_instances, "m", _TokensApiClient_getOccurrenceFloor).call(this, hexChainId);
|
|
249
|
+
// Same query shape as `TokenListController.getTokensURL` (token-service.ts),
|
|
250
|
+
// but `occurrenceFloor` comes from `/v1/suggestedOccurrenceFloors`.
|
|
192
251
|
// No `first=...` cap — the API returns the full per-chain list bounded
|
|
193
252
|
// server-side by `occurrenceFloor`.
|
|
194
253
|
const url = `${TOKEN_END_POINT_API}/tokens/${decimalChainId}` +
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TokensApiClient.mjs","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/clients/TokensApiClient.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,OAAO,IAAI,iBAAiB,EAC5B,mBAAmB,EACpB,mCAAmC;AAIpC;;;;;GAKG;AACH,MAAM,mBAAmB,GAAG,kCAAkC,CAAC;AAE/D;;;;GAIG;AACH,MAAM,sBAAsB,GAAG,GAAG,mBAAmB,uBAAuB,CAAC;AAE7E;;;;;GAKG;AACH,MAAM,+BAA+B,GAAG,EAAE,GAAG,KAAM,CAAC;AAEpD;;;;GAIG;AACH,MAAM,sBAAsB,GAAG,QAAiB,CAAC;AAEjD;;;;;;;GAOG;AACH,SAAS,kBAAkB,CAAC,UAAmB;IAC7C,IACE,UAAU,KAAK,iBAAiB,CAAC,eAAe,CAAC;QACjD,UAAU,KAAK,iBAAiB,CAAC,iBAAiB,CAAC;QACnD,UAAU,KAAK,sBAAsB,EACrC,CAAC;QACD,OAAO,CAAC,CAAC;IACX,CAAC;IACD,OAAO,CAAC,CAAC;AAC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IAE9D,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QAC7B,OAAO,EAAE,IAAI,CAAC,OAAO;QACrB,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,EAAE;QACzB,IAAI,EAAE,IAAI,CAAC,IAAI,IAAI,EAAE;QACrB,QAAQ,EAAE,IAAI,CAAC,QAAQ,IAAI,EAAE;QAC7B,OAAO,EAAE,IAAI,CAAC,OAAO;QACrB,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,WAAW,EAAE,IAAI,CAAC,WAAW;KAC9B,CAAC,CAAC,CAAC;AACN,CAAC;AAGH;;;;;;;;;;GAUG;AACH,SAAS,yBAAyB,CAChC,UAAmB,EACnB,KAAyB;IAEzB,IAAI,UAAU,KAAK,iBAAiB,CAAC,eAAe,CAAC,EAAE,CAAC;QACtD,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE;YAC3B,MAAM,WAAW,GAAG,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC;YAC3C,OAAO,WAAW,CAAC,QAAQ,CAAC,WAAW,CAAC,IAAI,WAAW,CAAC,MAAM,IAAI,CAAC,CAAC;QACtE,CAAC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import {\n ChainId as ControllerChainId,\n convertHexToDecimal,\n} from '@metamask/controller-utils';\n\nimport type { ChainId, TokenListEntry } from '../types';\n\n/**\n * Same host + path that `TokenListController` (assets-controllers) uses\n * (`token-service.ts` → `getTokensURL`). Sharing this endpoint keeps the\n * RPC token detector aligned with the rest of the wallet's token listing\n * (occurrence floors, aggregator filters, icon URLs, etc.).\n */\nconst TOKEN_END_POINT_API = 'https://token.api.cx.metamask.io';\n\n/**\n * Endpoint that returns which CAIP chain IDs the Tokens API supports.\n * Used to skip detection (and avoid unnecessary network requests) for chains\n * that are not in the supported-networks list.\n */\nconst SUPPORTED_NETWORKS_URL = `${TOKEN_END_POINT_API}/v2/supportedNetworks`;\n\n/**\n * How long to keep the supported-networks response in the instance-level\n * cache before refreshing it. One hour is sufficient — the list rarely\n * changes and a stale cache just means we may do an unnecessary token-list\n * fetch for a newly-unsupported chain (harmless).\n */\nconst SUPPORTED_NETWORKS_CACHE_TTL_MS = 60 * 60_000;\n\n/**\n * Tempo Mainnet — not yet present in `@metamask/controller-utils`'s `ChainId`\n * map at the time of writing, so it's spelled out as a literal here exactly as\n * `TokenListController` does (see `token-service.ts:getTokensURL`).\n */\nconst TEMPO_MAINNET_CHAIN_ID = '0x1079' as const;\n\n/**\n * Per-chain occurrence floor, mirroring `TokenListController.getTokensURL`:\n * Linea mainnet, MegaETH mainnet, and Tempo mainnet have thinner aggregator\n * coverage so we lower the floor; everything else uses the default 3.\n *\n * @param hexChainId - Hex chain ID.\n * @returns The occurrence floor to send to the Tokens API.\n */\nfunction getOccurrenceFloor(hexChainId: ChainId): number {\n if (\n hexChainId === ControllerChainId['linea-mainnet'] ||\n hexChainId === ControllerChainId['megaeth-mainnet'] ||\n hexChainId === TEMPO_MAINNET_CHAIN_ID\n ) {\n return 1;\n }\n return 3;\n}\n\n/**\n * TanStack-Query cache config for the cached `fetchTokenList` path.\n *\n * The Tokens API per-chain list barely changes between polls, so we keep\n * results fresh for a few minutes (`staleTime`) and retain them in cache for\n * an hour (`gcTime`) so re-detections across accounts/chains hit the cache.\n * These tunings only apply when a `queryClient` is provided to the client;\n * the uncached fallback path (used in standalone tests) is unaffected.\n */\nconst TOKEN_LIST_STALE_TIME_MS = 5 * 60_000;\nconst TOKEN_LIST_GC_TIME_MS = 60 * 60_000;\n\n/**\n * Shape of the `/v2/supportedNetworks` response.\n */\ntype SupportedNetworksResponse = {\n fullSupport?: string[];\n partialSupport?: string[];\n};\n\n/**\n * Shape of a single item returned by the Tokens API `/tokens/{chainId}`\n * endpoint. Mirrors `TokenListToken` in\n * `packages/assets-controllers/src/TokenListController.ts` and the response\n * parsed by `fetchTokenListByChainId` in `token-service.ts`.\n */\ntype ApiTokenListItem = {\n address: string;\n symbol?: string;\n name?: string;\n decimals?: number;\n occurrences?: number;\n aggregators?: string[];\n iconUrl?: string;\n};\n\n/**\n * Minimal structural type for the TanStack Query client method we use.\n * Avoids a direct dependency on `@tanstack/query-core` while still being\n * fully compatible with the shared `QueryClient` exposed by\n * `ApiPlatformClient.queryClient` (`@metamask/core-backend`).\n */\nexport type TokenListQueryClient = {\n fetchQuery<TData>(options: {\n queryKey: readonly unknown[];\n queryFn: () => Promise<TData>;\n staleTime?: number;\n gcTime?: number;\n }): Promise<TData>;\n};\n\nexport type TokensApiClientConfig = {\n /** Fetch function (defaults to globalThis.fetch). */\n fetch?: typeof globalThis.fetch;\n /**\n * Optional TanStack-Query client used to cache token-list responses across\n * detector polls / accounts / instances. When omitted, every call hits the\n * network directly (preserves prior behaviour for tests and standalone use).\n */\n queryClient?: TokenListQueryClient;\n};\n\n/**\n * Client for the MetaMask Tokens API.\n *\n * Fetches the per-chain ERC-20 token list from the same endpoint that\n * `TokenListController` uses (`token.api.cx.metamask.io/tokens/{chainId}`),\n * with the same query parameters and the same per-chain occurrence floor /\n * Linea aggregator filter. This keeps RPC token detection in lockstep with\n * the wallet's primary token list.\n *\n * Before fetching a chain's token list, the client checks\n * `/v2/supportedNetworks` and returns `[]` immediately for chains that are\n * not in the supported list, avoiding unnecessary API calls. The supported-\n * networks response is cached in-memory for one hour.\n *\n * When constructed with a `queryClient`, token-list results are cached and\n * deduped via TanStack Query (5 min staleTime, 1 h gcTime), so concurrent\n * detection cycles for the same chain coalesce into a single network request.\n */\nexport class TokensApiClient {\n readonly #fetch: typeof globalThis.fetch;\n\n readonly #queryClient: TokenListQueryClient | undefined;\n\n /** CAIP chain IDs returned by `/v2/supportedNetworks` (both tiers). */\n #supportedChainIds: Set<string> | undefined;\n\n /** Timestamp of the last successful `/v2/supportedNetworks` fetch. */\n #supportedChainIdsCachedAt = 0;\n\n /**\n * In-flight `/v2/supportedNetworks` request shared across concurrent callers\n * so only one network request is made even when multiple `fetchTokenList`\n * calls arrive before the first one resolves.\n */\n #supportedChainIdsRefreshPromise: Promise<void> | undefined;\n\n constructor(config?: TokensApiClientConfig) {\n this.#fetch = config?.fetch ?? globalThis.fetch.bind(globalThis);\n this.#queryClient = config?.queryClient;\n }\n\n /**\n * Fetch the list of ERC-20 tokens for a chain from the Tokens API.\n *\n * Returns `[]` immediately (without hitting the token-list endpoint) when\n * the chain is not in the `/v2/supportedNetworks` response, or when the\n * supported-networks check fails for any reason.\n *\n * @param hexChainId - Chain ID in hex format (e.g. `'0x1'` for Ethereum mainnet).\n * @returns Array of token list entries with address and metadata, or an empty\n * array if the chain is unsupported or the request fails.\n */\n async fetchTokenList(hexChainId: ChainId): Promise<TokenListEntry[]> {\n // Treat any error from the supported-networks check as \"not supported\":\n // the token-list endpoint is only contacted for known-supported chains.\n if (!(await this.#isSupportedChain(hexChainId).catch(() => false))) {\n return [];\n }\n\n const queryClient = this.#queryClient;\n if (queryClient === undefined) {\n return this.#fetchTokenListUncached(hexChainId);\n }\n\n return queryClient.fetchQuery({\n // Namespacing keeps this key from colliding with other clients that\n // share the same QueryClient (e.g. core-backend's ApiPlatformClient).\n queryKey: [\n 'assets-controller',\n 'rpc-detection',\n 'token-list',\n { chainId: hexChainId },\n ],\n queryFn: () => this.#fetchTokenListUncached(hexChainId),\n staleTime: TOKEN_LIST_STALE_TIME_MS,\n gcTime: TOKEN_LIST_GC_TIME_MS,\n });\n }\n\n /**\n * Check whether the given chain is present in the supported-networks list.\n *\n * Uses an instance-level cache (1 h TTL). Throws if the network request\n * fails — callers should handle this (e.g. via `.catch(() => false)`).\n *\n * @param hexChainId - Hex chain ID to check.\n * @returns `true` when the chain is in the supported-networks list.\n */\n async #isSupportedChain(hexChainId: ChainId): Promise<boolean> {\n const now = Date.now();\n if (\n this.#supportedChainIds === undefined ||\n now - this.#supportedChainIdsCachedAt >= SUPPORTED_NETWORKS_CACHE_TTL_MS\n ) {\n await this.#refreshSupportedChainIds(now);\n }\n\n const caipChainId = `eip155:${convertHexToDecimal(hexChainId)}`;\n return this.#supportedChainIds?.has(caipChainId) ?? false;\n }\n\n /**\n * Fetch `/v2/supportedNetworks` and update the instance cache.\n * Concurrent callers share the same in-flight Promise so only one network\n * request is made. If the response is not 2xx the cache is left unchanged\n * (the chain will be treated as unsupported this cycle).\n *\n * @param now - Current timestamp used to stamp the cache entry.\n * @returns A promise that resolves once the cache has been refreshed.\n */\n async #refreshSupportedChainIds(now: number): Promise<void> {\n if (this.#supportedChainIdsRefreshPromise !== undefined) {\n return this.#supportedChainIdsRefreshPromise;\n }\n\n this.#supportedChainIdsRefreshPromise = (async (): Promise<void> => {\n try {\n const response = await this.#fetch(SUPPORTED_NETWORKS_URL);\n if (response.ok) {\n const data = (await response.json()) as SupportedNetworksResponse;\n this.#supportedChainIds = new Set([\n ...(data.fullSupport ?? []),\n ...(data.partialSupport ?? []),\n ]);\n this.#supportedChainIdsCachedAt = now;\n }\n } finally {\n this.#supportedChainIdsRefreshPromise = undefined;\n }\n })();\n\n return this.#supportedChainIdsRefreshPromise;\n }\n\n async #fetchTokenListUncached(\n hexChainId: ChainId,\n ): Promise<TokenListEntry[]> {\n const decimalChainId = convertHexToDecimal(hexChainId);\n const occurrenceFloor = getOccurrenceFloor(hexChainId);\n\n // Mirrors `TokenListController.getTokensURL` exactly (token-service.ts).\n // No `first=...` cap — the API returns the full per-chain list bounded\n // server-side by `occurrenceFloor`.\n const url =\n `${TOKEN_END_POINT_API}/tokens/${decimalChainId}` +\n `?occurrenceFloor=${occurrenceFloor}` +\n `&includeNativeAssets=false` +\n `&includeTokenFees=false` +\n `&includeAssetType=false` +\n `&includeERC20Permit=false` +\n `&includeStorage=false` +\n `&includeRwaData=true`;\n\n let response: Response;\n try {\n response = await this.#fetch(url);\n } catch (error) {\n console.error(\n `Tokens API request failed for chain ${hexChainId}:`,\n error,\n );\n return [];\n }\n\n if (!response.ok) {\n console.error(\n `Tokens API responded with ${response.status} for chain ${hexChainId}`,\n );\n return [];\n }\n\n const raw = (await response.json()) as unknown;\n const items: ApiTokenListItem[] = Array.isArray(raw)\n ? (raw as ApiTokenListItem[])\n : [];\n\n const filtered = applyChainSpecificFilters(hexChainId, items);\n\n return filtered.map((item) => ({\n address: item.address,\n symbol: item.symbol ?? '',\n name: item.name ?? '',\n decimals: item.decimals ?? 18,\n iconUrl: item.iconUrl,\n aggregators: item.aggregators,\n occurrences: item.occurrences,\n }));\n }\n}\n\n/**\n * Apply chain-specific filters to a raw token list response, mirroring\n * `fetchTokenListByChainId` in `assets-controllers/src/token-service.ts`.\n *\n * For Linea mainnet, the API returns extras with low aggregator coverage, so\n * we keep only entries flagged by Linea's own team or seen by ≥3 aggregators.\n *\n * @param hexChainId - Hex chain ID.\n * @param items - Raw items from the API response.\n * @returns Items after chain-specific filtering.\n */\nfunction applyChainSpecificFilters(\n hexChainId: ChainId,\n items: ApiTokenListItem[],\n): ApiTokenListItem[] {\n if (hexChainId === ControllerChainId['linea-mainnet']) {\n return items.filter((item) => {\n const aggregators = item.aggregators ?? [];\n return aggregators.includes('lineaTeam') || aggregators.length >= 3;\n });\n }\n return items;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"TokensApiClient.mjs","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/clients/TokensApiClient.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,OAAO,IAAI,iBAAiB,EAC5B,mBAAmB,EACpB,mCAAmC;AAIpC;;;;;GAKG;AACH,MAAM,mBAAmB,GAAG,kCAAkC,CAAC;AAE/D;;;;GAIG;AACH,MAAM,sBAAsB,GAAG,GAAG,mBAAmB,uBAAuB,CAAC;AAE7E;;;;GAIG;AACH,MAAM,+BAA+B,GAAG,GAAG,mBAAmB,+BAA+B,CAAC;AAE9F;;;GAGG;AACH,MAAM,wBAAwB,GAAG,CAAC,CAAC;AAEnC;;;;;GAKG;AACH,MAAM,+BAA+B,GAAG,EAAE,GAAG,KAAM,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CAAC,IAAI,WAAW,CAAC,MAAM,IAAI,CAAC,CAAC;QACtE,CAAC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import {\n ChainId as ControllerChainId,\n convertHexToDecimal,\n} from '@metamask/controller-utils';\n\nimport type { ChainId, TokenListEntry } from '../types';\n\n/**\n * Same host + path that `TokenListController` (assets-controllers) uses\n * (`token-service.ts` → `getTokensURL`). Sharing this endpoint keeps the\n * RPC token detector aligned with the rest of the wallet's token listing\n * (occurrence floors, aggregator filters, icon URLs, etc.).\n */\nconst TOKEN_END_POINT_API = 'https://token.api.cx.metamask.io';\n\n/**\n * Endpoint that returns which CAIP chain IDs the Tokens API supports.\n * Used to skip detection (and avoid unnecessary network requests) for chains\n * that are not in the supported-networks list.\n */\nconst SUPPORTED_NETWORKS_URL = `${TOKEN_END_POINT_API}/v2/supportedNetworks`;\n\n/**\n * Per-chain suggested occurrence floors used as the `occurrenceFloor` query\n * param when fetching token lists (and aligned with TokenDataSource spam\n * filtering). Keys are decimal chain IDs.\n */\nconst SUGGESTED_OCCURRENCE_FLOORS_URL = `${TOKEN_END_POINT_API}/v1/suggestedOccurrenceFloors`;\n\n/**\n * Fallback `occurrenceFloor` when `/v1/suggestedOccurrenceFloors` has no entry\n * for the chain, or the floors request fails.\n */\nconst DEFAULT_OCCURRENCE_FLOOR = 3;\n\n/**\n * How long to keep the supported-networks response in the instance-level\n * cache before refreshing it. One hour is sufficient — the list rarely\n * changes and a stale cache just means we may do an unnecessary token-list\n * fetch for a newly-unsupported chain (harmless).\n */\nconst SUPPORTED_NETWORKS_CACHE_TTL_MS = 60 * 60_000;\n\n/**\n * How long to keep suggested occurrence floors cached. Same TTL as supported\n * networks — floors change infrequently.\n */\nconst SUGGESTED_OCCURRENCE_FLOORS_CACHE_TTL_MS = 60 * 60_000;\n\n/**\n * TanStack-Query cache config for the cached `fetchTokenList` path.\n *\n * The Tokens API per-chain list barely changes between polls, so we keep\n * results fresh for a few minutes (`staleTime`) and retain them in cache for\n * an hour (`gcTime`) so re-detections across accounts/chains hit the cache.\n * These tunings only apply when a `queryClient` is provided to the client;\n * the uncached fallback path (used in standalone tests) is unaffected.\n */\nconst TOKEN_LIST_STALE_TIME_MS = 5 * 60_000;\nconst TOKEN_LIST_GC_TIME_MS = 60 * 60_000;\n\n/**\n * Shape of the `/v2/supportedNetworks` response.\n */\ntype SupportedNetworksResponse = {\n fullSupport?: string[];\n partialSupport?: string[];\n};\n\n/**\n * Shape of a single item returned by the Tokens API `/tokens/{chainId}`\n * endpoint. Mirrors `TokenListToken` in\n * `packages/assets-controllers/src/TokenListController.ts` and the response\n * parsed by `fetchTokenListByChainId` in `token-service.ts`.\n */\ntype ApiTokenListItem = {\n address: string;\n symbol?: string;\n name?: string;\n decimals?: number;\n occurrences?: number;\n aggregators?: string[];\n iconUrl?: string;\n};\n\n/**\n * Minimal structural type for the TanStack Query client method we use.\n * Avoids a direct dependency on `@tanstack/query-core` while still being\n * fully compatible with the shared `QueryClient` exposed by\n * `ApiPlatformClient.queryClient` (`@metamask/core-backend`).\n */\nexport type TokenListQueryClient = {\n fetchQuery<TData>(options: {\n queryKey: readonly unknown[];\n queryFn: () => Promise<TData>;\n staleTime?: number;\n gcTime?: number;\n }): Promise<TData>;\n};\n\nexport type TokensApiClientConfig = {\n /** Fetch function (defaults to globalThis.fetch). */\n fetch?: typeof globalThis.fetch;\n /**\n * Optional TanStack-Query client used to cache token-list responses across\n * detector polls / accounts / instances. When omitted, every call hits the\n * network directly (preserves prior behaviour for tests and standalone use).\n */\n queryClient?: TokenListQueryClient;\n};\n\n/**\n * Client for the MetaMask Tokens API.\n *\n * Fetches the per-chain ERC-20 token list from the same endpoint that\n * `TokenListController` uses (`token.api.cx.metamask.io/tokens/{chainId}`),\n * with the same query parameters. The `occurrenceFloor` query param comes from\n * Token API `/v1/suggestedOccurrenceFloors` (fallback {@link DEFAULT_OCCURRENCE_FLOOR}),\n * matching `TokenDataSource` spam filtering. Linea's post-response aggregator\n * filter is still applied client-side.\n *\n * Before fetching a chain's token list, the client checks\n * `/v2/supportedNetworks` and returns `[]` immediately for chains that are\n * not in the supported list, avoiding unnecessary API calls. The supported-\n * networks response is cached in-memory for one hour.\n *\n * When constructed with a `queryClient`, token-list results are cached and\n * deduped via TanStack Query (5 min staleTime, 1 h gcTime), so concurrent\n * detection cycles for the same chain coalesce into a single network request.\n */\nexport class TokensApiClient {\n readonly #fetch: typeof globalThis.fetch;\n\n readonly #queryClient: TokenListQueryClient | undefined;\n\n /** CAIP chain IDs returned by `/v2/supportedNetworks` (both tiers). */\n #supportedChainIds: Set<string> | undefined;\n\n /** Timestamp of the last successful `/v2/supportedNetworks` fetch. */\n #supportedChainIdsCachedAt = 0;\n\n /**\n * In-flight `/v2/supportedNetworks` request shared across concurrent callers\n * so only one network request is made even when multiple `fetchTokenList`\n * calls arrive before the first one resolves.\n */\n #supportedChainIdsRefreshPromise: Promise<void> | undefined;\n\n /** Decimal chain ID → suggested occurrence floor from Token API. */\n #suggestedOccurrenceFloors: Record<string, number> | undefined;\n\n /** Timestamp of the last successful floors fetch. */\n #suggestedOccurrenceFloorsCachedAt = 0;\n\n /** In-flight floors request shared across concurrent callers. */\n #suggestedOccurrenceFloorsRefreshPromise: Promise<void> | undefined;\n\n constructor(config?: TokensApiClientConfig) {\n this.#fetch = config?.fetch ?? globalThis.fetch.bind(globalThis);\n this.#queryClient = config?.queryClient;\n }\n\n /**\n * Fetch the list of ERC-20 tokens for a chain from the Tokens API.\n *\n * Returns `[]` immediately (without hitting the token-list endpoint) when\n * the chain is not in the `/v2/supportedNetworks` response, or when the\n * supported-networks check fails for any reason.\n *\n * @param hexChainId - Chain ID in hex format (e.g. `'0x1'` for Ethereum mainnet).\n * @returns Array of token list entries with address and metadata, or an empty\n * array if the chain is unsupported or the request fails.\n */\n async fetchTokenList(hexChainId: ChainId): Promise<TokenListEntry[]> {\n // Treat any error from the supported-networks check as \"not supported\":\n // the token-list endpoint is only contacted for known-supported chains.\n if (!(await this.#isSupportedChain(hexChainId).catch(() => false))) {\n return [];\n }\n\n const queryClient = this.#queryClient;\n if (queryClient === undefined) {\n return this.#fetchTokenListUncached(hexChainId);\n }\n\n return queryClient.fetchQuery({\n // Namespacing keeps this key from colliding with other clients that\n // share the same QueryClient (e.g. core-backend's ApiPlatformClient).\n queryKey: [\n 'assets-controller',\n 'rpc-detection',\n 'token-list',\n { chainId: hexChainId },\n ],\n queryFn: () => this.#fetchTokenListUncached(hexChainId),\n staleTime: TOKEN_LIST_STALE_TIME_MS,\n gcTime: TOKEN_LIST_GC_TIME_MS,\n });\n }\n\n /**\n * Check whether the given chain is present in the supported-networks list.\n *\n * Uses an instance-level cache (1 h TTL). Throws if the network request\n * fails — callers should handle this (e.g. via `.catch(() => false)`).\n *\n * @param hexChainId - Hex chain ID to check.\n * @returns `true` when the chain is in the supported-networks list.\n */\n async #isSupportedChain(hexChainId: ChainId): Promise<boolean> {\n const now = Date.now();\n if (\n this.#supportedChainIds === undefined ||\n now - this.#supportedChainIdsCachedAt >= SUPPORTED_NETWORKS_CACHE_TTL_MS\n ) {\n await this.#refreshSupportedChainIds(now);\n }\n\n const caipChainId = `eip155:${convertHexToDecimal(hexChainId)}`;\n return this.#supportedChainIds?.has(caipChainId) ?? false;\n }\n\n /**\n * Fetch `/v2/supportedNetworks` and update the instance cache.\n * Concurrent callers share the same in-flight Promise so only one network\n * request is made. If the response is not 2xx the cache is left unchanged\n * (the chain will be treated as unsupported this cycle).\n *\n * @param now - Current timestamp used to stamp the cache entry.\n * @returns A promise that resolves once the cache has been refreshed.\n */\n async #refreshSupportedChainIds(now: number): Promise<void> {\n if (this.#supportedChainIdsRefreshPromise !== undefined) {\n return this.#supportedChainIdsRefreshPromise;\n }\n\n this.#supportedChainIdsRefreshPromise = (async (): Promise<void> => {\n try {\n const response = await this.#fetch(SUPPORTED_NETWORKS_URL);\n if (response.ok) {\n const data = (await response.json()) as SupportedNetworksResponse;\n this.#supportedChainIds = new Set([\n ...(data.fullSupport ?? []),\n ...(data.partialSupport ?? []),\n ]);\n this.#supportedChainIdsCachedAt = now;\n }\n } finally {\n this.#supportedChainIdsRefreshPromise = undefined;\n }\n })();\n\n return this.#supportedChainIdsRefreshPromise;\n }\n\n /**\n * Resolve the `occurrenceFloor` query param for a chain from Token API\n * `/v1/suggestedOccurrenceFloors`. Falls back to\n * {@link DEFAULT_OCCURRENCE_FLOOR} when the chain is missing or the request\n * fails.\n *\n * @param hexChainId - Hex chain ID.\n * @returns Occurrence floor to send to `/tokens/{chainId}`.\n */\n async #getOccurrenceFloor(hexChainId: ChainId): Promise<number> {\n const now = Date.now();\n if (\n this.#suggestedOccurrenceFloors === undefined ||\n now - this.#suggestedOccurrenceFloorsCachedAt >=\n SUGGESTED_OCCURRENCE_FLOORS_CACHE_TTL_MS\n ) {\n await this.#refreshSuggestedOccurrenceFloors(now);\n }\n\n const decimalChainId = String(convertHexToDecimal(hexChainId));\n return (\n this.#suggestedOccurrenceFloors?.[decimalChainId] ??\n DEFAULT_OCCURRENCE_FLOOR\n );\n }\n\n /**\n * Fetch `/v1/suggestedOccurrenceFloors` and update the instance cache.\n * Concurrent callers share the in-flight Promise. Failures leave the cache\n * empty so {@link #getOccurrenceFloor} falls back to the default.\n *\n * @param now - Current timestamp used to stamp the cache entry.\n * @returns A promise that resolves once the cache has been refreshed.\n */\n async #refreshSuggestedOccurrenceFloors(now: number): Promise<void> {\n if (this.#suggestedOccurrenceFloorsRefreshPromise !== undefined) {\n return this.#suggestedOccurrenceFloorsRefreshPromise;\n }\n\n this.#suggestedOccurrenceFloorsRefreshPromise =\n (async (): Promise<void> => {\n try {\n const response = await this.#fetch(SUGGESTED_OCCURRENCE_FLOORS_URL);\n if (response.ok) {\n const data = (await response.json()) as Record<string, number>;\n this.#suggestedOccurrenceFloors =\n data && typeof data === 'object' && !Array.isArray(data)\n ? data\n : {};\n this.#suggestedOccurrenceFloorsCachedAt = now;\n } else {\n this.#suggestedOccurrenceFloors = {};\n this.#suggestedOccurrenceFloorsCachedAt = now;\n }\n } catch {\n this.#suggestedOccurrenceFloors = {};\n this.#suggestedOccurrenceFloorsCachedAt = now;\n } finally {\n this.#suggestedOccurrenceFloorsRefreshPromise = undefined;\n }\n })();\n\n return this.#suggestedOccurrenceFloorsRefreshPromise;\n }\n\n async #fetchTokenListUncached(\n hexChainId: ChainId,\n ): Promise<TokenListEntry[]> {\n const decimalChainId = convertHexToDecimal(hexChainId);\n const occurrenceFloor = await this.#getOccurrenceFloor(hexChainId);\n\n // Same query shape as `TokenListController.getTokensURL` (token-service.ts),\n // but `occurrenceFloor` comes from `/v1/suggestedOccurrenceFloors`.\n // No `first=...` cap — the API returns the full per-chain list bounded\n // server-side by `occurrenceFloor`.\n const url =\n `${TOKEN_END_POINT_API}/tokens/${decimalChainId}` +\n `?occurrenceFloor=${occurrenceFloor}` +\n `&includeNativeAssets=false` +\n `&includeTokenFees=false` +\n `&includeAssetType=false` +\n `&includeERC20Permit=false` +\n `&includeStorage=false` +\n `&includeRwaData=true`;\n\n let response: Response;\n try {\n response = await this.#fetch(url);\n } catch (error) {\n console.error(\n `Tokens API request failed for chain ${hexChainId}:`,\n error,\n );\n return [];\n }\n\n if (!response.ok) {\n console.error(\n `Tokens API responded with ${response.status} for chain ${hexChainId}`,\n );\n return [];\n }\n\n const raw = (await response.json()) as unknown;\n const items: ApiTokenListItem[] = Array.isArray(raw)\n ? (raw as ApiTokenListItem[])\n : [];\n\n const filtered = applyChainSpecificFilters(hexChainId, items);\n\n return filtered.map((item) => ({\n address: item.address,\n symbol: item.symbol ?? '',\n name: item.name ?? '',\n decimals: item.decimals ?? 18,\n iconUrl: item.iconUrl,\n aggregators: item.aggregators,\n occurrences: item.occurrences,\n }));\n }\n}\n\n/**\n * Apply chain-specific filters to a raw token list response, mirroring\n * `fetchTokenListByChainId` in `assets-controllers/src/token-service.ts`.\n *\n * For Linea mainnet, the API returns extras with low aggregator coverage, so\n * we keep only entries flagged by Linea's own team or seen by ≥3 aggregators.\n *\n * @param hexChainId - Hex chain ID.\n * @param items - Raw items from the API response.\n * @returns Items after chain-specific filtering.\n */\nfunction applyChainSpecificFilters(\n hexChainId: ChainId,\n items: ApiTokenListItem[],\n): ApiTokenListItem[] {\n if (hexChainId === ControllerChainId['linea-mainnet']) {\n return items.filter((item) => {\n const aggregators = item.aggregators ?? [];\n return aggregators.includes('lineaTeam') || aggregators.length >= 3;\n });\n }\n return items;\n}\n"]}
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,yBAAyB;AACzB,2DAG4B;AAF1B,oHAAA,gBAAgB,OAAA;AAChB,mIAAA,+BAA+B,OAAA;AAEjC,uCAAiD;AAAxC,+GAAA,qBAAqB,OAAA;AAC9B,2CAOoB;AANlB,2HAAA,+BAA+B,OAAA;AAC/B,8HAAA,kCAAkC,OAAA;AAClC,kHAAA,sBAAsB,OAAA;AACtB,kHAAA,sBAAsB,OAAA;AACtB,2HAAA,+BAA+B,OAAA;AAC/B,mHAAA,uBAAuB,OAAA;
|
|
1
|
+
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,yBAAyB;AACzB,2DAG4B;AAF1B,oHAAA,gBAAgB,OAAA;AAChB,mIAAA,+BAA+B,OAAA;AAEjC,uCAAiD;AAAxC,+GAAA,qBAAqB,OAAA;AAC9B,2CAOoB;AANlB,2HAAA,+BAA+B,OAAA;AAC/B,8HAAA,kCAAkC,OAAA;AAClC,kHAAA,sBAAsB,OAAA;AACtB,kHAAA,sBAAsB,OAAA;AACtB,2HAAA,+BAA+B,OAAA;AAC/B,mHAAA,uBAAuB,OAAA;AAuFzB,sCAAsC;AACtC,yDAAoD;AAA3C,kHAAA,kBAAkB,OAAA;AAI3B,6BAA6B;AAC7B,yDAAuD;AAA9C,qHAAA,qBAAqB,OAAA;AAQ9B,kCAAkC;AAClC,yDAGwB;AAFtB,0HAAA,0BAA0B,OAAA;AAC1B,gIAAA,gCAAgC,OAAA;AAQlC,qBAAqB;AACrB,yDAAoE;AAA3D,6GAAA,aAAa,OAAA;AAAE,mHAAA,mBAAmB,OAAA;AAS3C,gFAAgF;AAChF,yDASwB;AARtB,8GAAA,cAAc,OAAA;AACd,oHAAA,oBAAoB,OAAA;AACpB,qHAAA,qBAAqB,OAAA;AACrB,YAAY;AACZ,kHAAA,kBAAkB,OAAA;AAClB,oBAAoB;AACpB,iHAAA,iBAAiB,OAAA;AACjB,uHAAA,uBAAuB,OAAA;AAQzB,0BAA0B;AAC1B,yDAAkE;AAAzD,+GAAA,eAAe,OAAA;AAAE,+GAAA,eAAe,OAAA;AAQzC,cAAc;AACd,uDAIuB;AAHrB,8HAAA,+BAA+B,OAAA;AAC/B,kHAAA,mBAAmB,OAAA;AACnB,oHAAA,qBAAqB,OAAA;AAOvB,YAAY;AACZ,2CAIiB;AAHf,yGAAA,gBAAgB,OAAA;AAChB,qHAAA,4BAA4B,OAAA;AAC5B,qHAAA,4BAA4B,OAAA;AAW9B,YAAY;AACZ,mDAM6B;AAL3B,wHAAA,6BAA6B,OAAA;AAC7B,gIAAA,qCAAqC,OAAA;AACrC,yHAAA,8BAA8B,OAAA;AAC9B,+GAAA,oBAAoB,OAAA;AACpB,sHAAA,2BAA2B,OAAA","sourcesContent":["// Main controller export\nexport {\n AssetsController,\n getDefaultAssetsControllerState,\n} from './AssetsController';\nexport { AssetsDataSourceError } from './errors';\nexport {\n DEFAULT_TRACKED_ASSETS_BY_CHAIN,\n CHAINS_WITH_DEFAULT_TRACKED_ASSETS,\n DEFAULT_ASSET_METADATA,\n buildDefaultAssetsInfo,\n getDefaultTrackedAssetsForChain,\n getDefaultAssetMetadata,\n} from './defaults';\nexport type { PendingTokenMetadata } from './AssetsController';\n\n// State and messenger types\nexport type {\n AssetsControllerState,\n AssetsControllerMessenger,\n AssetsControllerOptions,\n AssetsControllerGetStateAction,\n AssetsControllerActions,\n AssetsControllerStateChangeEvent,\n AssetsControllerBalanceChangedEvent,\n AssetsControllerPriceChangedEvent,\n AssetsControllerAssetsDetectedEvent,\n AssetsControllerEvents,\n} from './AssetsController';\nexport type {\n AssetsControllerGetAssetsAction,\n AssetsControllerGetAssetsBalanceAction,\n AssetsControllerGetAssetMetadataAction,\n AssetsControllerGetAssetAction,\n AssetsControllerGetAssetsPriceAction,\n AssetsControllerAddCustomAssetAction,\n AssetsControllerRemoveCustomAssetAction,\n AssetsControllerGetCustomAssetsAction,\n AssetsControllerHideAssetAction,\n AssetsControllerUnhideAssetAction,\n AssetsControllerGetExchangeRatesForBridgeAction,\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerSetSelectedCurrencyAction,\n} from './AssetsController-method-action-types';\n\n// Core types\nexport type {\n // CAIP types\n Caip19AssetId,\n AccountId,\n ChainId,\n // Asset types\n AssetType,\n TokenStandard,\n // Contract data types\n TokenFees,\n HoneypotStatus,\n StorageSlots,\n LocalizedDescription,\n // Metadata types\n BaseAssetMetadata,\n FungibleAssetMetadata,\n ERC721AssetMetadata,\n ERC1155AssetMetadata,\n AssetMetadata,\n // Price types\n BaseAssetPrice,\n FungibleAssetPrice,\n NFTAssetPrice,\n AssetPrice,\n // Balance types\n FungibleAssetBalance,\n ERC721AssetBalance,\n ERC1155AssetBalance,\n AssetBalance,\n // Data source types\n AccountWithSupportedChains,\n DataType,\n DataRequest,\n DataResponse,\n AssetsUpdateMode,\n // Middleware types\n Context,\n NextFunction,\n Middleware,\n AssetsDataSource,\n FetchContext,\n FetchNextFunction,\n FetchMiddleware,\n SubscriptionResponse,\n // Combined asset type\n Asset,\n // Event types\n BalanceChangeEvent,\n PriceChangeEvent,\n MetadataChangeEvent,\n AssetsDetectedEvent,\n} from './types';\n\n// Data sources - base class and types\nexport { AbstractDataSource } from './data-sources';\n\nexport type { DataSourceState, SubscriptionRequest } from './data-sources';\n\n// Data sources - AccountsApi\nexport { AccountsApiDataSource } from './data-sources';\n\nexport type {\n AccountsApiDataSourceConfig,\n AccountsApiDataSourceOptions,\n AccountsApiDataSourceState,\n} from './data-sources';\n\n// Data sources - BackendWebsocket\nexport {\n BackendWebsocketDataSource,\n createBackendWebsocketDataSource,\n} from './data-sources';\n\nexport type {\n BackendWebsocketDataSourceOptions,\n BackendWebsocketDataSourceState,\n} from './data-sources';\n\n// Data sources - RPC\nexport { RpcDataSource, createRpcDataSource } from './data-sources';\n\nexport type {\n RpcDataSourceConfig,\n RpcDataSourceOptions,\n RpcDataSourceState,\n ChainStatus,\n} from './data-sources';\n\n// Data sources - Unified Snap Data Source (dynamically discovers keyring snaps)\nexport {\n SnapDataSource,\n createSnapDataSource,\n SNAP_DATA_SOURCE_NAME,\n // Constants\n KEYRING_PERMISSION,\n // Utility functions\n getChainIdsCaveat,\n extractChainFromAssetId,\n} from './data-sources';\n\nexport type {\n SnapDataSourceState,\n SnapDataSourceOptions,\n} from './data-sources';\n\n// Enrichment data sources\nexport { TokenDataSource, PriceDataSource } from './data-sources';\n\nexport type {\n TokenDataSourceOptions,\n PriceDataSourceConfig,\n PriceDataSourceOptions,\n} from './data-sources';\n\n// Middlewares\nexport {\n CustomAssetGraduationMiddleware,\n DetectionMiddleware,\n RpcFallbackMiddleware,\n} from './middlewares';\nexport type {\n CustomAssetGraduationMiddlewareOptions,\n RpcFallbackMiddlewareOptions,\n} from './middlewares';\n\n// Utilities\nexport {\n normalizeAssetId,\n formatExchangeRatesForBridge,\n formatStateForTransactionPay,\n} from './utils';\nexport type {\n AccountForLegacyFormat,\n BridgeExchangeRatesFormat,\n FormatExchangeRatesForBridgeParams,\n FormatStateForTransactionPayParams,\n LegacyToken,\n TransactionPayLegacyFormat,\n} from './utils';\n\n// Selectors\nexport {\n calculateBalanceForAllWallets,\n calculateBalanceChangeForAccountGroup,\n getAggregatedBalanceForAccount,\n getGroupIdForAccount,\n getInternalAccountsForGroup,\n} from './selectors/balance';\n\nexport type {\n AccountGroupBalance,\n AccountsById,\n AggregatedBalanceEntry,\n AggregatedBalanceForAccount,\n AllWalletsBalance,\n BalanceChangePeriod,\n BalanceChangeResult,\n EnabledNetworkMap,\n WalletBalance,\n} from './selectors/balance';\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -3,7 +3,7 @@ export { AssetsDataSourceError } from "./errors.cjs";
|
|
|
3
3
|
export { DEFAULT_TRACKED_ASSETS_BY_CHAIN, CHAINS_WITH_DEFAULT_TRACKED_ASSETS, DEFAULT_ASSET_METADATA, buildDefaultAssetsInfo, getDefaultTrackedAssetsForChain, getDefaultAssetMetadata, } from "./defaults.cjs";
|
|
4
4
|
export type { PendingTokenMetadata } from "./AssetsController.cjs";
|
|
5
5
|
export type { AssetsControllerState, AssetsControllerMessenger, AssetsControllerOptions, AssetsControllerGetStateAction, AssetsControllerActions, AssetsControllerStateChangeEvent, AssetsControllerBalanceChangedEvent, AssetsControllerPriceChangedEvent, AssetsControllerAssetsDetectedEvent, AssetsControllerEvents, } from "./AssetsController.cjs";
|
|
6
|
-
export type { AssetsControllerGetAssetsAction, AssetsControllerGetAssetsBalanceAction, AssetsControllerGetAssetMetadataAction, AssetsControllerGetAssetsPriceAction, AssetsControllerAddCustomAssetAction, AssetsControllerRemoveCustomAssetAction, AssetsControllerGetCustomAssetsAction, AssetsControllerHideAssetAction, AssetsControllerUnhideAssetAction, AssetsControllerGetExchangeRatesForBridgeAction, AssetsControllerGetStateForTransactionPayAction, AssetsControllerSetSelectedCurrencyAction, } from "./AssetsController-method-action-types.cjs";
|
|
6
|
+
export type { AssetsControllerGetAssetsAction, AssetsControllerGetAssetsBalanceAction, AssetsControllerGetAssetMetadataAction, AssetsControllerGetAssetAction, AssetsControllerGetAssetsPriceAction, AssetsControllerAddCustomAssetAction, AssetsControllerRemoveCustomAssetAction, AssetsControllerGetCustomAssetsAction, AssetsControllerHideAssetAction, AssetsControllerUnhideAssetAction, AssetsControllerGetExchangeRatesForBridgeAction, AssetsControllerGetStateForTransactionPayAction, AssetsControllerSetSelectedCurrencyAction, } from "./AssetsController-method-action-types.cjs";
|
|
7
7
|
export type { Caip19AssetId, AccountId, ChainId, AssetType, TokenStandard, TokenFees, HoneypotStatus, StorageSlots, LocalizedDescription, BaseAssetMetadata, FungibleAssetMetadata, ERC721AssetMetadata, ERC1155AssetMetadata, AssetMetadata, BaseAssetPrice, FungibleAssetPrice, NFTAssetPrice, AssetPrice, FungibleAssetBalance, ERC721AssetBalance, ERC1155AssetBalance, AssetBalance, AccountWithSupportedChains, DataType, DataRequest, DataResponse, AssetsUpdateMode, Context, NextFunction, Middleware, AssetsDataSource, FetchContext, FetchNextFunction, FetchMiddleware, SubscriptionResponse, Asset, BalanceChangeEvent, PriceChangeEvent, MetadataChangeEvent, AssetsDetectedEvent, } from "./types.cjs";
|
|
8
8
|
export { AbstractDataSource } from "./data-sources/index.cjs";
|
|
9
9
|
export type { DataSourceState, SubscriptionRequest } from "./data-sources/index.cjs";
|
|
@@ -20,7 +20,7 @@ export type { TokenDataSourceOptions, PriceDataSourceConfig, PriceDataSourceOpti
|
|
|
20
20
|
export { CustomAssetGraduationMiddleware, DetectionMiddleware, RpcFallbackMiddleware, } from "./middlewares/index.cjs";
|
|
21
21
|
export type { CustomAssetGraduationMiddlewareOptions, RpcFallbackMiddlewareOptions, } from "./middlewares/index.cjs";
|
|
22
22
|
export { normalizeAssetId, formatExchangeRatesForBridge, formatStateForTransactionPay, } from "./utils/index.cjs";
|
|
23
|
-
export type { AccountForLegacyFormat, BridgeExchangeRatesFormat, LegacyToken, TransactionPayLegacyFormat, } from "./utils/index.cjs";
|
|
23
|
+
export type { AccountForLegacyFormat, BridgeExchangeRatesFormat, FormatExchangeRatesForBridgeParams, FormatStateForTransactionPayParams, LegacyToken, TransactionPayLegacyFormat, } from "./utils/index.cjs";
|
|
24
24
|
export { calculateBalanceForAllWallets, calculateBalanceChangeForAccountGroup, getAggregatedBalanceForAccount, getGroupIdForAccount, getInternalAccountsForGroup, } from "./selectors/balance.cjs";
|
|
25
25
|
export type { AccountGroupBalance, AccountsById, AggregatedBalanceEntry, AggregatedBalanceForAccount, AllWalletsBalance, BalanceChangePeriod, BalanceChangeResult, EnabledNetworkMap, WalletBalance, } from "./selectors/balance.cjs";
|
|
26
26
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gBAAgB,EAChB,+BAA+B,GAChC,+BAA2B;AAC5B,OAAO,EAAE,qBAAqB,EAAE,qBAAiB;AACjD,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,EAClC,sBAAsB,EACtB,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,GACxB,uBAAmB;AACpB,YAAY,EAAE,oBAAoB,EAAE,+BAA2B;AAG/D,YAAY,EACV,qBAAqB,EACrB,yBAAyB,EACzB,uBAAuB,EACvB,8BAA8B,EAC9B,uBAAuB,EACvB,gCAAgC,EAChC,mCAAmC,EACnC,iCAAiC,EACjC,mCAAmC,EACnC,sBAAsB,GACvB,+BAA2B;AAC5B,YAAY,EACV,+BAA+B,EAC/B,sCAAsC,EACtC,sCAAsC,EACtC,oCAAoC,EACpC,oCAAoC,EACpC,uCAAuC,EACvC,qCAAqC,EACrC,+BAA+B,EAC/B,iCAAiC,EACjC,+CAA+C,EAC/C,+CAA+C,EAC/C,yCAAyC,GAC1C,mDAA+C;AAGhD,YAAY,EAEV,aAAa,EACb,SAAS,EACT,OAAO,EAEP,SAAS,EACT,aAAa,EAEb,SAAS,EACT,cAAc,EACd,YAAY,EACZ,oBAAoB,EAEpB,iBAAiB,EACjB,qBAAqB,EACrB,mBAAmB,EACnB,oBAAoB,EACpB,aAAa,EAEb,cAAc,EACd,kBAAkB,EAClB,aAAa,EACb,UAAU,EAEV,oBAAoB,EACpB,kBAAkB,EAClB,mBAAmB,EACnB,YAAY,EAEZ,0BAA0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EACX,0BAA0B,GAC3B,0BAAgB;AAGjB,OAAO,EACL,6BAA6B,EAC7B,qCAAqC,EACrC,8BAA8B,EAC9B,oBAAoB,EACpB,2BAA2B,GAC5B,gCAA4B;AAE7B,YAAY,EACV,mBAAmB,EACnB,YAAY,EACZ,sBAAsB,EACtB,2BAA2B,EAC3B,iBAAiB,EACjB,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,aAAa,GACd,gCAA4B"}
|
|
1
|
+
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gBAAgB,EAChB,+BAA+B,GAChC,+BAA2B;AAC5B,OAAO,EAAE,qBAAqB,EAAE,qBAAiB;AACjD,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,EAClC,sBAAsB,EACtB,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,GACxB,uBAAmB;AACpB,YAAY,EAAE,oBAAoB,EAAE,+BAA2B;AAG/D,YAAY,EACV,qBAAqB,EACrB,yBAAyB,EACzB,uBAAuB,EACvB,8BAA8B,EAC9B,uBAAuB,EACvB,gCAAgC,EAChC,mCAAmC,EACnC,iCAAiC,EACjC,mCAAmC,EACnC,sBAAsB,GACvB,+BAA2B;AAC5B,YAAY,EACV,+BAA+B,EAC/B,sCAAsC,EACtC,sCAAsC,EACtC,8BAA8B,EAC9B,oCAAoC,EACpC,oCAAoC,EACpC,uCAAuC,EACvC,qCAAqC,EACrC,+BAA+B,EAC/B,iCAAiC,EACjC,+CAA+C,EAC/C,+CAA+C,EAC/C,yCAAyC,GAC1C,mDAA+C;AAGhD,YAAY,EAEV,aAAa,EACb,SAAS,EACT,OAAO,EAEP,SAAS,EACT,aAAa,EAEb,SAAS,EACT,cAAc,EACd,YAAY,EACZ,oBAAoB,EAEpB,iBAAiB,EACjB,qBAAqB,EACrB,mBAAmB,EACnB,oBAAoB,EACpB,aAAa,EAEb,cAAc,EACd,kBAAkB,EAClB,aAAa,EACb,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BAA4B,GAC7B,0BAAgB;AACjB,YAAY,EACV,sBAAsB,EACtB,yBAAyB,EACzB,kCAAkC,EAClC,kCAAkC,EAClC,WAAW,EACX,0BAA0B,GAC3B,0BAAgB;AAGjB,OAAO,EACL,6BAA6B,EAC7B,qCAAqC,EACrC,8BAA8B,EAC9B,oBAAoB,EACpB,2BAA2B,GAC5B,gCAA4B;AAE7B,YAAY,EACV,mBAAmB,EACnB,YAAY,EACZ,sBAAsB,EACtB,2BAA2B,EAC3B,iBAAiB,EACjB,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,aAAa,GACd,gCAA4B"}
|
package/dist/index.d.mts
CHANGED
|
@@ -3,7 +3,7 @@ export { AssetsDataSourceError } from "./errors.mjs";
|
|
|
3
3
|
export { DEFAULT_TRACKED_ASSETS_BY_CHAIN, CHAINS_WITH_DEFAULT_TRACKED_ASSETS, DEFAULT_ASSET_METADATA, buildDefaultAssetsInfo, getDefaultTrackedAssetsForChain, getDefaultAssetMetadata, } from "./defaults.mjs";
|
|
4
4
|
export type { PendingTokenMetadata } from "./AssetsController.mjs";
|
|
5
5
|
export type { AssetsControllerState, AssetsControllerMessenger, AssetsControllerOptions, AssetsControllerGetStateAction, AssetsControllerActions, AssetsControllerStateChangeEvent, AssetsControllerBalanceChangedEvent, AssetsControllerPriceChangedEvent, AssetsControllerAssetsDetectedEvent, AssetsControllerEvents, } from "./AssetsController.mjs";
|
|
6
|
-
export type { AssetsControllerGetAssetsAction, AssetsControllerGetAssetsBalanceAction, AssetsControllerGetAssetMetadataAction, AssetsControllerGetAssetsPriceAction, AssetsControllerAddCustomAssetAction, AssetsControllerRemoveCustomAssetAction, AssetsControllerGetCustomAssetsAction, AssetsControllerHideAssetAction, AssetsControllerUnhideAssetAction, AssetsControllerGetExchangeRatesForBridgeAction, AssetsControllerGetStateForTransactionPayAction, AssetsControllerSetSelectedCurrencyAction, } from "./AssetsController-method-action-types.mjs";
|
|
6
|
+
export type { AssetsControllerGetAssetsAction, AssetsControllerGetAssetsBalanceAction, AssetsControllerGetAssetMetadataAction, AssetsControllerGetAssetAction, AssetsControllerGetAssetsPriceAction, AssetsControllerAddCustomAssetAction, AssetsControllerRemoveCustomAssetAction, AssetsControllerGetCustomAssetsAction, AssetsControllerHideAssetAction, AssetsControllerUnhideAssetAction, AssetsControllerGetExchangeRatesForBridgeAction, AssetsControllerGetStateForTransactionPayAction, AssetsControllerSetSelectedCurrencyAction, } from "./AssetsController-method-action-types.mjs";
|
|
7
7
|
export type { Caip19AssetId, AccountId, ChainId, AssetType, TokenStandard, TokenFees, HoneypotStatus, StorageSlots, LocalizedDescription, BaseAssetMetadata, FungibleAssetMetadata, ERC721AssetMetadata, ERC1155AssetMetadata, AssetMetadata, BaseAssetPrice, FungibleAssetPrice, NFTAssetPrice, AssetPrice, FungibleAssetBalance, ERC721AssetBalance, ERC1155AssetBalance, AssetBalance, AccountWithSupportedChains, DataType, DataRequest, DataResponse, AssetsUpdateMode, Context, NextFunction, Middleware, AssetsDataSource, FetchContext, FetchNextFunction, FetchMiddleware, SubscriptionResponse, Asset, BalanceChangeEvent, PriceChangeEvent, MetadataChangeEvent, AssetsDetectedEvent, } from "./types.mjs";
|
|
8
8
|
export { AbstractDataSource } from "./data-sources/index.mjs";
|
|
9
9
|
export type { DataSourceState, SubscriptionRequest } from "./data-sources/index.mjs";
|
|
@@ -20,7 +20,7 @@ export type { TokenDataSourceOptions, PriceDataSourceConfig, PriceDataSourceOpti
|
|
|
20
20
|
export { CustomAssetGraduationMiddleware, DetectionMiddleware, RpcFallbackMiddleware, } from "./middlewares/index.mjs";
|
|
21
21
|
export type { CustomAssetGraduationMiddlewareOptions, RpcFallbackMiddlewareOptions, } from "./middlewares/index.mjs";
|
|
22
22
|
export { normalizeAssetId, formatExchangeRatesForBridge, formatStateForTransactionPay, } from "./utils/index.mjs";
|
|
23
|
-
export type { AccountForLegacyFormat, BridgeExchangeRatesFormat, LegacyToken, TransactionPayLegacyFormat, } from "./utils/index.mjs";
|
|
23
|
+
export type { AccountForLegacyFormat, BridgeExchangeRatesFormat, FormatExchangeRatesForBridgeParams, FormatStateForTransactionPayParams, LegacyToken, TransactionPayLegacyFormat, } from "./utils/index.mjs";
|
|
24
24
|
export { calculateBalanceForAllWallets, calculateBalanceChangeForAccountGroup, getAggregatedBalanceForAccount, getGroupIdForAccount, getInternalAccountsForGroup, } from "./selectors/balance.mjs";
|
|
25
25
|
export type { AccountGroupBalance, AccountsById, AggregatedBalanceEntry, AggregatedBalanceForAccount, AllWalletsBalance, BalanceChangePeriod, BalanceChangeResult, EnabledNetworkMap, WalletBalance, } from "./selectors/balance.mjs";
|
|
26
26
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gBAAgB,EAChB,+BAA+B,GAChC,+BAA2B;AAC5B,OAAO,EAAE,qBAAqB,EAAE,qBAAiB;AACjD,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,EAClC,sBAAsB,EACtB,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,GACxB,uBAAmB;AACpB,YAAY,EAAE,oBAAoB,EAAE,+BAA2B;AAG/D,YAAY,EACV,qBAAqB,EACrB,yBAAyB,EACzB,uBAAuB,EACvB,8BAA8B,EAC9B,uBAAuB,EACvB,gCAAgC,EAChC,mCAAmC,EACnC,iCAAiC,EACjC,mCAAmC,EACnC,sBAAsB,GACvB,+BAA2B;AAC5B,YAAY,EACV,+BAA+B,EAC/B,sCAAsC,EACtC,sCAAsC,EACtC,oCAAoC,EACpC,oCAAoC,EACpC,uCAAuC,EACvC,qCAAqC,EACrC,+BAA+B,EAC/B,iCAAiC,EACjC,+CAA+C,EAC/C,+CAA+C,EAC/C,yCAAyC,GAC1C,mDAA+C;AAGhD,YAAY,EAEV,aAAa,EACb,SAAS,EACT,OAAO,EAEP,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B;AAGxB,OAAO,EACL,+BAA+B,EAC/B,mBAAmB,EACnB,qBAAqB,GACtB,gCAAsB;AACvB,YAAY,EACV,sCAAsC,EACtC,4BAA4B,GAC7B,gCAAsB;AAGvB,OAAO,EACL,gBAAgB,EAChB,4BAA4B,EAC5B,4BAA4B,GAC7B,0BAAgB;AACjB,YAAY,EACV,sBAAsB,EACtB,yBAAyB,EACzB,WAAW,EACX,0BAA0B,GAC3B,0BAAgB;AAGjB,OAAO,EACL,6BAA6B,EAC7B,qCAAqC,EACrC,8BAA8B,EAC9B,oBAAoB,EACpB,2BAA2B,GAC5B,gCAA4B;AAE7B,YAAY,EACV,mBAAmB,EACnB,YAAY,EACZ,sBAAsB,EACtB,2BAA2B,EAC3B,iBAAiB,EACjB,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,aAAa,GACd,gCAA4B"}
|
|
1
|
+
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gBAAgB,EAChB,+BAA+B,GAChC,+BAA2B;AAC5B,OAAO,EAAE,qBAAqB,EAAE,qBAAiB;AACjD,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,EAClC,sBAAsB,EACtB,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,GACxB,uBAAmB;AACpB,YAAY,EAAE,oBAAoB,EAAE,+BAA2B;AAG/D,YAAY,EACV,qBAAqB,EACrB,yBAAyB,EACzB,uBAAuB,EACvB,8BAA8B,EAC9B,uBAAuB,EACvB,gCAAgC,EAChC,mCAAmC,EACnC,iCAAiC,EACjC,mCAAmC,EACnC,sBAAsB,GACvB,+BAA2B;AAC5B,YAAY,EACV,+BAA+B,EAC/B,sCAAsC,EACtC,sCAAsC,EACtC,8BAA8B,EAC9B,oCAAoC,EACpC,oCAAoC,EACpC,uCAAuC,EACvC,qCAAqC,EACrC,+BAA+B,EAC/B,iCAAiC,EACjC,+CAA+C,EAC/C,+CAA+C,EAC/C,yC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iCAAuB;AAElE,YAAY,EACV,sBAAsB,EACtB,qBAAqB,EACrB,sBAAsB,GACvB,iCAAuB;AAGxB,OAAO,EACL,+BAA+B,EAC/B,mBAAmB,EACnB,qBAAqB,GACtB,gCAAsB;AACvB,YAAY,EACV,sCAAsC,EACtC,4BAA4B,GAC7B,gCAAsB;AAGvB,OAAO,EACL,gBAAgB,EAChB,4BAA4B,EAC5B,4BAA4B,GAC7B,0BAAgB;AACjB,YAAY,EACV,sBAAsB,EACtB,yBAAyB,EACzB,kCAAkC,EAClC,kCAAkC,EAClC,WAAW,EACX,0BAA0B,GAC3B,0BAAgB;AAGjB,OAAO,EACL,6BAA6B,EAC7B,qCAAqC,EACrC,8BAA8B,EAC9B,oBAAoB,EACpB,2BAA2B,GAC5B,gCAA4B;AAE7B,YAAY,EACV,mBAAmB,EACnB,YAAY,EACZ,sBAAsB,EACtB,2BAA2B,EAC3B,iBAAiB,EACjB,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,aAAa,GACd,gCAA4B"}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,yBAAyB;AACzB,OAAO,EACL,gBAAgB,EAChB,+BAA+B,EAChC,+BAA2B;AAC5B,OAAO,EAAE,qBAAqB,EAAE,qBAAiB;AACjD,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,EAClC,sBAAsB,EACtB,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,EACxB,uBAAmB;
|
|
1
|
+
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,yBAAyB;AACzB,OAAO,EACL,gBAAgB,EAChB,+BAA+B,EAChC,+BAA2B;AAC5B,OAAO,EAAE,qBAAqB,EAAE,qBAAiB;AACjD,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,EAClC,sBAAsB,EACtB,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,EACxB,uBAAmB;AAsFpB,sCAAsC;AACtC,OAAO,EAAE,kBAAkB,EAAE,iCAAuB;AAIpD,6BAA6B;AAC7B,OAAO,EAAE,qBAAqB,EAAE,iCAAuB;AAQvD,kCAAkC;AAClC,OAAO,EACL,0BAA0B,EAC1B,gCAAgC,EACjC,iCAAuB;AAOxB,qBAAqB;AACrB,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,iCAAuB;AASpE,gFAAgF;AAChF,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,qBAAqB;AACrB,YAAY;AACZ,kBAAkB;AAClB,oBAAoB;AACpB,iBAAiB,EACjB,uBAAuB,EACxB,iCAAuB;AAOxB,0BAA0B;AAC1B,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,iCAAuB;AAQlE,cAAc;AACd,OAAO,EACL,+BAA+B,EAC/B,mBAAmB,EACnB,qBAAqB,EACtB,gCAAsB;AAMvB,YAAY;AACZ,OAAO,EACL,gBAAgB,EAChB,4BAA4B,EAC5B,4BAA4B,EAC7B,0BAAgB;AAUjB,YAAY;AACZ,OAAO,EACL,6BAA6B,EAC7B,qCAAqC,EACrC,8BAA8B,EAC9B,oBAAoB,EACpB,2BAA2B,EAC5B,gCAA4B","sourcesContent":["// Main controller export\nexport {\n AssetsController,\n getDefaultAssetsControllerState,\n} from './AssetsController';\nexport { AssetsDataSourceError } from './errors';\nexport {\n DEFAULT_TRACKED_ASSETS_BY_CHAIN,\n CHAINS_WITH_DEFAULT_TRACKED_ASSETS,\n DEFAULT_ASSET_METADATA,\n buildDefaultAssetsInfo,\n getDefaultTrackedAssetsForChain,\n getDefaultAssetMetadata,\n} from './defaults';\nexport type { PendingTokenMetadata } from './AssetsController';\n\n// State and messenger types\nexport type {\n AssetsControllerState,\n AssetsControllerMessenger,\n AssetsControllerOptions,\n AssetsControllerGetStateAction,\n AssetsControllerActions,\n AssetsControllerStateChangeEvent,\n AssetsControllerBalanceChangedEvent,\n AssetsControllerPriceChangedEvent,\n AssetsControllerAssetsDetectedEvent,\n AssetsControllerEvents,\n} from './AssetsController';\nexport type {\n AssetsControllerGetAssetsAction,\n AssetsControllerGetAssetsBalanceAction,\n AssetsControllerGetAssetMetadataAction,\n AssetsControllerGetAssetAction,\n AssetsControllerGetAssetsPriceAction,\n AssetsControllerAddCustomAssetAction,\n AssetsControllerRemoveCustomAssetAction,\n AssetsControllerGetCustomAssetsAction,\n AssetsControllerHideAssetAction,\n AssetsControllerUnhideAssetAction,\n AssetsControllerGetExchangeRatesForBridgeAction,\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerSetSelectedCurrencyAction,\n} from './AssetsController-method-action-types';\n\n// Core types\nexport type {\n // CAIP types\n Caip19AssetId,\n AccountId,\n ChainId,\n // Asset types\n AssetType,\n TokenStandard,\n // Contract data types\n TokenFees,\n HoneypotStatus,\n StorageSlots,\n LocalizedDescription,\n // Metadata types\n BaseAssetMetadata,\n FungibleAssetMetadata,\n ERC721AssetMetadata,\n ERC1155AssetMetadata,\n AssetMetadata,\n // Price types\n BaseAssetPrice,\n FungibleAssetPrice,\n NFTAssetPrice,\n AssetPrice,\n // Balance types\n FungibleAssetBalance,\n ERC721AssetBalance,\n ERC1155AssetBalance,\n AssetBalance,\n // Data source types\n AccountWithSupportedChains,\n DataType,\n DataRequest,\n DataResponse,\n AssetsUpdateMode,\n // Middleware types\n Context,\n NextFunction,\n Middleware,\n AssetsDataSource,\n FetchContext,\n FetchNextFunction,\n FetchMiddleware,\n SubscriptionResponse,\n // Combined asset type\n Asset,\n // Event types\n BalanceChangeEvent,\n PriceChangeEvent,\n MetadataChangeEvent,\n AssetsDetectedEvent,\n} from './types';\n\n// Data sources - base class and types\nexport { AbstractDataSource } from './data-sources';\n\nexport type { DataSourceState, SubscriptionRequest } from './data-sources';\n\n// Data sources - AccountsApi\nexport { AccountsApiDataSource } from './data-sources';\n\nexport type {\n AccountsApiDataSourceConfig,\n AccountsApiDataSourceOptions,\n AccountsApiDataSourceState,\n} from './data-sources';\n\n// Data sources - BackendWebsocket\nexport {\n BackendWebsocketDataSource,\n createBackendWebsocketDataSource,\n} from './data-sources';\n\nexport type {\n BackendWebsocketDataSourceOptions,\n BackendWebsocketDataSourceState,\n} from './data-sources';\n\n// Data sources - RPC\nexport { RpcDataSource, createRpcDataSource } from './data-sources';\n\nexport type {\n RpcDataSourceConfig,\n RpcDataSourceOptions,\n RpcDataSourceState,\n ChainStatus,\n} from './data-sources';\n\n// Data sources - Unified Snap Data Source (dynamically discovers keyring snaps)\nexport {\n SnapDataSource,\n createSnapDataSource,\n SNAP_DATA_SOURCE_NAME,\n // Constants\n KEYRING_PERMISSION,\n // Utility functions\n getChainIdsCaveat,\n extractChainFromAssetId,\n} from './data-sources';\n\nexport type {\n SnapDataSourceState,\n SnapDataSourceOptions,\n} from './data-sources';\n\n// Enrichment data sources\nexport { TokenDataSource, PriceDataSource } from './data-sources';\n\nexport type {\n TokenDataSourceOptions,\n PriceDataSourceConfig,\n PriceDataSourceOptions,\n} from './data-sources';\n\n// Middlewares\nexport {\n CustomAssetGraduationMiddleware,\n DetectionMiddleware,\n RpcFallbackMiddleware,\n} from './middlewares';\nexport type {\n CustomAssetGraduationMiddlewareOptions,\n RpcFallbackMiddlewareOptions,\n} from './middlewares';\n\n// Utilities\nexport {\n normalizeAssetId,\n formatExchangeRatesForBridge,\n formatStateForTransactionPay,\n} from './utils';\nexport type {\n AccountForLegacyFormat,\n BridgeExchangeRatesFormat,\n FormatExchangeRatesForBridgeParams,\n FormatStateForTransactionPayParams,\n LegacyToken,\n TransactionPayLegacyFormat,\n} from './utils';\n\n// Selectors\nexport {\n calculateBalanceForAllWallets,\n calculateBalanceChangeForAccountGroup,\n getAggregatedBalanceForAccount,\n getGroupIdForAccount,\n getInternalAccountsForGroup,\n} from './selectors/balance';\n\nexport type {\n AccountGroupBalance,\n AccountsById,\n AggregatedBalanceEntry,\n AggregatedBalanceForAccount,\n AllWalletsBalance,\n BalanceChangePeriod,\n BalanceChangeResult,\n EnabledNetworkMap,\n WalletBalance,\n} from './selectors/balance';\n"]}
|
|
@@ -1,25 +1,55 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.formatExchangeRatesForBridge = void 0;
|
|
3
|
+
exports.clearFormatExchangeRatesForBridgeCacheForTesting = exports.formatExchangeRatesForBridge = void 0;
|
|
4
4
|
const util_1 = require("@ethereumjs/util");
|
|
5
5
|
const assets_controllers_1 = require("@metamask/assets-controllers");
|
|
6
6
|
const utils_1 = require("@metamask/utils");
|
|
7
7
|
const utils_2 = require("@metamask/utils");
|
|
8
|
+
const lodash_1 = require("lodash");
|
|
9
|
+
let lastCall = null;
|
|
8
10
|
/**
|
|
9
11
|
* Converts AssetsController state (assetsPrice, selectedCurrency) into the
|
|
10
12
|
* same format the bridge expects from MultichainAssetsRatesController,
|
|
11
13
|
* CurrencyRateController, and TokenRatesController so the bridge can use
|
|
12
14
|
* a single action when useAssetsControllerForRates is true.
|
|
13
15
|
*
|
|
16
|
+
* Memoized on input identity for BaseController state slices (`===`) and
|
|
17
|
+
* lodash `isEqual` for rebuilt maps (`nativeAssetIdentifiers`). Bridge quote
|
|
18
|
+
* / rate paths call this repeatedly while assets state is unchanged; recomputing
|
|
19
|
+
* runs keccak256 (`toChecksumAddress`) and CAIP parsing per priced asset.
|
|
20
|
+
*
|
|
14
21
|
* @param params - Conversion parameters.
|
|
15
|
-
* @param params.assetsInfo - Metadata map keyed by CAIP-19 asset ID; used to determine native assets via `type === 'native'`.
|
|
16
|
-
* @param params.assetsPrice - Map of CAIP-19 asset ID to price data (must include both `price` and `usdPrice`).
|
|
17
|
-
* @param params.selectedCurrency - ISO 4217 currency code (e.g. 'usd').
|
|
18
|
-
* @param params.nativeAssetIdentifiers - Map of CAIP-2 chain ID to native asset ID. Used for EVM native lookups.
|
|
19
|
-
* @param params.networkConfigurationsByChainId - Optional map of Hex chain ID to network config (e.g. from NetworkController state). Used to resolve native currency symbol via `nativeCurrency`; keys are Hex (e.g. '0x1').
|
|
20
22
|
* @returns Bridge-compatible conversionRates, currencyRates, marketData, currentCurrency.
|
|
21
23
|
*/
|
|
22
24
|
function formatExchangeRatesForBridge(params) {
|
|
25
|
+
if (lastCall?.params.assetsInfo === params.assetsInfo &&
|
|
26
|
+
lastCall.params.assetsPrice === params.assetsPrice &&
|
|
27
|
+
lastCall.params.selectedCurrency === params.selectedCurrency &&
|
|
28
|
+
lastCall.params.networkConfigurationsByChainId ===
|
|
29
|
+
params.networkConfigurationsByChainId &&
|
|
30
|
+
(0, lodash_1.isEqual)(lastCall.params.nativeAssetIdentifiers, params.nativeAssetIdentifiers)) {
|
|
31
|
+
return lastCall.result;
|
|
32
|
+
}
|
|
33
|
+
const result = computeExchangeRatesForBridge(params);
|
|
34
|
+
lastCall = { params, result };
|
|
35
|
+
return result;
|
|
36
|
+
}
|
|
37
|
+
exports.formatExchangeRatesForBridge = formatExchangeRatesForBridge;
|
|
38
|
+
/**
|
|
39
|
+
* Clears the {@link formatExchangeRatesForBridge} memoize cache. Exported for tests.
|
|
40
|
+
*/
|
|
41
|
+
function clearFormatExchangeRatesForBridgeCacheForTesting() {
|
|
42
|
+
lastCall = null;
|
|
43
|
+
}
|
|
44
|
+
exports.clearFormatExchangeRatesForBridgeCacheForTesting = clearFormatExchangeRatesForBridgeCacheForTesting;
|
|
45
|
+
/**
|
|
46
|
+
* Performs the actual exchange-rate conversion for
|
|
47
|
+
* {@link formatExchangeRatesForBridge}.
|
|
48
|
+
*
|
|
49
|
+
* @param params - Conversion parameters.
|
|
50
|
+
* @returns Bridge-compatible rates.
|
|
51
|
+
*/
|
|
52
|
+
function computeExchangeRatesForBridge(params) {
|
|
23
53
|
const { assetsInfo, assetsPrice, selectedCurrency, nativeAssetIdentifiers, networkConfigurationsByChainId = {}, } = params;
|
|
24
54
|
const conversionRates = {};
|
|
25
55
|
const currencyRates = {};
|
|
@@ -128,5 +158,4 @@ function formatExchangeRatesForBridge(params) {
|
|
|
128
158
|
currentCurrency: selectedCurrency,
|
|
129
159
|
};
|
|
130
160
|
}
|
|
131
|
-
exports.formatExchangeRatesForBridge = formatExchangeRatesForBridge;
|
|
132
161
|
//# sourceMappingURL=formatExchangeRatesForBridge.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formatExchangeRatesForBridge.cjs","sourceRoot":"","sources":["../../src/utils/formatExchangeRatesForBridge.ts"],"names":[],"mappings":";;;AAAA,2CAAqD;AACrD,qEAOsC;AACtC,2CAAuE;AACvE,2CAAuE;AAqBvE;;;;;;;;;;;;;GAaG;AACH,SAAgB,4BAA4B,CAAC,MAM5C;IACC,MAAM,EACJ,UAAU,EACV,WAAW,EACX,gBAAgB,EAChB,sBAAsB,EACtB,8BAA8B,GAAG,EAAE,GACpC,GAAG,MAAM,CAAC;IACX,MAAM,eAAe,GACnB,EAAE,CAAC;IACL,MAAM,aAAa,GAAuC,EAAE,CAAC;IAC7D,MAAM,UAAU,GAA4C,EAAE,CAAC;IAE/D,MAAM,YAAY,GAAG,wCAAmB,CAAC,gBAAgB,CAAC,WAAW,EAAE,CAAC,CAAC;IACzE,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO;YACL,eAAe,EAAE,EAAE;YACnB,aAAa,EAAE,EAAE;YACjB,UAAU,EAAE,EAAE;YACd,eAAe,EAAE,gBAAgB;SAClC,CAAC;IACJ,CAAC;IAED,MAAM,mBAAmB,GAAG,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,MAAM,CAE5D,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,SAAS,CAAC,EAAE,EAAE;QAC9B,IAAI,SAAS,CAAC,cAAc,KAAK,UAAU,EAAE,CAAC;YAC5C,GAAG,CAAC,OAAwB,CAAC,GAAG,SAAS,CAAC;QAC5C,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP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,EAAE;wBACrC,iBAAiB,EAAE,GAAG,SAAS,CAAC,iBAAiB,EAAE;wBACnD,SAAS,EAAE,GAAG,SAAS,CAAC,SAAS,EAAE;wBACnC,WAAW,EAAE,GAAG,SAAS,CAAC,WAAW,EAAE;wBACvC,kBAAkB,EAAE;4BAClB,IAAI,EAAE,SAAS,CAAC,oBAA8B;4BAC9C,GAAG,EAAE,SAAS,CAAC,oBAA8B;4BAC7C,GAAG,EAAE,SAAS,CAAC,oBAA8B;4BAC7C,IAAI,EAAE,SAAS,CAAC,qBAA+B;4BAC/C,IAAI,EAAE,SAAS,CAAC,qBAA+B;4BAC/C,KAAK,EAAE,SAAS,CAAC,sBAAgC;4BACjD,GAAG,EAAE,SAAS,CAAC,oBAA8B;yBAC9C;qBACF;iBACwE,CAAC;YAC9E,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,2BAA2B;QAC7B,CAAC;IACH,CAAC;IAED,OAAO;QACL,eAAe;QACf,aAAa;QACb,UAAU;QACV,eAAe,EAAE,gBAAgB;KAClC,CAAC;AACJ,CAAC;AA7ID,oEA6IC","sourcesContent":["import { toChecksumAddress } from '@ethereumjs/util';\nimport {\n CurrencyRateState,\n MAP_CAIP_CURRENCIES,\n MarketDataDetails,\n MultichainAssetsRatesControllerState,\n TokenRatesControllerState,\n getNativeTokenAddress,\n} from '@metamask/assets-controllers';\nimport { Hex, KnownCaipNamespace, numberToHex } from '@metamask/utils';\nimport { parseCaipAssetType, parseCaipChainId } from '@metamask/utils';\n\nimport type {\n AssetMetadata,\n AssetPrice,\n FungibleAssetPrice,\n Caip19AssetId,\n} from '../types';\n\n/**\n * Exchange rates in the format expected by the bridge controller:\n * conversionRates (MultichainAssetsRatesController) + currencyRates (CurrencyRateController)\n * + marketData (TokenRatesController) + currentCurrency.\n */\nexport type BridgeExchangeRatesFormat = {\n conversionRates: MultichainAssetsRatesControllerState['conversionRates'];\n currencyRates: CurrencyRateState['currencyRates'];\n marketData: TokenRatesControllerState['marketData'];\n currentCurrency: string;\n};\n\n/**\n * Converts AssetsController state (assetsPrice, selectedCurrency) into the\n * same format the bridge expects from MultichainAssetsRatesController,\n * CurrencyRateController, and TokenRatesController so the bridge can use\n * a single action when useAssetsControllerForRates is true.\n *\n * @param params - Conversion parameters.\n * @param params.assetsInfo - Metadata map keyed by CAIP-19 asset ID; used to determine native assets via `type === 'native'`.\n * @param params.assetsPrice - Map of CAIP-19 asset ID to price data (must include both `price` and `usdPrice`).\n * @param params.selectedCurrency - ISO 4217 currency code (e.g. 'usd').\n * @param params.nativeAssetIdentifiers - Map of CAIP-2 chain ID to native asset ID. Used for EVM native lookups.\n * @param params.networkConfigurationsByChainId - Optional map of Hex chain ID to network config (e.g. from NetworkController state). Used to resolve native currency symbol via `nativeCurrency`; keys are Hex (e.g. '0x1').\n * @returns Bridge-compatible conversionRates, currencyRates, marketData, currentCurrency.\n */\nexport function formatExchangeRatesForBridge(params: {\n assetsInfo: Record<string, AssetMetadata>;\n assetsPrice: Record<string, AssetPrice>;\n selectedCurrency: string;\n nativeAssetIdentifiers: Record<string, string>;\n networkConfigurationsByChainId?: Record<string, { nativeCurrency?: string }>;\n}): BridgeExchangeRatesFormat {\n const {\n assetsInfo,\n assetsPrice,\n selectedCurrency,\n nativeAssetIdentifiers,\n networkConfigurationsByChainId = {},\n } = params;\n const conversionRates: MultichainAssetsRatesControllerState['conversionRates'] =\n {};\n const currencyRates: CurrencyRateState['currencyRates'] = {};\n const marketData: TokenRatesControllerState['marketData'] = {};\n\n const currencyCaip = MAP_CAIP_CURRENCIES[selectedCurrency.toLowerCase()];\n if (!currencyCaip) {\n return {\n conversionRates: {},\n currencyRates: {},\n marketData: {},\n currentCurrency: selectedCurrency,\n };\n }\n\n const fungibleAssetsPrice = Object.entries(assetsPrice).reduce<\n Record<Caip19AssetId, FungibleAssetPrice>\n >((acc, [assetId, priceData]) => {\n if (priceData.assetPriceType === 'fungible') {\n acc[assetId as Caip19AssetId] = priceData;\n }\n return acc;\n }, {});\n\n for (const [assetId, priceData] of Object.entries(fungibleAssetsPrice)) {\n const { price, usdPrice, lastUpdated } = priceData;\n if (price < 0) {\n continue;\n }\n\n const lastUpdatedInSeconds = lastUpdated / 1000;\n const expirationOffsetInSeconds = 60;\n const expirationTime = lastUpdatedInSeconds + expirationOffsetInSeconds;\n\n try {\n const isNative = assetsInfo[assetId]?.type === 'native';\n const parsed = parseCaipAssetType(assetId as Caip19AssetId);\n const chainIdParsed = parseCaipChainId(parsed.chainId);\n\n if (chainIdParsed.namespace === KnownCaipNamespace.Eip155) {\n const chainIdHex = numberToHex(parseInt(chainIdParsed.reference, 10));\n\n const nativeAssetId = (\n isNative ? assetId : nativeAssetIdentifiers[parsed.chainId]\n ) as Caip19AssetId | undefined;\n\n const nativeCurrencySymbol =\n networkConfigurationsByChainId[chainIdHex]?.nativeCurrency;\n\n const nativeAssetUsdPrice =\n nativeAssetId && fungibleAssetsPrice[nativeAssetId]?.usdPrice;\n\n if (\n !nativeAssetId ||\n !nativeCurrencySymbol ||\n nativeAssetUsdPrice === undefined\n ) {\n // If we do not have a native asset for that chain or a price for it, the asset needs to be skipped\n continue;\n }\n\n let tokenAddress: Hex | undefined;\n if (parsed.assetNamespace === 'erc20') {\n tokenAddress = toChecksumAddress(parsed.assetReference);\n } else if (isNative) {\n tokenAddress = toChecksumAddress(getNativeTokenAddress(chainIdHex));\n }\n\n if (tokenAddress) {\n const priceInNative =\n nativeAssetUsdPrice > 0 ? usdPrice / nativeAssetUsdPrice : usdPrice;\n if (!marketData[chainIdHex]) {\n marketData[chainIdHex] = {};\n }\n marketData[chainIdHex][tokenAddress] = {\n ...priceData,\n price: priceInNative,\n currency: nativeCurrencySymbol,\n assetId,\n chainId: chainIdHex,\n tokenAddress,\n } as MarketDataDetails;\n }\n\n if (isNative) {\n currencyRates[nativeCurrencySymbol] = {\n conversionDate: lastUpdatedInSeconds,\n conversionRate: price,\n usdConversionRate: usdPrice,\n };\n }\n } else {\n conversionRates[assetId as Caip19AssetId] = {\n rate: String(price),\n currency: currencyCaip,\n conversionTime: lastUpdatedInSeconds,\n expirationTime,\n marketData: {\n fungible: true,\n allTimeHigh: `${priceData.allTimeHigh}`,\n allTimeLow: `${priceData.allTimeLow}`,\n circulatingSupply: `${priceData.circulatingSupply}`,\n marketCap: `${priceData.marketCap}`,\n totalVolume: `${priceData.totalVolume}`,\n pricePercentChange: {\n PT1H: priceData.pricePercentChange1h as number,\n P1D: priceData.pricePercentChange1d as number,\n P7D: priceData.pricePercentChange7d as number,\n P14D: priceData.pricePercentChange14d as number,\n P30D: priceData.pricePercentChange30d as number,\n P200D: priceData.pricePercentChange200d as number,\n P1Y: priceData.pricePercentChange1y as number,\n },\n },\n } as MultichainAssetsRatesControllerState['conversionRates'][Caip19AssetId];\n }\n } catch {\n // Skip malformed asset IDs\n }\n }\n\n return {\n conversionRates,\n currencyRates,\n marketData,\n currentCurrency: selectedCurrency,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"formatExchangeRatesForBridge.cjs","sourceRoot":"","sources":["../../src/utils/formatExchangeRatesForBridge.ts"],"names":[],"mappings":";;;AAAA,2CAAqD;AACrD,qEAOsC;AACtC,2CAAuE;AACvE,2CAAuE;AACvE,mCAAiC;AA8BjC,IAAI,QAAQ,GAGD,IAAI,CAAC;AAEhB;;;;;;;;;;;;;GAaG;AACH,SAAgB,4BAA4B,CAC1C,MAA0C;IAE1C,IACE,QAAQ,EAAE,MAAM,CAAC,UAAU,KAAK,MAAM,CAAC,UAAU;QACjD,QAAQ,CAAC,MAAM,CAAC,WAAW,KAAK,MAAM,CAAC,WAAW;QAClD,QAAQ,CAAC,MAAM,CAAC,gBAAgB,KAAK,MAAM,CAAC,gBAAgB;QAC5D,QAAQ,CAAC,MAAM,CAAC,8BAA8B;YAC5C,MAAM,CAAC,8BAA8B;QACvC,IAAA,gBAAO,EACL,QAAQ,CAAC,MAAM,CAAC,sBAAsB,EACtC,MAAM,CAAC,sBAAsB,CAC9B,EACD,CAAC;QACD,OAA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,SAAS,EAAE;wBACnC,WAAW,EAAE,GAAG,SAAS,CAAC,WAAW,EAAE;wBACvC,kBAAkB,EAAE;4BAClB,IAAI,EAAE,SAAS,CAAC,oBAA8B;4BAC9C,GAAG,EAAE,SAAS,CAAC,oBAA8B;4BAC7C,GAAG,EAAE,SAAS,CAAC,oBAA8B;4BAC7C,IAAI,EAAE,SAAS,CAAC,qBAA+B;4BAC/C,IAAI,EAAE,SAAS,CAAC,qBAA+B;4BAC/C,KAAK,EAAE,SAAS,CAAC,sBAAgC;4BACjD,GAAG,EAAE,SAAS,CAAC,oBAA8B;yBAC9C;qBACF;iBACwE,CAAC;YAC9E,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,2BAA2B;QAC7B,CAAC;IACH,CAAC;IAED,OAAO;QACL,eAAe;QACf,aAAa;QACb,UAAU;QACV,eAAe,EAAE,gBAAgB;KAClC,CAAC;AACJ,CAAC","sourcesContent":["import { toChecksumAddress } from '@ethereumjs/util';\nimport {\n CurrencyRateState,\n MAP_CAIP_CURRENCIES,\n MarketDataDetails,\n MultichainAssetsRatesControllerState,\n TokenRatesControllerState,\n getNativeTokenAddress,\n} from '@metamask/assets-controllers';\nimport { Hex, KnownCaipNamespace, numberToHex } from '@metamask/utils';\nimport { parseCaipAssetType, parseCaipChainId } from '@metamask/utils';\nimport { isEqual } from 'lodash';\n\nimport type {\n AssetMetadata,\n AssetPrice,\n FungibleAssetPrice,\n Caip19AssetId,\n} from '../types';\n\n/**\n * Exchange rates in the format expected by the bridge controller:\n * conversionRates (MultichainAssetsRatesController) + currencyRates (CurrencyRateController)\n * + marketData (TokenRatesController) + currentCurrency.\n */\nexport type BridgeExchangeRatesFormat = {\n conversionRates: MultichainAssetsRatesControllerState['conversionRates'];\n currencyRates: CurrencyRateState['currencyRates'];\n marketData: TokenRatesControllerState['marketData'];\n currentCurrency: string;\n};\n\n/** Parameters accepted by {@link formatExchangeRatesForBridge}. */\nexport type FormatExchangeRatesForBridgeParams = {\n assetsInfo: Record<string, AssetMetadata>;\n assetsPrice: Record<string, AssetPrice>;\n selectedCurrency: string;\n nativeAssetIdentifiers: Record<string, string>;\n networkConfigurationsByChainId?: Record<string, { nativeCurrency?: string }>;\n};\n\nlet lastCall: {\n params: FormatExchangeRatesForBridgeParams;\n result: BridgeExchangeRatesFormat;\n} | null = null;\n\n/**\n * Converts AssetsController state (assetsPrice, selectedCurrency) into the\n * same format the bridge expects from MultichainAssetsRatesController,\n * CurrencyRateController, and TokenRatesController so the bridge can use\n * a single action when useAssetsControllerForRates is true.\n *\n * Memoized on input identity for BaseController state slices (`===`) and\n * lodash `isEqual` for rebuilt maps (`nativeAssetIdentifiers`). Bridge quote\n * / rate paths call this repeatedly while assets state is unchanged; recomputing\n * runs keccak256 (`toChecksumAddress`) and CAIP parsing per priced asset.\n *\n * @param params - Conversion parameters.\n * @returns Bridge-compatible conversionRates, currencyRates, marketData, currentCurrency.\n */\nexport function formatExchangeRatesForBridge(\n params: FormatExchangeRatesForBridgeParams,\n): BridgeExchangeRatesFormat {\n if (\n lastCall?.params.assetsInfo === params.assetsInfo &&\n lastCall.params.assetsPrice === params.assetsPrice &&\n lastCall.params.selectedCurrency === params.selectedCurrency &&\n lastCall.params.networkConfigurationsByChainId ===\n params.networkConfigurationsByChainId &&\n isEqual(\n lastCall.params.nativeAssetIdentifiers,\n params.nativeAssetIdentifiers,\n )\n ) {\n return lastCall.result;\n }\n\n const result = computeExchangeRatesForBridge(params);\n lastCall = { params, result };\n return result;\n}\n\n/**\n * Clears the {@link formatExchangeRatesForBridge} memoize cache. Exported for tests.\n */\nexport function clearFormatExchangeRatesForBridgeCacheForTesting(): void {\n lastCall = null;\n}\n\n/**\n * Performs the actual exchange-rate conversion for\n * {@link formatExchangeRatesForBridge}.\n *\n * @param params - Conversion parameters.\n * @returns Bridge-compatible rates.\n */\nfunction computeExchangeRatesForBridge(\n params: FormatExchangeRatesForBridgeParams,\n): BridgeExchangeRatesFormat {\n const {\n assetsInfo,\n assetsPrice,\n selectedCurrency,\n nativeAssetIdentifiers,\n networkConfigurationsByChainId = {},\n } = params;\n const conversionRates: MultichainAssetsRatesControllerState['conversionRates'] =\n {};\n const currencyRates: CurrencyRateState['currencyRates'] = {};\n const marketData: TokenRatesControllerState['marketData'] = {};\n\n const currencyCaip = MAP_CAIP_CURRENCIES[selectedCurrency.toLowerCase()];\n if (!currencyCaip) {\n return {\n conversionRates: {},\n currencyRates: {},\n marketData: {},\n currentCurrency: selectedCurrency,\n };\n }\n\n const fungibleAssetsPrice = Object.entries(assetsPrice).reduce<\n Record<Caip19AssetId, FungibleAssetPrice>\n >((acc, [assetId, priceData]) => {\n if (priceData.assetPriceType === 'fungible') {\n acc[assetId as Caip19AssetId] = priceData;\n }\n return acc;\n }, {});\n\n for (const [assetId, priceData] of Object.entries(fungibleAssetsPrice)) {\n const { price, usdPrice, lastUpdated } = priceData;\n if (price < 0) {\n continue;\n }\n\n const lastUpdatedInSeconds = lastUpdated / 1000;\n const expirationOffsetInSeconds = 60;\n const expirationTime = lastUpdatedInSeconds + expirationOffsetInSeconds;\n\n try {\n const isNative = assetsInfo[assetId]?.type === 'native';\n const parsed = parseCaipAssetType(assetId as Caip19AssetId);\n const chainIdParsed = parseCaipChainId(parsed.chainId);\n\n if (chainIdParsed.namespace === KnownCaipNamespace.Eip155) {\n const chainIdHex = numberToHex(parseInt(chainIdParsed.reference, 10));\n\n const nativeAssetId = (\n isNative ? assetId : nativeAssetIdentifiers[parsed.chainId]\n ) as Caip19AssetId | undefined;\n\n const nativeCurrencySymbol =\n networkConfigurationsByChainId[chainIdHex]?.nativeCurrency;\n\n const nativeAssetUsdPrice =\n nativeAssetId && fungibleAssetsPrice[nativeAssetId]?.usdPrice;\n\n if (\n !nativeAssetId ||\n !nativeCurrencySymbol ||\n nativeAssetUsdPrice === undefined\n ) {\n // If we do not have a native asset for that chain or a price for it, the asset needs to be skipped\n continue;\n }\n\n let tokenAddress: Hex | undefined;\n if (parsed.assetNamespace === 'erc20') {\n tokenAddress = toChecksumAddress(parsed.assetReference);\n } else if (isNative) {\n tokenAddress = toChecksumAddress(getNativeTokenAddress(chainIdHex));\n }\n\n if (tokenAddress) {\n const priceInNative =\n nativeAssetUsdPrice > 0 ? usdPrice / nativeAssetUsdPrice : usdPrice;\n if (!marketData[chainIdHex]) {\n marketData[chainIdHex] = {};\n }\n marketData[chainIdHex][tokenAddress] = {\n ...priceData,\n price: priceInNative,\n currency: nativeCurrencySymbol,\n assetId,\n chainId: chainIdHex,\n tokenAddress,\n } as MarketDataDetails;\n }\n\n if (isNative) {\n currencyRates[nativeCurrencySymbol] = {\n conversionDate: lastUpdatedInSeconds,\n conversionRate: price,\n usdConversionRate: usdPrice,\n };\n }\n } else {\n conversionRates[assetId as Caip19AssetId] = {\n rate: String(price),\n currency: currencyCaip,\n conversionTime: lastUpdatedInSeconds,\n expirationTime,\n marketData: {\n fungible: true,\n allTimeHigh: `${priceData.allTimeHigh}`,\n allTimeLow: `${priceData.allTimeLow}`,\n circulatingSupply: `${priceData.circulatingSupply}`,\n marketCap: `${priceData.marketCap}`,\n totalVolume: `${priceData.totalVolume}`,\n pricePercentChange: {\n PT1H: priceData.pricePercentChange1h as number,\n P1D: priceData.pricePercentChange1d as number,\n P7D: priceData.pricePercentChange7d as number,\n P14D: priceData.pricePercentChange14d as number,\n P30D: priceData.pricePercentChange30d as number,\n P200D: priceData.pricePercentChange200d as number,\n P1Y: priceData.pricePercentChange1y as number,\n },\n },\n } as MultichainAssetsRatesControllerState['conversionRates'][Caip19AssetId];\n }\n } catch {\n // Skip malformed asset IDs\n }\n }\n\n return {\n conversionRates,\n currencyRates,\n marketData,\n currentCurrency: selectedCurrency,\n };\n}\n"]}
|
|
@@ -11,27 +11,33 @@ export type BridgeExchangeRatesFormat = {
|
|
|
11
11
|
marketData: TokenRatesControllerState['marketData'];
|
|
12
12
|
currentCurrency: string;
|
|
13
13
|
};
|
|
14
|
+
/** Parameters accepted by {@link formatExchangeRatesForBridge}. */
|
|
15
|
+
export type FormatExchangeRatesForBridgeParams = {
|
|
16
|
+
assetsInfo: Record<string, AssetMetadata>;
|
|
17
|
+
assetsPrice: Record<string, AssetPrice>;
|
|
18
|
+
selectedCurrency: string;
|
|
19
|
+
nativeAssetIdentifiers: Record<string, string>;
|
|
20
|
+
networkConfigurationsByChainId?: Record<string, {
|
|
21
|
+
nativeCurrency?: string;
|
|
22
|
+
}>;
|
|
23
|
+
};
|
|
14
24
|
/**
|
|
15
25
|
* Converts AssetsController state (assetsPrice, selectedCurrency) into the
|
|
16
26
|
* same format the bridge expects from MultichainAssetsRatesController,
|
|
17
27
|
* CurrencyRateController, and TokenRatesController so the bridge can use
|
|
18
28
|
* a single action when useAssetsControllerForRates is true.
|
|
19
29
|
*
|
|
30
|
+
* Memoized on input identity for BaseController state slices (`===`) and
|
|
31
|
+
* lodash `isEqual` for rebuilt maps (`nativeAssetIdentifiers`). Bridge quote
|
|
32
|
+
* / rate paths call this repeatedly while assets state is unchanged; recomputing
|
|
33
|
+
* runs keccak256 (`toChecksumAddress`) and CAIP parsing per priced asset.
|
|
34
|
+
*
|
|
20
35
|
* @param params - Conversion parameters.
|
|
21
|
-
* @param params.assetsInfo - Metadata map keyed by CAIP-19 asset ID; used to determine native assets via `type === 'native'`.
|
|
22
|
-
* @param params.assetsPrice - Map of CAIP-19 asset ID to price data (must include both `price` and `usdPrice`).
|
|
23
|
-
* @param params.selectedCurrency - ISO 4217 currency code (e.g. 'usd').
|
|
24
|
-
* @param params.nativeAssetIdentifiers - Map of CAIP-2 chain ID to native asset ID. Used for EVM native lookups.
|
|
25
|
-
* @param params.networkConfigurationsByChainId - Optional map of Hex chain ID to network config (e.g. from NetworkController state). Used to resolve native currency symbol via `nativeCurrency`; keys are Hex (e.g. '0x1').
|
|
26
36
|
* @returns Bridge-compatible conversionRates, currencyRates, marketData, currentCurrency.
|
|
27
37
|
*/
|
|
28
|
-
export declare function formatExchangeRatesForBridge(params:
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
networkConfigurationsByChainId?: Record<string, {
|
|
34
|
-
nativeCurrency?: string;
|
|
35
|
-
}>;
|
|
36
|
-
}): BridgeExchangeRatesFormat;
|
|
38
|
+
export declare function formatExchangeRatesForBridge(params: FormatExchangeRatesForBridgeParams): BridgeExchangeRatesFormat;
|
|
39
|
+
/**
|
|
40
|
+
* Clears the {@link formatExchangeRatesForBridge} memoize cache. Exported for tests.
|
|
41
|
+
*/
|
|
42
|
+
export declare function clearFormatExchangeRatesForBridgeCacheForTesting(): void;
|
|
37
43
|
//# sourceMappingURL=formatExchangeRatesForBridge.d.cts.map
|