@metamask-previews/assets-controller 20.2.3-preview-2ad7fb9 → 20.2.3-preview-55295a2

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +0 -19
  2. package/README.md +0 -6
  3. package/dist/AssetsController.d.ts +2 -11
  4. package/dist/AssetsController.d.ts.map +1 -1
  5. package/dist/AssetsController.js +7 -55
  6. package/dist/AssetsController.js.map +1 -1
  7. package/dist/data-sources/AccountsApiDataSource.d.ts +3 -20
  8. package/dist/data-sources/AccountsApiDataSource.d.ts.map +1 -1
  9. package/dist/data-sources/AccountsApiDataSource.js +4 -66
  10. package/dist/data-sources/AccountsApiDataSource.js.map +1 -1
  11. package/dist/index.d.ts +1 -6
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +0 -3
  14. package/dist/index.js.map +1 -1
  15. package/dist/types.d.ts +0 -17
  16. package/dist/types.d.ts.map +1 -1
  17. package/dist/types.js.map +1 -1
  18. package/package.json +1 -3
  19. package/dist/accounts-api-balances-service/accounts-api-balances-service-method-action-types.d.ts +0 -22
  20. package/dist/accounts-api-balances-service/accounts-api-balances-service-method-action-types.d.ts.map +0 -1
  21. package/dist/accounts-api-balances-service/accounts-api-balances-service-method-action-types.js +0 -6
  22. package/dist/accounts-api-balances-service/accounts-api-balances-service-method-action-types.js.map +0 -1
  23. package/dist/accounts-api-balances-service/accounts-api-balances-service.d.ts +0 -140
  24. package/dist/accounts-api-balances-service/accounts-api-balances-service.d.ts.map +0 -1
  25. package/dist/accounts-api-balances-service/accounts-api-balances-service.js +0 -280
  26. package/dist/accounts-api-balances-service/accounts-api-balances-service.js.map +0 -1
  27. package/dist/accounts-api-balances-service/structs.d.ts +0 -208
  28. package/dist/accounts-api-balances-service/structs.d.ts.map +0 -1
  29. package/dist/accounts-api-balances-service/structs.js +0 -92
  30. package/dist/accounts-api-balances-service/structs.js.map +0 -1
  31. package/dist/assetsFetchTracker.d.ts +0 -31
  32. package/dist/assetsFetchTracker.d.ts.map +0 -1
  33. package/dist/assetsFetchTracker.js +0 -85
  34. package/dist/assetsFetchTracker.js.map +0 -1
  35. package/dist/selectors/fetchStatus.d.ts +0 -36
  36. package/dist/selectors/fetchStatus.d.ts.map +0 -1
  37. package/dist/selectors/fetchStatus.js +0 -44
  38. package/dist/selectors/fetchStatus.js.map +0 -1
@@ -1,280 +0,0 @@
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
@@ -1 +0,0 @@
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;;;;;;;;;;GAUG;AACH,SAAS,cAAc,CAAC,KAAc;IACpC,MAAM,SAAS,GAAG,KAGL,CAAC;IACd,OAAO,SAAS,EAAE,UAAU,IAAI,SAAS,EAAE,MAAM,CAAC;AACpD,CAAC;AAED;;;;;;GAMG;AACH,SAAS,yBAAyB,CAAC,KAAc;IAC/C,MAAM,MAAM,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;IACrC,OAAO,CACL,OAAO,MAAM,KAAK,QAAQ;QAC1B,MAAM,IAAI,GAAG;QACb,MAAM,GAAG,GAAG;QACZ,MAAM,KAAK,GAAG;QACd,MAAM,KAAK,GAAG,CACf,CAAC;AACJ,CAAC;AAED;;;;;;GAM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SAChD,CAAC;QACF,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACxB,OAAO,CAAC,0BAA0B,CAAC,GAAG,IAAI,CAAC,cAAc,CAAC;QAC5D,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,eAAe,EAAE,CAAC;QAC3C,IAAI,KAAK,EAAE,CAAC;YACV,OAAO,CAAC,aAAa,GAAG,UAAU,KAAK,EAAE,CAAC;QAC5C,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,eAAe;QACnB,MAAM,YAAY,GAAG,CAAC,KAAK,IAAiC,EAAE,CAC5D,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,yCAAyC,CAAC,CAAC,EAAE,CAAC,KAAK,CACvE,GAAG,EAAE,CAAC,SAAS,CAChB,CAAC;QAEF,IAAI,IAAI,CAAC,iBAAiB,IAAI,CAAC,EAAE,CAAC;YAChC,OAAO,MAAM,YAAY,CAAC;QAC5B,CAAC;QAED,IAAI,SAAoD,CAAC;QACzD,MAAM,cAAc,GAAG,IAAI,OAAO,CAAY,CAAC,OAAO,EAAE,EAAE;YACxD,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,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"]}
@@ -1,208 +0,0 @@
1
- import type { Infer } from '@metamask/superstruct';
2
- /** Accounts API v5 multi account balances response. */
3
- export declare const V5BalancesResponseStruct: import("@metamask/superstruct").Struct<{
4
- count: number;
5
- unprocessedNetworks: string[];
6
- balances: {
7
- object?: string | null | undefined;
8
- symbol?: string | null | undefined;
9
- name?: string | null | undefined;
10
- type?: string | null | undefined;
11
- decimals?: number | null | undefined;
12
- assetId: string;
13
- balance: string;
14
- accountId: string;
15
- metadata?: {
16
- limit?: string | undefined;
17
- authorized?: boolean | undefined;
18
- sponsored?: boolean | undefined;
19
- spendableBalance?: string | undefined;
20
- minimumReserveBalance?: string | undefined;
21
- } | null | undefined;
22
- }[];
23
- }, {
24
- count: import("@metamask/superstruct").Struct<number, null>;
25
- unprocessedNetworks: import("@metamask/superstruct").Struct<string[], import("@metamask/superstruct").Struct<string, null>>;
26
- balances: import("@metamask/superstruct").Struct<{
27
- object?: string | null | undefined;
28
- symbol?: string | null | undefined;
29
- name?: string | null | undefined;
30
- type?: string | null | undefined;
31
- decimals?: number | null | undefined;
32
- assetId: string;
33
- balance: string;
34
- accountId: string;
35
- metadata?: {
36
- limit?: string | undefined;
37
- authorized?: boolean | undefined;
38
- sponsored?: boolean | undefined;
39
- spendableBalance?: string | undefined;
40
- minimumReserveBalance?: string | undefined;
41
- } | null | undefined;
42
- }[], import("@metamask/superstruct").Struct<{
43
- object?: string | null | undefined;
44
- symbol?: string | null | undefined;
45
- name?: string | null | undefined;
46
- type?: string | null | undefined;
47
- decimals?: number | null | undefined;
48
- assetId: string;
49
- balance: string;
50
- accountId: string;
51
- metadata?: {
52
- limit?: string | undefined;
53
- authorized?: boolean | undefined;
54
- sponsored?: boolean | undefined;
55
- spendableBalance?: string | undefined;
56
- minimumReserveBalance?: string | undefined;
57
- } | null | undefined;
58
- }, {
59
- object: import("@metamask/superstruct").Struct<string | null | undefined, null>;
60
- symbol: import("@metamask/superstruct").Struct<string | null | undefined, null>;
61
- name: import("@metamask/superstruct").Struct<string | null | undefined, null>;
62
- type: import("@metamask/superstruct").Struct<string | null | undefined, null>;
63
- decimals: import("@metamask/superstruct").Struct<number | null | undefined, null>;
64
- assetId: import("@metamask/superstruct").Struct<string, null>;
65
- balance: import("@metamask/superstruct").Struct<string, null>;
66
- accountId: import("@metamask/superstruct").Struct<string, null>;
67
- metadata: import("@metamask/superstruct").Struct<{
68
- limit?: string | undefined;
69
- authorized?: boolean | undefined;
70
- sponsored?: boolean | undefined;
71
- spendableBalance?: string | undefined;
72
- minimumReserveBalance?: string | undefined;
73
- } | null | undefined, {
74
- limit: import("@metamask/superstruct").Struct<string | undefined, null>;
75
- authorized: import("@metamask/superstruct").Struct<boolean | undefined, null>;
76
- sponsored: import("@metamask/superstruct").Struct<boolean | undefined, null>;
77
- spendableBalance: import("@metamask/superstruct").Struct<string | undefined, null>;
78
- minimumReserveBalance: import("@metamask/superstruct").Struct<string | undefined, null>;
79
- }>;
80
- }>>;
81
- }>;
82
- /** Accounts API v6 multi account balances response. */
83
- export declare const V6BalancesResponseStruct: import("@metamask/superstruct").Struct<{
84
- unprocessedNetworks: string[];
85
- unprocessedIncludeAssetIds: string[];
86
- balances: {
87
- accountId: string;
88
- object: string;
89
- type?: string | null | undefined;
90
- assetId: string;
91
- name?: string | null | undefined;
92
- symbol?: string | null | undefined;
93
- decimals?: number | null | undefined;
94
- balance: string;
95
- price?: string | null | undefined;
96
- labels?: string[] | null | undefined;
97
- canonicalHead?: string | null | undefined;
98
- metadata?: {
99
- limit?: string | undefined;
100
- authorized?: boolean | undefined;
101
- sponsored?: boolean | undefined;
102
- spendableBalance?: string | undefined;
103
- minimumReserveBalance?: string | undefined;
104
- } | {
105
- protocolId: string;
106
- productName: string;
107
- description: string;
108
- protocolUrl: string;
109
- protocolIconUrl?: string | undefined;
110
- positionType: "deposit" | "investment" | "loan" | "locked" | "reward" | "staked" | "wallet";
111
- poolAddress: string;
112
- groupId: string;
113
- } | null | undefined;
114
- }[];
115
- processingDefiPositions?: string[] | null | undefined;
116
- }, {
117
- unprocessedNetworks: import("@metamask/superstruct").Struct<string[], import("@metamask/superstruct").Struct<string, null>>;
118
- unprocessedIncludeAssetIds: import("@metamask/superstruct").Struct<string[], import("@metamask/superstruct").Struct<string, null>>;
119
- balances: import("@metamask/superstruct").Struct<{
120
- accountId: string;
121
- object: string;
122
- type?: string | null | undefined;
123
- assetId: string;
124
- name?: string | null | undefined;
125
- symbol?: string | null | undefined;
126
- decimals?: number | null | undefined;
127
- balance: string;
128
- price?: string | null | undefined;
129
- labels?: string[] | null | undefined;
130
- canonicalHead?: string | null | undefined;
131
- metadata?: {
132
- limit?: string | undefined;
133
- authorized?: boolean | undefined;
134
- sponsored?: boolean | undefined;
135
- spendableBalance?: string | undefined;
136
- minimumReserveBalance?: string | undefined;
137
- } | {
138
- protocolId: string;
139
- productName: string;
140
- description: string;
141
- protocolUrl: string;
142
- protocolIconUrl?: string | undefined;
143
- positionType: "deposit" | "investment" | "loan" | "locked" | "reward" | "staked" | "wallet";
144
- poolAddress: string;
145
- groupId: string;
146
- } | null | undefined;
147
- }[], import("@metamask/superstruct").Struct<{
148
- accountId: string;
149
- object: string;
150
- type?: string | null | undefined;
151
- assetId: string;
152
- name?: string | null | undefined;
153
- symbol?: string | null | undefined;
154
- decimals?: number | null | undefined;
155
- balance: string;
156
- price?: string | null | undefined;
157
- labels?: string[] | null | undefined;
158
- canonicalHead?: string | null | undefined;
159
- metadata?: {
160
- limit?: string | undefined;
161
- authorized?: boolean | undefined;
162
- sponsored?: boolean | undefined;
163
- spendableBalance?: string | undefined;
164
- minimumReserveBalance?: string | undefined;
165
- } | {
166
- protocolId: string;
167
- productName: string;
168
- description: string;
169
- protocolUrl: string;
170
- protocolIconUrl?: string | undefined;
171
- positionType: "deposit" | "investment" | "loan" | "locked" | "reward" | "staked" | "wallet";
172
- poolAddress: string;
173
- groupId: string;
174
- } | null | undefined;
175
- }, {
176
- accountId: import("@metamask/superstruct").Struct<string, null>;
177
- object: import("@metamask/superstruct").Struct<string, null>;
178
- type: import("@metamask/superstruct").Struct<string | null | undefined, null>;
179
- assetId: import("@metamask/superstruct").Struct<string, null>;
180
- name: import("@metamask/superstruct").Struct<string | null | undefined, null>;
181
- symbol: import("@metamask/superstruct").Struct<string | null | undefined, null>;
182
- decimals: import("@metamask/superstruct").Struct<number | null | undefined, null>;
183
- balance: import("@metamask/superstruct").Struct<string, null>;
184
- price: import("@metamask/superstruct").Struct<string | null | undefined, null>;
185
- labels: import("@metamask/superstruct").Struct<string[] | null | undefined, import("@metamask/superstruct").Struct<string, null>>;
186
- canonicalHead: import("@metamask/superstruct").Struct<string | null | undefined, null>;
187
- metadata: import("@metamask/superstruct").Struct<{
188
- limit?: string | undefined;
189
- authorized?: boolean | undefined;
190
- sponsored?: boolean | undefined;
191
- spendableBalance?: string | undefined;
192
- minimumReserveBalance?: string | undefined;
193
- } | {
194
- protocolId: string;
195
- productName: string;
196
- description: string;
197
- protocolUrl: string;
198
- protocolIconUrl?: string | undefined;
199
- positionType: "deposit" | "investment" | "loan" | "locked" | "reward" | "staked" | "wallet";
200
- poolAddress: string;
201
- groupId: string;
202
- } | null | undefined, null>;
203
- }>>;
204
- processingDefiPositions: import("@metamask/superstruct").Struct<string[] | null | undefined, import("@metamask/superstruct").Struct<string, null>>;
205
- }>;
206
- /** A validated v5 or v6 balances response. */
207
- export type BalancesResponse = Infer<typeof V5BalancesResponseStruct> | Infer<typeof V6BalancesResponseStruct>;
208
- //# sourceMappingURL=structs.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"structs.d.ts","sourceRoot":"","sources":["../../src/accounts-api-balances-service/structs.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAuFnD,uDAAuD;AACvD,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAInC,CAAC;AAEH,uDAAuD;AACvD,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAKnC,CAAC;AAEH,8CAA8C;AAC9C,MAAM,MAAM,gBAAgB,GACxB,KAAK,CAAC,OAAO,wBAAwB,CAAC,GACtC,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC"}
@@ -1,92 +0,0 @@
1
- import { array, boolean, enums, nullable, number, optional, string, type, union, } from '@metamask/superstruct';
2
- /**
3
- * Stellar specific token metadata (trustline and native reserve fields).
4
- * All fields are optional and unknown fields are allowed.
5
- */
6
- const TokenBalanceMetadataStruct = type({
7
- limit: optional(string()),
8
- authorized: optional(boolean()),
9
- sponsored: optional(boolean()),
10
- spendableBalance: optional(string()),
11
- minimumReserveBalance: optional(string()),
12
- });
13
- /**
14
- * DeFi protocol metadata attached to `object: defi` rows (v6 only).
15
- */
16
- const DefiBalanceMetadataStruct = type({
17
- protocolId: string(),
18
- productName: string(),
19
- description: string(),
20
- protocolUrl: string(),
21
- protocolIconUrl: optional(string()),
22
- positionType: enums([
23
- 'deposit',
24
- 'loan',
25
- 'locked',
26
- 'staked',
27
- 'reward',
28
- 'wallet',
29
- 'investment',
30
- ]),
31
- poolAddress: string(),
32
- groupId: string(),
33
- });
34
- /**
35
- * A string field the data source does not read. It is kept loose (optional
36
- * and nullable) so an API change to it never rejects a whole response.
37
- */
38
- const LooseStringStruct = optional(nullable(string()));
39
- /**
40
- * A number field the data source does not read, kept loose for the same
41
- * reason as {@link LooseStringStruct}.
42
- */
43
- const LooseNumberStruct = optional(nullable(number()));
44
- /**
45
- * A v5 balance row. Only `accountId`, `assetId`, `balance` and `metadata` are
46
- * read by the data source, every other field is loose.
47
- */
48
- const V5BalanceItemStruct = type({
49
- object: LooseStringStruct,
50
- symbol: LooseStringStruct,
51
- name: LooseStringStruct,
52
- type: LooseStringStruct,
53
- decimals: LooseNumberStruct,
54
- assetId: string(),
55
- balance: string(),
56
- accountId: string(),
57
- metadata: optional(nullable(TokenBalanceMetadataStruct)),
58
- });
59
- /**
60
- * A v6 balance row. Only `accountId`, `assetId`, `balance`, `object` and
61
- * `metadata` are read by the data source, every other field is loose.
62
- * `object` is a plain string so unknown row kinds are skipped by the data
63
- * source instead of rejecting the response.
64
- */
65
- const V6BalanceItemStruct = type({
66
- accountId: string(),
67
- object: string(),
68
- type: LooseStringStruct,
69
- assetId: string(),
70
- name: LooseStringStruct,
71
- symbol: LooseStringStruct,
72
- decimals: LooseNumberStruct,
73
- balance: string(),
74
- price: LooseStringStruct,
75
- labels: optional(nullable(array(string()))),
76
- canonicalHead: LooseStringStruct,
77
- metadata: optional(nullable(union([DefiBalanceMetadataStruct, TokenBalanceMetadataStruct]))),
78
- });
79
- /** Accounts API v5 multi account balances response. */
80
- export const V5BalancesResponseStruct = type({
81
- count: number(),
82
- unprocessedNetworks: array(string()),
83
- balances: array(V5BalanceItemStruct),
84
- });
85
- /** Accounts API v6 multi account balances response. */
86
- export const V6BalancesResponseStruct = type({
87
- unprocessedNetworks: array(string()),
88
- unprocessedIncludeAssetIds: array(string()),
89
- balances: array(V6BalanceItemStruct),
90
- processingDefiPositions: optional(nullable(array(string()))),
91
- });
92
- //# sourceMappingURL=structs.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"structs.js","sourceRoot":"","sources":["../../src/accounts-api-balances-service/structs.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,OAAO,EACP,KAAK,EACL,QAAQ,EACR,MAAM,EACN,QAAQ,EACR,MAAM,EACN,IAAI,EACJ,KAAK,GACN,MAAM,uBAAuB,CAAC;AAG/B;;;GAGG;AACH,MAAM,0BAA0B,GAAG,IAAI,CAAC;IACtC,KAAK,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;IACzB,UAAU,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC/B,SAAS,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC9B,gBAAgB,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;IACpC,qBAAqB,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;CAC1C,CAAC,CAAC;AAEH;;GAEG;AACH,MAAM,yBAAyB,GAAG,IAAI,CAAC;IACrC,UAAU,EAAE,MAAM,EAAE;IACpB,WAAW,EAAE,MAAM,EAAE;IACrB,WAAW,EAAE,MAAM,EAAE;IACrB,WAAW,EAAE,MAAM,EAAE;IACrB,eAAe,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;IACnC,YAAY,EAAE,KAAK,CAAC;QAClB,SAAS;QACT,MAAM;QACN,QAAQ;QACR,QAAQ;QACR,QAAQ;QACR,QAAQ;QACR,YAAY;KACb,CAAC;IACF,WAAW,EAAE,MAAM,EAAE;IACrB,OAAO,EAAE,MAAM,EAAE;CAClB,CAAC,CAAC;AAEH;;;GAGG;AACH,MAAM,iBAAiB,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;AAEvD;;;GAGG;AACH,MAAM,iBAAiB,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;AAEvD;;;GAGG;AACH,MAAM,mBAAmB,GAAG,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,MAAM,EAAE,CAAC;IAC3C,QAAQ,EAAE,KAAK,CAAC,mBAAmB,CAAC;IACpC,uBAAuB,EAAE,QAAQ,CAAC,QAAQ,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;CAC7D,CAAC,CAAC","sourcesContent":["import {\n array,\n boolean,\n enums,\n nullable,\n number,\n optional,\n string,\n type,\n union,\n} from '@metamask/superstruct';\nimport type { Infer } from '@metamask/superstruct';\n\n/**\n * Stellar specific token metadata (trustline and native reserve fields).\n * All fields are optional and unknown fields are allowed.\n */\nconst TokenBalanceMetadataStruct = type({\n limit: optional(string()),\n authorized: optional(boolean()),\n sponsored: optional(boolean()),\n spendableBalance: optional(string()),\n minimumReserveBalance: optional(string()),\n});\n\n/**\n * DeFi protocol metadata attached to `object: defi` rows (v6 only).\n */\nconst DefiBalanceMetadataStruct = type({\n protocolId: string(),\n productName: string(),\n description: string(),\n protocolUrl: string(),\n protocolIconUrl: optional(string()),\n positionType: enums([\n 'deposit',\n 'loan',\n 'locked',\n 'staked',\n 'reward',\n 'wallet',\n 'investment',\n ]),\n poolAddress: string(),\n groupId: string(),\n});\n\n/**\n * A string field the data source does not read. It is kept loose (optional\n * and nullable) so an API change to it never rejects a whole response.\n */\nconst LooseStringStruct = optional(nullable(string()));\n\n/**\n * A number field the data source does not read, kept loose for the same\n * reason as {@link LooseStringStruct}.\n */\nconst LooseNumberStruct = optional(nullable(number()));\n\n/**\n * A v5 balance row. Only `accountId`, `assetId`, `balance` and `metadata` are\n * read by the data source, every other field is loose.\n */\nconst V5BalanceItemStruct = type({\n object: LooseStringStruct,\n symbol: LooseStringStruct,\n name: LooseStringStruct,\n type: LooseStringStruct,\n decimals: LooseNumberStruct,\n assetId: string(),\n balance: string(),\n accountId: string(),\n metadata: optional(nullable(TokenBalanceMetadataStruct)),\n});\n\n/**\n * A v6 balance row. Only `accountId`, `assetId`, `balance`, `object` and\n * `metadata` are read by the data source, every other field is loose.\n * `object` is a plain string so unknown row kinds are skipped by the data\n * source instead of rejecting the response.\n */\nconst V6BalanceItemStruct = type({\n accountId: string(),\n object: string(),\n type: LooseStringStruct,\n assetId: string(),\n name: LooseStringStruct,\n symbol: LooseStringStruct,\n decimals: LooseNumberStruct,\n balance: string(),\n price: LooseStringStruct,\n labels: optional(nullable(array(string()))),\n canonicalHead: LooseStringStruct,\n metadata: optional(\n nullable(union([DefiBalanceMetadataStruct, TokenBalanceMetadataStruct])),\n ),\n});\n\n/** Accounts API v5 multi account balances response. */\nexport const V5BalancesResponseStruct = type({\n count: number(),\n unprocessedNetworks: array(string()),\n balances: array(V5BalanceItemStruct),\n});\n\n/** Accounts API v6 multi account balances response. */\nexport const V6BalancesResponseStruct = type({\n unprocessedNetworks: array(string()),\n unprocessedIncludeAssetIds: array(string()),\n balances: array(V6BalanceItemStruct),\n processingDefiPositions: optional(nullable(array(string()))),\n});\n\n/** A validated v5 or v6 balances response. */\nexport type BalancesResponse =\n | Infer<typeof V5BalancesResponseStruct>\n | Infer<typeof V6BalancesResponseStruct>;\n"]}