@metamask-previews/assets-controller 20.2.3-preview-4dd847ca3 → 20.2.3-preview-2ad7fb9
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 +19 -0
- package/README.md +6 -0
- package/dist/AssetsController.d.ts +11 -2
- package/dist/AssetsController.d.ts.map +1 -1
- package/dist/AssetsController.js +55 -7
- package/dist/AssetsController.js.map +1 -1
- package/dist/accounts-api-balances-service/accounts-api-balances-service-method-action-types.d.ts +22 -0
- package/dist/accounts-api-balances-service/accounts-api-balances-service-method-action-types.d.ts.map +1 -0
- package/dist/accounts-api-balances-service/accounts-api-balances-service-method-action-types.js +6 -0
- package/dist/accounts-api-balances-service/accounts-api-balances-service-method-action-types.js.map +1 -0
- package/dist/accounts-api-balances-service/accounts-api-balances-service.d.ts +140 -0
- package/dist/accounts-api-balances-service/accounts-api-balances-service.d.ts.map +1 -0
- package/dist/accounts-api-balances-service/accounts-api-balances-service.js +280 -0
- package/dist/accounts-api-balances-service/accounts-api-balances-service.js.map +1 -0
- package/dist/accounts-api-balances-service/structs.d.ts +208 -0
- package/dist/accounts-api-balances-service/structs.d.ts.map +1 -0
- package/dist/accounts-api-balances-service/structs.js +92 -0
- package/dist/accounts-api-balances-service/structs.js.map +1 -0
- package/dist/assetsFetchTracker.d.ts +31 -0
- package/dist/assetsFetchTracker.d.ts.map +1 -0
- package/dist/assetsFetchTracker.js +85 -0
- package/dist/assetsFetchTracker.js.map +1 -0
- package/dist/data-sources/AccountsApiDataSource.d.ts +20 -3
- package/dist/data-sources/AccountsApiDataSource.d.ts.map +1 -1
- package/dist/data-sources/AccountsApiDataSource.js +66 -4
- package/dist/data-sources/AccountsApiDataSource.js.map +1 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/selectors/fetchStatus.d.ts +36 -0
- package/dist/selectors/fetchStatus.d.ts.map +1 -0
- package/dist/selectors/fetchStatus.js +44 -0
- package/dist/selectors/fetchStatus.js.map +1 -0
- package/dist/types.d.ts +17 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +3 -1
package/dist/accounts-api-balances-service/accounts-api-balances-service-method-action-types.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file is auto generated.
|
|
3
|
+
* Do not edit manually.
|
|
4
|
+
*/
|
|
5
|
+
import type { AccountsApiBalancesService } from './accounts-api-balances-service.js';
|
|
6
|
+
/**
|
|
7
|
+
* Fetches balances for the given accounts from the Accounts API v5 or v6
|
|
8
|
+
* multi account balances endpoint. Serves from cache when fresh, and shares
|
|
9
|
+
* one request between concurrent identical calls.
|
|
10
|
+
*
|
|
11
|
+
* @param options - The fetch options. See {@link FetchBalancesOptions}.
|
|
12
|
+
* @returns The validated balances response.
|
|
13
|
+
*/
|
|
14
|
+
export type AccountsApiBalancesServiceFetchBalancesAction = {
|
|
15
|
+
type: `AccountsApiBalancesService:fetchBalances`;
|
|
16
|
+
handler: AccountsApiBalancesService['fetchBalances'];
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Union of all AccountsApiBalancesService action types.
|
|
20
|
+
*/
|
|
21
|
+
export type AccountsApiBalancesServiceMethodActions = AccountsApiBalancesServiceFetchBalancesAction;
|
|
22
|
+
//# sourceMappingURL=accounts-api-balances-service-method-action-types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"accounts-api-balances-service-method-action-types.d.ts","sourceRoot":"","sources":["../../src/accounts-api-balances-service/accounts-api-balances-service-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AAErF;;;;;;;GAOG;AACH,MAAM,MAAM,6CAA6C,GAAG;IAC1D,IAAI,EAAE,0CAA0C,CAAC;IACjD,OAAO,EAAE,0BAA0B,CAAC,eAAe,CAAC,CAAC;CACtD,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,uCAAuC,GACjD,6CAA6C,CAAC"}
|
package/dist/accounts-api-balances-service/accounts-api-balances-service-method-action-types.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"accounts-api-balances-service-method-action-types.js","sourceRoot":"","sources":["../../src/accounts-api-balances-service/accounts-api-balances-service-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { AccountsApiBalancesService } from './accounts-api-balances-service.js';\n\n/**\n * Fetches balances for the given accounts from the Accounts API v5 or v6\n * multi account balances endpoint. Serves from cache when fresh, and shares\n * one request between concurrent identical calls.\n *\n * @param options - The fetch options. See {@link FetchBalancesOptions}.\n * @returns The validated balances response.\n */\nexport type AccountsApiBalancesServiceFetchBalancesAction = {\n type: `AccountsApiBalancesService:fetchBalances`;\n handler: AccountsApiBalancesService['fetchBalances'];\n};\n\n/**\n * Union of all AccountsApiBalancesService action types.\n */\nexport type AccountsApiBalancesServiceMethodActions =\n AccountsApiBalancesServiceFetchBalancesAction;\n"]}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { BaseDataService } from '@metamask/base-data-service';
|
|
2
|
+
import type { CreateServicePolicyOptions, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, DataServiceInvalidateQueriesAction, QueryStateChangeHandler } from '@metamask/base-data-service';
|
|
3
|
+
import type { Messenger } from '@metamask/messenger';
|
|
4
|
+
import type { AccountsApiBalancesServiceMethodActions } from './accounts-api-balances-service-method-action-types.js';
|
|
5
|
+
import type { BalancesResponse } from './structs.js';
|
|
6
|
+
/**
|
|
7
|
+
* The name of the {@link AccountsApiBalancesService}, used to namespace the
|
|
8
|
+
* service's actions and events.
|
|
9
|
+
*/
|
|
10
|
+
export declare const serviceName = "AccountsApiBalancesService";
|
|
11
|
+
/**
|
|
12
|
+
* Invalidates cached queries for {@link AccountsApiBalancesService}.
|
|
13
|
+
*/
|
|
14
|
+
export type AccountsApiBalancesServiceInvalidateQueriesAction = DataServiceInvalidateQueriesAction<typeof serviceName>;
|
|
15
|
+
/**
|
|
16
|
+
* Actions that {@link AccountsApiBalancesService} exposes to other consumers.
|
|
17
|
+
*/
|
|
18
|
+
export type AccountsApiBalancesServiceActions = AccountsApiBalancesServiceMethodActions | AccountsApiBalancesServiceInvalidateQueriesAction;
|
|
19
|
+
/**
|
|
20
|
+
* Retrieves a bearer token from the `AuthenticationController`.
|
|
21
|
+
*/
|
|
22
|
+
type AuthenticationControllerGetBearerTokenAction = {
|
|
23
|
+
type: 'AuthenticationController:getBearerToken';
|
|
24
|
+
handler: (entropySourceId?: string) => Promise<string>;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Actions from other messengers that {@link AccountsApiBalancesService}
|
|
28
|
+
* calls.
|
|
29
|
+
*/
|
|
30
|
+
type AllowedActions = AuthenticationControllerGetBearerTokenAction;
|
|
31
|
+
/**
|
|
32
|
+
* Published when {@link AccountsApiBalancesService}'s cache is updated.
|
|
33
|
+
*/
|
|
34
|
+
export type AccountsApiBalancesServiceCacheUpdatedEvent = DataServiceCacheUpdatedEvent<typeof serviceName>;
|
|
35
|
+
/**
|
|
36
|
+
* Published when a key within {@link AccountsApiBalancesService}'s cache is
|
|
37
|
+
* updated.
|
|
38
|
+
*/
|
|
39
|
+
export type AccountsApiBalancesServiceGranularCacheUpdatedEvent = DataServiceGranularCacheUpdatedEvent<typeof serviceName>;
|
|
40
|
+
/**
|
|
41
|
+
* Events that {@link AccountsApiBalancesService} exposes to other consumers.
|
|
42
|
+
*/
|
|
43
|
+
export type AccountsApiBalancesServiceEvents = AccountsApiBalancesServiceCacheUpdatedEvent | AccountsApiBalancesServiceGranularCacheUpdatedEvent;
|
|
44
|
+
/**
|
|
45
|
+
* Events from other messengers that {@link AccountsApiBalancesService}
|
|
46
|
+
* subscribes to.
|
|
47
|
+
*/
|
|
48
|
+
type AllowedEvents = never;
|
|
49
|
+
/**
|
|
50
|
+
* The messenger restricted to actions and events accessed by
|
|
51
|
+
* {@link AccountsApiBalancesService}.
|
|
52
|
+
*/
|
|
53
|
+
export type AccountsApiBalancesServiceMessenger = Messenger<typeof serviceName, AccountsApiBalancesServiceActions | AllowedActions, AccountsApiBalancesServiceEvents | AllowedEvents>;
|
|
54
|
+
/**
|
|
55
|
+
* Options accepted by {@link AccountsApiBalancesService.fetchBalances}.
|
|
56
|
+
*/
|
|
57
|
+
export type FetchBalancesOptions = {
|
|
58
|
+
/** Which multi account balances endpoint to call. */
|
|
59
|
+
version: 'v5' | 'v6';
|
|
60
|
+
/** CAIP-10 account IDs to fetch balances for. */
|
|
61
|
+
accountIds: string[];
|
|
62
|
+
/** CAIP-19 asset IDs the backend must always return (v6 only). */
|
|
63
|
+
includeAssetIds?: string[];
|
|
64
|
+
/** CAIP-19 asset IDs the backend must drop (v6 only). */
|
|
65
|
+
excludeAssetIds?: string[];
|
|
66
|
+
/** CAIP-2 chain IDs to restrict the response to. */
|
|
67
|
+
networks?: string[];
|
|
68
|
+
/** When true, ignores any cached result and fetches fresh data. */
|
|
69
|
+
forceUpdate?: boolean;
|
|
70
|
+
/**
|
|
71
|
+
* When true, adds a random `bypassServerCache` query parameter so the API's
|
|
72
|
+
* own cache is skipped too. Such fetches use their own cache entry and are
|
|
73
|
+
* never served from the cache.
|
|
74
|
+
*/
|
|
75
|
+
bypassServerCache?: boolean;
|
|
76
|
+
/**
|
|
77
|
+
* Called with the state of the underlying query as it changes. See
|
|
78
|
+
* {@link QueryStateChangeHandler}.
|
|
79
|
+
*/
|
|
80
|
+
onQueryStateChange?: QueryStateChangeHandler;
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* Data service that fetches multi account balances from the Accounts API v5
|
|
84
|
+
* and v6 endpoints.
|
|
85
|
+
*
|
|
86
|
+
* It sends the same request as the core backend `ApiPlatformClient` (URL,
|
|
87
|
+
* query parameters and headers), wraps it in a service policy, and validates
|
|
88
|
+
* the response before returning it. It has no persistence.
|
|
89
|
+
*/
|
|
90
|
+
export declare class AccountsApiBalancesService extends BaseDataService<typeof serviceName, AccountsApiBalancesServiceMessenger> {
|
|
91
|
+
#private;
|
|
92
|
+
/**
|
|
93
|
+
* Constructs a new {@link AccountsApiBalancesService}.
|
|
94
|
+
*
|
|
95
|
+
* @param args - The constructor arguments.
|
|
96
|
+
* @param args.messenger - The messenger suited for this service.
|
|
97
|
+
* @param args.fetch - A function that can be used to make an HTTP request.
|
|
98
|
+
* @param args.clientProduct - Sent as the `x-metamask-clientproduct` header.
|
|
99
|
+
* @param args.clientVersion - Sent as the `x-metamask-clientversion` header
|
|
100
|
+
* when set.
|
|
101
|
+
* @param args.baseUrl - The Accounts API base URL. Defaults to production.
|
|
102
|
+
* @param args.authTokenTimeout - How long to wait for the bearer token, in
|
|
103
|
+
* milliseconds, before sending the request without it. 0 waits forever.
|
|
104
|
+
* Defaults to 500.
|
|
105
|
+
* @param args.staleTime - How long a response is served from cache, in
|
|
106
|
+
* milliseconds. Defaults to 1 minute.
|
|
107
|
+
* @param args.gcTime - How long an unused response stays in memory, in
|
|
108
|
+
* milliseconds. Defaults to 5 minutes.
|
|
109
|
+
* @param args.policyOptions - Overrides for the default policy options
|
|
110
|
+
* passed to `createServicePolicy`. See {@link CreateServicePolicyOptions}.
|
|
111
|
+
* Each override replaces the default for that key as a whole, so passing
|
|
112
|
+
* `retryFilterPolicy` or `isServiceFailure` drops the default
|
|
113
|
+
* `BrokenCircuitError` and 4xx handling. One policy, and so one circuit
|
|
114
|
+
* breaker, is shared by v5, v6 and every query key of a service instance:
|
|
115
|
+
* once it trips, both versions fail fast for the break duration (balances
|
|
116
|
+
* then fall back to RPC).
|
|
117
|
+
*/
|
|
118
|
+
constructor({ messenger, fetch: fetchFunction, clientProduct, clientVersion, baseUrl, authTokenTimeout, staleTime, gcTime, policyOptions, }: {
|
|
119
|
+
messenger: AccountsApiBalancesServiceMessenger;
|
|
120
|
+
fetch: typeof globalThis.fetch;
|
|
121
|
+
clientProduct: string;
|
|
122
|
+
clientVersion?: string;
|
|
123
|
+
baseUrl?: string;
|
|
124
|
+
authTokenTimeout?: number;
|
|
125
|
+
staleTime?: number;
|
|
126
|
+
gcTime?: number;
|
|
127
|
+
policyOptions?: CreateServicePolicyOptions;
|
|
128
|
+
});
|
|
129
|
+
/**
|
|
130
|
+
* Fetches balances for the given accounts from the Accounts API v5 or v6
|
|
131
|
+
* multi account balances endpoint. Serves from cache when fresh, and shares
|
|
132
|
+
* one request between concurrent identical calls.
|
|
133
|
+
*
|
|
134
|
+
* @param options - The fetch options. See {@link FetchBalancesOptions}.
|
|
135
|
+
* @returns The validated balances response.
|
|
136
|
+
*/
|
|
137
|
+
fetchBalances(options: FetchBalancesOptions): Promise<BalancesResponse>;
|
|
138
|
+
}
|
|
139
|
+
export {};
|
|
140
|
+
//# sourceMappingURL=accounts-api-balances-service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"accounts-api-balances-service.d.ts","sourceRoot":"","sources":["../../src/accounts-api-balances-service/accounts-api-balances-service.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EAIhB,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EACV,0BAA0B,EAC1B,4BAA4B,EAC5B,oCAAoC,EACpC,kCAAkC,EAClC,uBAAuB,EACxB,MAAM,6BAA6B,CAAC;AAErC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAGrD,OAAO,KAAK,EAAE,uCAAuC,EAAE,MAAM,wDAAwD,CAAC;AAKtH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAIrD;;;GAGG;AACH,eAAO,MAAM,WAAW,+BAA+B,CAAC;AA6GxD;;GAEG;AACH,MAAM,MAAM,iDAAiD,GAC3D,kCAAkC,CAAC,OAAO,WAA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CAAC;AAEF;;;;;;;GAOG;AACH,qBAAa,0BAA2B,SAAQ,eAAe,CAC7D,OAAO,WAAW,EAClB,mCAAmC,CACpC;;IAeC;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACH,YAAY,EACV,SAAS,EACT,KAAK,EAAE,aAAa,EACpB,aAAa,EACb,aAAa,EACb,OAA0B,EAC1B,gBAAgD,EAChD,SAAiC,EACjC,MAA2B,EAC3B,aAAkB,GACnB,EAAE;QACD,SAAS,EAAE,mCAAmC,CAAC;QAC/C,KAAK,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;QAC/B,aAAa,EAAE,MAAM,CAAC;QACtB,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC1B,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,aAAa,CAAC,EAAE,0BAA0B,CAAC;KAC5C,EAkBA;IAED;;;;;;;OAOG;IACG,aAAa,CACjB,OAAO,EAAE,oBAAoB,GAC5B,OAAO,CAAC,gBAAgB,CAAC,CA6E3B;CAwEF"}
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { BaseDataService, BrokenCircuitError, ExponentialBackoff, handleWhen, } from '@metamask/base-data-service';
|
|
2
|
+
import { HttpError } from '@metamask/controller-utils';
|
|
3
|
+
import { V5BalancesResponseStruct, V6BalancesResponseStruct, } from './structs.js';
|
|
4
|
+
// === GENERAL ===
|
|
5
|
+
/**
|
|
6
|
+
* The name of the {@link AccountsApiBalancesService}, used to namespace the
|
|
7
|
+
* service's actions and events.
|
|
8
|
+
*/
|
|
9
|
+
export const serviceName = 'AccountsApiBalancesService';
|
|
10
|
+
/** The production Accounts API base URL (same as `API_URLS.ACCOUNTS`). */
|
|
11
|
+
const DEFAULT_BASE_URL = 'https://accounts.api.cx.metamask.io';
|
|
12
|
+
/** How long a balances response is served from cache (`STALE_TIMES.BALANCES`). */
|
|
13
|
+
const DEFAULT_STALE_TIME_MS = 60 * 1000;
|
|
14
|
+
/** How long an unused balances response stays in memory (`GC_TIMES.DEFAULT`). */
|
|
15
|
+
const DEFAULT_GC_TIME_MS = 5 * 60 * 1000;
|
|
16
|
+
/** How long to wait for the bearer token (`DEFAULT_AUTH_TOKEN_TIMEOUT`). */
|
|
17
|
+
const DEFAULT_AUTH_TOKEN_TIMEOUT_MS = 500;
|
|
18
|
+
/** How long the circuit stays open once it breaks. */
|
|
19
|
+
const DEFAULT_CIRCUIT_BREAK_DURATION_MS = 60 * 1000;
|
|
20
|
+
/**
|
|
21
|
+
* Reads the HTTP status carried by an error, if any.
|
|
22
|
+
*
|
|
23
|
+
* `HttpError` carries `httpStatus`. The `status` fallback is load bearing: an
|
|
24
|
+
* injected `fetch` may reject with its own error type that only carries
|
|
25
|
+
* `status`, and without it such a 4xx would be retried and counted toward the
|
|
26
|
+
* circuit breaker.
|
|
27
|
+
*
|
|
28
|
+
* @param error - The thrown value.
|
|
29
|
+
* @returns The `httpStatus` (or `status`) of the error, if present.
|
|
30
|
+
*/
|
|
31
|
+
function getErrorStatus(error) {
|
|
32
|
+
const candidate = error;
|
|
33
|
+
return candidate?.httpStatus ?? candidate?.status;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Whether an error is a client error that a retry cannot fix (any 4xx other
|
|
37
|
+
* than 408 and 429).
|
|
38
|
+
*
|
|
39
|
+
* @param error - The thrown value.
|
|
40
|
+
* @returns True if the error should not be retried.
|
|
41
|
+
*/
|
|
42
|
+
function isNonRetryableClientError(error) {
|
|
43
|
+
const status = getErrorStatus(error);
|
|
44
|
+
return (typeof status === 'number' &&
|
|
45
|
+
status >= 400 &&
|
|
46
|
+
status < 500 &&
|
|
47
|
+
status !== 408 &&
|
|
48
|
+
status !== 429);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Builds the default policy options. Errors without a numeric status (network
|
|
52
|
+
* errors), 5xx, 408 and 429 count toward the circuit breaker and are retried;
|
|
53
|
+
* other 4xx and `BrokenCircuitError` are neither.
|
|
54
|
+
*
|
|
55
|
+
* @returns The default policy options.
|
|
56
|
+
*/
|
|
57
|
+
function getDefaultPolicyOptions() {
|
|
58
|
+
return {
|
|
59
|
+
maxRetries: 3,
|
|
60
|
+
retryFilterPolicy: handleWhen((error) => !(error instanceof BrokenCircuitError) &&
|
|
61
|
+
!isNonRetryableClientError(error)),
|
|
62
|
+
backoff: new ExponentialBackoff({ initialDelay: 1000, maxDelay: 5000 }),
|
|
63
|
+
isServiceFailure: (error) => {
|
|
64
|
+
const status = getErrorStatus(error);
|
|
65
|
+
return (typeof status !== 'number' ||
|
|
66
|
+
status >= 500 ||
|
|
67
|
+
status === 408 ||
|
|
68
|
+
status === 429);
|
|
69
|
+
},
|
|
70
|
+
circuitBreakDuration: DEFAULT_CIRCUIT_BREAK_DURATION_MS,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Generates a short random value for the `bypassServerCache` query parameter,
|
|
75
|
+
* exactly as the core backend Accounts API client does. The API's server side
|
|
76
|
+
* cache keys on the full URL, so a unique value forces a cache miss.
|
|
77
|
+
*
|
|
78
|
+
* @returns An 8 character alphanumeric string.
|
|
79
|
+
*/
|
|
80
|
+
function generateBypassServerCache() {
|
|
81
|
+
return Math.random().toString(36).slice(2, 10).padEnd(8, '0');
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Returns a sorted copy of a list, or `null` when it is absent, so it can be
|
|
85
|
+
* used in a query key.
|
|
86
|
+
*
|
|
87
|
+
* @param list - The list to sort.
|
|
88
|
+
* @returns The sorted copy, or `null`.
|
|
89
|
+
*/
|
|
90
|
+
function sortedOrNull(list) {
|
|
91
|
+
return list ? [...list].sort() : null;
|
|
92
|
+
}
|
|
93
|
+
// === MESSENGER ===
|
|
94
|
+
const MESSENGER_EXPOSED_METHODS = ['fetchBalances'];
|
|
95
|
+
/**
|
|
96
|
+
* Data service that fetches multi account balances from the Accounts API v5
|
|
97
|
+
* and v6 endpoints.
|
|
98
|
+
*
|
|
99
|
+
* It sends the same request as the core backend `ApiPlatformClient` (URL,
|
|
100
|
+
* query parameters and headers), wraps it in a service policy, and validates
|
|
101
|
+
* the response before returning it. It has no persistence.
|
|
102
|
+
*/
|
|
103
|
+
export class AccountsApiBalancesService extends BaseDataService {
|
|
104
|
+
#fetch;
|
|
105
|
+
#baseUrl;
|
|
106
|
+
#clientProduct;
|
|
107
|
+
#clientVersion;
|
|
108
|
+
#authTokenTimeout;
|
|
109
|
+
#staleTime;
|
|
110
|
+
#gcTime;
|
|
111
|
+
/**
|
|
112
|
+
* Constructs a new {@link AccountsApiBalancesService}.
|
|
113
|
+
*
|
|
114
|
+
* @param args - The constructor arguments.
|
|
115
|
+
* @param args.messenger - The messenger suited for this service.
|
|
116
|
+
* @param args.fetch - A function that can be used to make an HTTP request.
|
|
117
|
+
* @param args.clientProduct - Sent as the `x-metamask-clientproduct` header.
|
|
118
|
+
* @param args.clientVersion - Sent as the `x-metamask-clientversion` header
|
|
119
|
+
* when set.
|
|
120
|
+
* @param args.baseUrl - The Accounts API base URL. Defaults to production.
|
|
121
|
+
* @param args.authTokenTimeout - How long to wait for the bearer token, in
|
|
122
|
+
* milliseconds, before sending the request without it. 0 waits forever.
|
|
123
|
+
* Defaults to 500.
|
|
124
|
+
* @param args.staleTime - How long a response is served from cache, in
|
|
125
|
+
* milliseconds. Defaults to 1 minute.
|
|
126
|
+
* @param args.gcTime - How long an unused response stays in memory, in
|
|
127
|
+
* milliseconds. Defaults to 5 minutes.
|
|
128
|
+
* @param args.policyOptions - Overrides for the default policy options
|
|
129
|
+
* passed to `createServicePolicy`. See {@link CreateServicePolicyOptions}.
|
|
130
|
+
* Each override replaces the default for that key as a whole, so passing
|
|
131
|
+
* `retryFilterPolicy` or `isServiceFailure` drops the default
|
|
132
|
+
* `BrokenCircuitError` and 4xx handling. One policy, and so one circuit
|
|
133
|
+
* breaker, is shared by v5, v6 and every query key of a service instance:
|
|
134
|
+
* once it trips, both versions fail fast for the break duration (balances
|
|
135
|
+
* then fall back to RPC).
|
|
136
|
+
*/
|
|
137
|
+
constructor({ messenger, fetch: fetchFunction, clientProduct, clientVersion, baseUrl = DEFAULT_BASE_URL, authTokenTimeout = DEFAULT_AUTH_TOKEN_TIMEOUT_MS, staleTime = DEFAULT_STALE_TIME_MS, gcTime = DEFAULT_GC_TIME_MS, policyOptions = {}, }) {
|
|
138
|
+
super({
|
|
139
|
+
name: serviceName,
|
|
140
|
+
messenger,
|
|
141
|
+
policyOptions: { ...getDefaultPolicyOptions(), ...policyOptions },
|
|
142
|
+
});
|
|
143
|
+
this.#fetch = fetchFunction;
|
|
144
|
+
this.#baseUrl = baseUrl;
|
|
145
|
+
this.#clientProduct = clientProduct;
|
|
146
|
+
this.#clientVersion = clientVersion;
|
|
147
|
+
this.#authTokenTimeout = authTokenTimeout;
|
|
148
|
+
this.#staleTime = staleTime;
|
|
149
|
+
this.#gcTime = gcTime;
|
|
150
|
+
this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Fetches balances for the given accounts from the Accounts API v5 or v6
|
|
154
|
+
* multi account balances endpoint. Serves from cache when fresh, and shares
|
|
155
|
+
* one request between concurrent identical calls.
|
|
156
|
+
*
|
|
157
|
+
* @param options - The fetch options. See {@link FetchBalancesOptions}.
|
|
158
|
+
* @returns The validated balances response.
|
|
159
|
+
*/
|
|
160
|
+
async fetchBalances(options) {
|
|
161
|
+
const { version, accountIds, includeAssetIds, excludeAssetIds, networks, forceUpdate = false, bypassServerCache = false, onQueryStateChange, } = options;
|
|
162
|
+
if (accountIds.length === 0) {
|
|
163
|
+
return version === 'v6'
|
|
164
|
+
? {
|
|
165
|
+
unprocessedNetworks: [],
|
|
166
|
+
unprocessedIncludeAssetIds: [],
|
|
167
|
+
balances: [],
|
|
168
|
+
}
|
|
169
|
+
: { count: 0, unprocessedNetworks: [], balances: [] };
|
|
170
|
+
}
|
|
171
|
+
const queryKey = [
|
|
172
|
+
`${this.name}:fetchBalances`,
|
|
173
|
+
version,
|
|
174
|
+
[...accountIds].sort(),
|
|
175
|
+
{
|
|
176
|
+
// v5 never sends these lists, so they stay out of its key.
|
|
177
|
+
includeAssetIds: version === 'v6' ? sortedOrNull(includeAssetIds) : null,
|
|
178
|
+
excludeAssetIds: version === 'v6' ? sortedOrNull(excludeAssetIds) : null,
|
|
179
|
+
networks: sortedOrNull(networks),
|
|
180
|
+
bypassServerCache,
|
|
181
|
+
},
|
|
182
|
+
];
|
|
183
|
+
if (forceUpdate) {
|
|
184
|
+
await this.invalidateQueries({
|
|
185
|
+
queryKey,
|
|
186
|
+
exact: true,
|
|
187
|
+
refetchType: 'none',
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
const responseStruct = (version === 'v6'
|
|
191
|
+
? V6BalancesResponseStruct
|
|
192
|
+
: V5BalancesResponseStruct);
|
|
193
|
+
return await this.fetchQuery({
|
|
194
|
+
queryKey,
|
|
195
|
+
responseStruct,
|
|
196
|
+
staleTime: bypassServerCache ? 0 : this.#staleTime,
|
|
197
|
+
gcTime: this.#gcTime,
|
|
198
|
+
onQueryStateChange,
|
|
199
|
+
queryFn: async () => {
|
|
200
|
+
const url = this.#buildUrl(version, {
|
|
201
|
+
accountIds,
|
|
202
|
+
networks,
|
|
203
|
+
...(version === 'v6' ? { includeAssetIds, excludeAssetIds } : {}),
|
|
204
|
+
bypassServerCache: bypassServerCache
|
|
205
|
+
? generateBypassServerCache()
|
|
206
|
+
: undefined,
|
|
207
|
+
});
|
|
208
|
+
const response = await this.#fetch(url, {
|
|
209
|
+
method: 'GET',
|
|
210
|
+
headers: await this.#buildHeaders(),
|
|
211
|
+
});
|
|
212
|
+
if (!response.ok) {
|
|
213
|
+
throw new HttpError(response.status, `Accounts API ${version} balances request failed with status '${response.status}'`);
|
|
214
|
+
}
|
|
215
|
+
return (await response.json());
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Builds the request URL. Mirrors the core backend client: undefined
|
|
221
|
+
* parameters are skipped and arrays are joined with commas.
|
|
222
|
+
*
|
|
223
|
+
* @param version - The endpoint version.
|
|
224
|
+
* @param params - The query parameters, in the order the client sends them.
|
|
225
|
+
* @returns The request URL.
|
|
226
|
+
*/
|
|
227
|
+
#buildUrl(version, params) {
|
|
228
|
+
const url = new URL(`/${version}/multiaccount/balances`, this.#baseUrl);
|
|
229
|
+
for (const [key, value] of Object.entries(params)) {
|
|
230
|
+
if (value === undefined) {
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
url.searchParams.set(key, Array.isArray(value) ? value.join(',') : value);
|
|
234
|
+
}
|
|
235
|
+
return url.toString();
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Builds the request headers, as the core backend client does.
|
|
239
|
+
*
|
|
240
|
+
* @returns The request headers.
|
|
241
|
+
*/
|
|
242
|
+
async #buildHeaders() {
|
|
243
|
+
const headers = {
|
|
244
|
+
'Content-Type': 'application/json',
|
|
245
|
+
'x-metamask-clientproduct': this.#clientProduct,
|
|
246
|
+
};
|
|
247
|
+
if (this.#clientVersion) {
|
|
248
|
+
headers['x-metamask-clientversion'] = this.#clientVersion;
|
|
249
|
+
}
|
|
250
|
+
const token = await this.#getBearerToken();
|
|
251
|
+
if (token) {
|
|
252
|
+
headers.Authorization = `Bearer ${token}`;
|
|
253
|
+
}
|
|
254
|
+
return headers;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Resolves the bearer token, giving up after `authTokenTimeout` so a slow
|
|
258
|
+
* token provider does not delay the request. Without a token in time, the
|
|
259
|
+
* request goes out unauthenticated, as with the core backend client.
|
|
260
|
+
*
|
|
261
|
+
* @returns The bearer token, or undefined if unavailable in time.
|
|
262
|
+
*/
|
|
263
|
+
async #getBearerToken() {
|
|
264
|
+
const tokenPromise = (async () => this.messenger.call('AuthenticationController:getBearerToken'))().catch(() => undefined);
|
|
265
|
+
if (this.#authTokenTimeout <= 0) {
|
|
266
|
+
return await tokenPromise;
|
|
267
|
+
}
|
|
268
|
+
let timeoutId;
|
|
269
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
270
|
+
timeoutId = setTimeout(() => resolve(undefined), this.#authTokenTimeout);
|
|
271
|
+
});
|
|
272
|
+
try {
|
|
273
|
+
return await Promise.race([tokenPromise, timeoutPromise]);
|
|
274
|
+
}
|
|
275
|
+
finally {
|
|
276
|
+
clearTimeout(timeoutId);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
//# sourceMappingURL=accounts-api-balances-service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"accounts-api-balances-service.js","sourceRoot":"","sources":["../../src/accounts-api-balances-service/accounts-api-balances-service.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,kBAAkB,EAClB,kBAAkB,EAClB,UAAU,GACX,MAAM,6BAA6B,CAAC;AAQrC,OAAO,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAKvD,OAAO,EACL,wBAAwB,EACxB,wBAAwB,GACzB,MAAM,cAAc,CAAC;AAGtB,kBAAkB;AAElB;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,4BAA4B,CAAC;AAExD,0EAA0E;AAC1E,MAAM,gBAAgB,GAAG,qCAAqC,CAAC;AAE/D,kFAAkF;AAClF,MAAM,qBAAqB,GAAG,EAAE,GAAG,IAAI,CAAC;AAExC,iFAAiF;AACjF,MAAM,kBAAkB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAEzC,4EAA4E;AAC5E,MAAM,6BAA6B,GAAG,GAAG,CAAC;AAE1C,sDAAsD;AACtD,MAAM,iCAAiC,GAAG,EAAE,GAAG,IAAI,CAAC;AAEpD;;;;;;;;;;G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iBAAiB,CAAC,CAAC;QAC3E,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC;YACH,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,YAAY,EAAE,cAAc,CAAC,CAAC,CAAC;QAC5D,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,SAAS,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC;CACF","sourcesContent":["import {\n BaseDataService,\n BrokenCircuitError,\n ExponentialBackoff,\n handleWhen,\n} from '@metamask/base-data-service';\nimport type {\n CreateServicePolicyOptions,\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n DataServiceInvalidateQueriesAction,\n QueryStateChangeHandler,\n} from '@metamask/base-data-service';\nimport { HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { Struct } from '@metamask/superstruct';\n\nimport type { AccountsApiBalancesServiceMethodActions } from './accounts-api-balances-service-method-action-types.js';\nimport {\n V5BalancesResponseStruct,\n V6BalancesResponseStruct,\n} from './structs.js';\nimport type { BalancesResponse } from './structs.js';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link AccountsApiBalancesService}, used to namespace the\n * service's actions and events.\n */\nexport const serviceName = 'AccountsApiBalancesService';\n\n/** The production Accounts API base URL (same as `API_URLS.ACCOUNTS`). */\nconst DEFAULT_BASE_URL = 'https://accounts.api.cx.metamask.io';\n\n/** How long a balances response is served from cache (`STALE_TIMES.BALANCES`). */\nconst DEFAULT_STALE_TIME_MS = 60 * 1000;\n\n/** How long an unused balances response stays in memory (`GC_TIMES.DEFAULT`). */\nconst DEFAULT_GC_TIME_MS = 5 * 60 * 1000;\n\n/** How long to wait for the bearer token (`DEFAULT_AUTH_TOKEN_TIMEOUT`). */\nconst DEFAULT_AUTH_TOKEN_TIMEOUT_MS = 500;\n\n/** How long the circuit stays open once it breaks. */\nconst DEFAULT_CIRCUIT_BREAK_DURATION_MS = 60 * 1000;\n\n/**\n * Reads the HTTP status carried by an error, if any.\n *\n * `HttpError` carries `httpStatus`. The `status` fallback is load bearing: an\n * injected `fetch` may reject with its own error type that only carries\n * `status`, and without it such a 4xx would be retried and counted toward the\n * circuit breaker.\n *\n * @param error - The thrown value.\n * @returns The `httpStatus` (or `status`) of the error, if present.\n */\nfunction getErrorStatus(error: unknown): unknown {\n const candidate = error as\n | { httpStatus?: unknown; status?: unknown }\n | null\n | undefined;\n return candidate?.httpStatus ?? candidate?.status;\n}\n\n/**\n * Whether an error is a client error that a retry cannot fix (any 4xx other\n * than 408 and 429).\n *\n * @param error - The thrown value.\n * @returns True if the error should not be retried.\n */\nfunction isNonRetryableClientError(error: unknown): boolean {\n const status = getErrorStatus(error);\n return (\n typeof status === 'number' &&\n status >= 400 &&\n status < 500 &&\n status !== 408 &&\n status !== 429\n );\n}\n\n/**\n * Builds the default policy options. Errors without a numeric status (network\n * errors), 5xx, 408 and 429 count toward the circuit breaker and are retried;\n * other 4xx and `BrokenCircuitError` are neither.\n *\n * @returns The default policy options.\n */\nfunction getDefaultPolicyOptions(): CreateServicePolicyOptions {\n return {\n maxRetries: 3,\n retryFilterPolicy: handleWhen(\n (error) =>\n !(error instanceof BrokenCircuitError) &&\n !isNonRetryableClientError(error),\n ),\n backoff: new ExponentialBackoff({ initialDelay: 1000, maxDelay: 5000 }),\n isServiceFailure: (error) => {\n const status = getErrorStatus(error);\n return (\n typeof status !== 'number' ||\n status >= 500 ||\n status === 408 ||\n status === 429\n );\n },\n circuitBreakDuration: DEFAULT_CIRCUIT_BREAK_DURATION_MS,\n };\n}\n\n/**\n * Generates a short random value for the `bypassServerCache` query parameter,\n * exactly as the core backend Accounts API client does. The API's server side\n * cache keys on the full URL, so a unique value forces a cache miss.\n *\n * @returns An 8 character alphanumeric string.\n */\nfunction generateBypassServerCache(): string {\n return Math.random().toString(36).slice(2, 10).padEnd(8, '0');\n}\n\n/**\n * Returns a sorted copy of a list, or `null` when it is absent, so it can be\n * used in a query key.\n *\n * @param list - The list to sort.\n * @returns The sorted copy, or `null`.\n */\nfunction sortedOrNull(list: string[] | undefined): string[] | null {\n return list ? [...list].sort() : null;\n}\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = ['fetchBalances'] as const;\n\n/**\n * Invalidates cached queries for {@link AccountsApiBalancesService}.\n */\nexport type AccountsApiBalancesServiceInvalidateQueriesAction =\n DataServiceInvalidateQueriesAction<typeof serviceName>;\n\n/**\n * Actions that {@link AccountsApiBalancesService} exposes to other consumers.\n */\nexport type AccountsApiBalancesServiceActions =\n | AccountsApiBalancesServiceMethodActions\n | AccountsApiBalancesServiceInvalidateQueriesAction;\n\n/**\n * Retrieves a bearer token from the `AuthenticationController`.\n */\ntype AuthenticationControllerGetBearerTokenAction = {\n type: 'AuthenticationController:getBearerToken';\n handler: (entropySourceId?: string) => Promise<string>;\n};\n\n/**\n * Actions from other messengers that {@link AccountsApiBalancesService}\n * calls.\n */\ntype AllowedActions = AuthenticationControllerGetBearerTokenAction;\n\n/**\n * Published when {@link AccountsApiBalancesService}'s cache is updated.\n */\nexport type AccountsApiBalancesServiceCacheUpdatedEvent =\n DataServiceCacheUpdatedEvent<typeof serviceName>;\n\n/**\n * Published when a key within {@link AccountsApiBalancesService}'s cache is\n * updated.\n */\nexport type AccountsApiBalancesServiceGranularCacheUpdatedEvent =\n DataServiceGranularCacheUpdatedEvent<typeof serviceName>;\n\n/**\n * Events that {@link AccountsApiBalancesService} exposes to other consumers.\n */\nexport type AccountsApiBalancesServiceEvents =\n | AccountsApiBalancesServiceCacheUpdatedEvent\n | AccountsApiBalancesServiceGranularCacheUpdatedEvent;\n\n/**\n * Events from other messengers that {@link AccountsApiBalancesService}\n * subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link AccountsApiBalancesService}.\n */\nexport type AccountsApiBalancesServiceMessenger = Messenger<\n typeof serviceName,\n AccountsApiBalancesServiceActions | AllowedActions,\n AccountsApiBalancesServiceEvents | AllowedEvents\n>;\n\n// === SERVICE DEFINITION ===\n\n/**\n * Options accepted by {@link AccountsApiBalancesService.fetchBalances}.\n */\nexport type FetchBalancesOptions = {\n /** Which multi account balances endpoint to call. */\n version: 'v5' | 'v6';\n /** CAIP-10 account IDs to fetch balances for. */\n accountIds: string[];\n /** CAIP-19 asset IDs the backend must always return (v6 only). */\n includeAssetIds?: string[];\n /** CAIP-19 asset IDs the backend must drop (v6 only). */\n excludeAssetIds?: string[];\n /** CAIP-2 chain IDs to restrict the response to. */\n networks?: string[];\n /** When true, ignores any cached result and fetches fresh data. */\n forceUpdate?: boolean;\n /**\n * When true, adds a random `bypassServerCache` query parameter so the API's\n * own cache is skipped too. Such fetches use their own cache entry and are\n * never served from the cache.\n */\n bypassServerCache?: boolean;\n /**\n * Called with the state of the underlying query as it changes. See\n * {@link QueryStateChangeHandler}.\n */\n onQueryStateChange?: QueryStateChangeHandler;\n};\n\n/**\n * Data service that fetches multi account balances from the Accounts API v5\n * and v6 endpoints.\n *\n * It sends the same request as the core backend `ApiPlatformClient` (URL,\n * query parameters and headers), wraps it in a service policy, and validates\n * the response before returning it. It has no persistence.\n */\nexport class AccountsApiBalancesService extends BaseDataService<\n typeof serviceName,\n AccountsApiBalancesServiceMessenger\n> {\n readonly #fetch: typeof globalThis.fetch;\n\n readonly #baseUrl: string;\n\n readonly #clientProduct: string;\n\n readonly #clientVersion: string | undefined;\n\n readonly #authTokenTimeout: number;\n\n readonly #staleTime: number;\n\n readonly #gcTime: number;\n\n /**\n * Constructs a new {@link AccountsApiBalancesService}.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this service.\n * @param args.fetch - A function that can be used to make an HTTP request.\n * @param args.clientProduct - Sent as the `x-metamask-clientproduct` header.\n * @param args.clientVersion - Sent as the `x-metamask-clientversion` header\n * when set.\n * @param args.baseUrl - The Accounts API base URL. Defaults to production.\n * @param args.authTokenTimeout - How long to wait for the bearer token, in\n * milliseconds, before sending the request without it. 0 waits forever.\n * Defaults to 500.\n * @param args.staleTime - How long a response is served from cache, in\n * milliseconds. Defaults to 1 minute.\n * @param args.gcTime - How long an unused response stays in memory, in\n * milliseconds. Defaults to 5 minutes.\n * @param args.policyOptions - Overrides for the default policy options\n * passed to `createServicePolicy`. See {@link CreateServicePolicyOptions}.\n * Each override replaces the default for that key as a whole, so passing\n * `retryFilterPolicy` or `isServiceFailure` drops the default\n * `BrokenCircuitError` and 4xx handling. One policy, and so one circuit\n * breaker, is shared by v5, v6 and every query key of a service instance:\n * once it trips, both versions fail fast for the break duration (balances\n * then fall back to RPC).\n */\n constructor({\n messenger,\n fetch: fetchFunction,\n clientProduct,\n clientVersion,\n baseUrl = DEFAULT_BASE_URL,\n authTokenTimeout = DEFAULT_AUTH_TOKEN_TIMEOUT_MS,\n staleTime = DEFAULT_STALE_TIME_MS,\n gcTime = DEFAULT_GC_TIME_MS,\n policyOptions = {},\n }: {\n messenger: AccountsApiBalancesServiceMessenger;\n fetch: typeof globalThis.fetch;\n clientProduct: string;\n clientVersion?: string;\n baseUrl?: string;\n authTokenTimeout?: number;\n staleTime?: number;\n gcTime?: number;\n policyOptions?: CreateServicePolicyOptions;\n }) {\n super({\n name: serviceName,\n messenger,\n policyOptions: { ...getDefaultPolicyOptions(), ...policyOptions },\n });\n this.#fetch = fetchFunction;\n this.#baseUrl = baseUrl;\n this.#clientProduct = clientProduct;\n this.#clientVersion = clientVersion;\n this.#authTokenTimeout = authTokenTimeout;\n this.#staleTime = staleTime;\n this.#gcTime = gcTime;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Fetches balances for the given accounts from the Accounts API v5 or v6\n * multi account balances endpoint. Serves from cache when fresh, and shares\n * one request between concurrent identical calls.\n *\n * @param options - The fetch options. See {@link FetchBalancesOptions}.\n * @returns The validated balances response.\n */\n async fetchBalances(\n options: FetchBalancesOptions,\n ): Promise<BalancesResponse> {\n const {\n version,\n accountIds,\n includeAssetIds,\n excludeAssetIds,\n networks,\n forceUpdate = false,\n bypassServerCache = false,\n onQueryStateChange,\n } = options;\n\n if (accountIds.length === 0) {\n return version === 'v6'\n ? {\n unprocessedNetworks: [],\n unprocessedIncludeAssetIds: [],\n balances: [],\n }\n : { count: 0, unprocessedNetworks: [], balances: [] };\n }\n\n const queryKey = [\n `${this.name}:fetchBalances`,\n version,\n [...accountIds].sort(),\n {\n // v5 never sends these lists, so they stay out of its key.\n includeAssetIds:\n version === 'v6' ? sortedOrNull(includeAssetIds) : null,\n excludeAssetIds:\n version === 'v6' ? sortedOrNull(excludeAssetIds) : null,\n networks: sortedOrNull(networks),\n bypassServerCache,\n },\n ] as const;\n\n if (forceUpdate) {\n await this.invalidateQueries({\n queryKey,\n exact: true,\n refetchType: 'none',\n });\n }\n\n const responseStruct = (version === 'v6'\n ? V6BalancesResponseStruct\n : V5BalancesResponseStruct) as unknown as Struct<BalancesResponse>;\n\n return await this.fetchQuery({\n queryKey,\n responseStruct,\n staleTime: bypassServerCache ? 0 : this.#staleTime,\n gcTime: this.#gcTime,\n onQueryStateChange,\n queryFn: async () => {\n const url = this.#buildUrl(version, {\n accountIds,\n networks,\n ...(version === 'v6' ? { includeAssetIds, excludeAssetIds } : {}),\n bypassServerCache: bypassServerCache\n ? generateBypassServerCache()\n : undefined,\n });\n const response = await this.#fetch(url, {\n method: 'GET',\n headers: await this.#buildHeaders(),\n });\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Accounts API ${version} balances request failed with status '${response.status}'`,\n );\n }\n return (await response.json()) as BalancesResponse;\n },\n });\n }\n\n /**\n * Builds the request URL. Mirrors the core backend client: undefined\n * parameters are skipped and arrays are joined with commas.\n *\n * @param version - The endpoint version.\n * @param params - The query parameters, in the order the client sends them.\n * @returns The request URL.\n */\n #buildUrl(\n version: 'v5' | 'v6',\n params: Record<string, string | string[] | undefined>,\n ): string {\n const url = new URL(`/${version}/multiaccount/balances`, this.#baseUrl);\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) {\n continue;\n }\n url.searchParams.set(key, Array.isArray(value) ? value.join(',') : value);\n }\n return url.toString();\n }\n\n /**\n * Builds the request headers, as the core backend client does.\n *\n * @returns The request headers.\n */\n async #buildHeaders(): Promise<Record<string, string>> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'x-metamask-clientproduct': this.#clientProduct,\n };\n if (this.#clientVersion) {\n headers['x-metamask-clientversion'] = this.#clientVersion;\n }\n const token = await this.#getBearerToken();\n if (token) {\n headers.Authorization = `Bearer ${token}`;\n }\n return headers;\n }\n\n /**\n * Resolves the bearer token, giving up after `authTokenTimeout` so a slow\n * token provider does not delay the request. Without a token in time, the\n * request goes out unauthenticated, as with the core backend client.\n *\n * @returns The bearer token, or undefined if unavailable in time.\n */\n async #getBearerToken(): Promise<string | undefined> {\n const tokenPromise = (async (): Promise<string | undefined> =>\n this.messenger.call('AuthenticationController:getBearerToken'))().catch(\n () => undefined,\n );\n\n if (this.#authTokenTimeout <= 0) {\n return await tokenPromise;\n }\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<undefined>((resolve) => {\n timeoutId = setTimeout(() => resolve(undefined), this.#authTokenTimeout);\n });\n\n try {\n return await Promise.race([tokenPromise, timeoutPromise]);\n } finally {\n clearTimeout(timeoutId);\n }\n }\n}\n"]}
|