@metamask-previews/assets-controller 20.4.1-preview-e9ac9ffe1 → 20.4.1-preview-70269bbdb

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 (36) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +3 -0
  3. package/dist/AssetsController-method-action-types.d.ts +6 -2
  4. package/dist/AssetsController-method-action-types.d.ts.map +1 -1
  5. package/dist/AssetsController-method-action-types.js.map +1 -1
  6. package/dist/AssetsController.d.ts +11 -13
  7. package/dist/AssetsController.d.ts.map +1 -1
  8. package/dist/AssetsController.js +27 -17
  9. package/dist/AssetsController.js.map +1 -1
  10. package/dist/data-sources/AccountActivityDataSource.d.ts +4 -2
  11. package/dist/data-sources/AccountActivityDataSource.d.ts.map +1 -1
  12. package/dist/data-sources/AccountActivityDataSource.js +3 -1
  13. package/dist/data-sources/AccountActivityDataSource.js.map +1 -1
  14. package/dist/data-sources/MarketStatsPriceStream.d.ts +67 -0
  15. package/dist/data-sources/MarketStatsPriceStream.d.ts.map +1 -0
  16. package/dist/data-sources/MarketStatsPriceStream.js +181 -0
  17. package/dist/data-sources/MarketStatsPriceStream.js.map +1 -0
  18. package/dist/data-sources/PriceDataSource.d.ts +29 -2
  19. package/dist/data-sources/PriceDataSource.d.ts.map +1 -1
  20. package/dist/data-sources/PriceDataSource.js +113 -37
  21. package/dist/data-sources/PriceDataSource.js.map +1 -1
  22. package/dist/data-sources/index.d.ts +1 -1
  23. package/dist/data-sources/index.d.ts.map +1 -1
  24. package/dist/data-sources/index.js.map +1 -1
  25. package/dist/index.d.ts +4 -2
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +2 -0
  28. package/dist/index.js.map +1 -1
  29. package/dist/store/MarketStatsStore.d.ts +72 -0
  30. package/dist/store/MarketStatsStore.d.ts.map +1 -0
  31. package/dist/store/MarketStatsStore.js +182 -0
  32. package/dist/store/MarketStatsStore.js.map +1 -0
  33. package/dist/types.d.ts +5 -0
  34. package/dist/types.d.ts.map +1 -1
  35. package/dist/types.js.map +1 -1
  36. package/package.json +1 -1
@@ -4,6 +4,7 @@ import { DedupingBatchFetcher } from '../utils/dedupingBatchFetcher.js';
4
4
  import { filterAssetsBySupportedNetworks, getAssetIdsForPriceFetch, getUnpricedResponseAssetIds, isPriceableAsset, } from '../utils/getAssetIdsForPriceFetch.js';
5
5
  import { fetchWithTimeout } from '../utils/index.js';
6
6
  import { reduceInBatchesSerially } from './evm-rpc-services/index.js';
7
+ import { MarketStatsPriceStream, readSpotPriceStreamEligibility, } from './MarketStatsPriceStream.js';
7
8
  // ============================================================================
8
9
  // CONSTANTS
9
10
  // ============================================================================
@@ -74,8 +75,13 @@ function isValidMarketData(data) {
74
75
  * - Fetches prices from Price API v3 spot-prices endpoint
75
76
  * - Supports one-time fetch and subscription-based polling
76
77
  * - In subscribe mode, uses constructor `getAssetsState` to read assetsBalance and fetch prices
78
+ * - Streams the same assets the price poll tracks, when the spot-price
79
+ * response marks them `wssSupport: true`, on market-stats.v1. The poll
80
+ * itself is the same as before: every tracked asset, on the same interval.
81
+ * Socket ticks are not written into controller state. The UI reads
82
+ * `MarketStatsService:pricesUpdated`.
77
83
  *
78
- * Usage: Create with queryApiClient and getAssetsState; subscribe() polls prices for held assets.
84
+ * Usage: Create with queryApiClient, messenger, and getAssetsState; subscribe() polls prices for held assets.
79
85
  */
80
86
  export class PriceDataSource {
81
87
  static controllerName = CONTROLLER_NAME;
@@ -95,6 +101,7 @@ export class PriceDataSource {
95
101
  */
96
102
  #deduper;
97
103
  #getAssetsState;
104
+ #marketStats;
98
105
  /** Active subscriptions by ID */
99
106
  #activeSubscriptions = new Map();
100
107
  constructor(options) {
@@ -103,6 +110,10 @@ export class PriceDataSource {
103
110
  this.#apiClient = options.queryApiClient;
104
111
  this.#fetchTimeoutMs = options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
105
112
  this.#getAssetsState = options.getAssetsState;
113
+ this.#marketStats = new MarketStatsPriceStream({
114
+ messenger: options.messenger,
115
+ getSelectedCurrency: () => this.#getSelectedCurrency(),
116
+ });
106
117
  this.#deduper = new DedupingBatchFetcher({
107
118
  fetchBatch: (assetIds) => this.#executeBatchFetch(assetIds),
108
119
  freshnessTtlMs: options.priceFreshnessTtlMs ?? this.#pollInterval,
@@ -182,6 +193,7 @@ export class PriceDataSource {
182
193
  const selectedCurrencyPrices = await fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
183
194
  currency: selectedCurrency,
184
195
  includeMarketData: true,
196
+ includeWssSupportField: true,
185
197
  }), this.#fetchTimeoutMs);
186
198
  return { selectedCurrencyPrices, usdPrices: selectedCurrencyPrices };
187
199
  }
@@ -189,10 +201,12 @@ export class PriceDataSource {
189
201
  fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
190
202
  currency: selectedCurrency,
191
203
  includeMarketData: true,
204
+ includeWssSupportField: true,
192
205
  }), this.#fetchTimeoutMs),
193
206
  fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
194
207
  currency: 'usd',
195
208
  includeMarketData: true,
209
+ includeWssSupportField: true,
196
210
  }), this.#fetchTimeoutMs),
197
211
  ]);
198
212
  return { selectedCurrencyPrices, usdPrices };
@@ -322,8 +336,18 @@ export class PriceDataSource {
322
336
  * @returns DataResponse containing asset prices.
323
337
  */
324
338
  async fetch(request) {
325
- const response = {};
326
339
  const assetIds = await this.#filterToSupportedPriceableAssets(this.#getAssetIdsFromBalanceState(request));
340
+ return this.#fetchAssetIdList(assetIds);
341
+ }
342
+ /**
343
+ * Fetch spot prices for an explicit id list. Empty when there is nothing to
344
+ * price or the Price API call fails.
345
+ *
346
+ * @param assetIds - CAIP-19 asset IDs already filtered to priceable assets.
347
+ * @returns DataResponse containing asset prices.
348
+ */
349
+ async #fetchAssetIdList(assetIds) {
350
+ const response = {};
327
351
  if (assetIds.length === 0) {
328
352
  return response;
329
353
  }
@@ -344,7 +368,7 @@ export class PriceDataSource {
344
368
  // ============================================================================
345
369
  /**
346
370
  * Subscribe to price updates.
347
- * Sets up polling that fetches prices for all assets in assetsBalance state.
371
+ * Polls the Price API, and streams assets that support market-stats.v1.
348
372
  *
349
373
  * @param subscriptionRequest - The subscription request configuration.
350
374
  */
@@ -367,6 +391,7 @@ export class PriceDataSource {
367
391
  updateMode: 'merge',
368
392
  });
369
393
  }
394
+ await this.#reconcileMarketStats();
370
395
  }
371
396
  catch (error) {
372
397
  log('Subscription update fetch failed', { subscriptionId, error });
@@ -383,37 +408,12 @@ export class PriceDataSource {
383
408
  // asset still "fresh" at the next tick, making the subscription re-fetch
384
409
  // only every other poll. The margin also absorbs network latency / jitter.
385
410
  this.#deduper.freshnessTtlMs = Math.min(this.#deduper.freshnessTtlMs, Math.floor(pollInterval * FRESHNESS_TTL_POLL_RATIO));
386
- // Create poll function - fetches prices using constructor getAssetsState.
387
- // The freshness TTL naturally gates re-fetches: assets fetched less than
388
- // `priceFreshnessTtlMs` ago are skipped, preventing duplicates when middleware
389
- // or other triggers already fetched the same assets between polls.
390
- // Concurrent middleware calls will join the inflight promise rather than
391
- // issuing duplicate requests.
392
- const pollFn = async () => {
393
- try {
394
- const subscription = this.#activeSubscriptions.get(subscriptionId);
395
- if (!subscription) {
396
- return;
397
- }
398
- const fetchResponse = await this.fetch(subscription.request);
399
- // Only report if we got prices
400
- if (fetchResponse.assetsPrice &&
401
- Object.keys(fetchResponse.assetsPrice).length > 0) {
402
- await subscription.onAssetsUpdate({
403
- ...fetchResponse,
404
- // merge overwrites existing spot prices on each poll; update would
405
- // seed-only and leave the first price forever.
406
- updateMode: 'merge',
407
- });
408
- }
409
- }
410
- catch (error) {
411
- log('Subscription poll failed', { subscriptionId, error });
412
- }
413
- };
414
- // Set up polling
411
+ // Each tick prices every tracked asset, the same as the poll without
412
+ // market stats. An open channel does not skip one.
415
413
  const timer = setInterval(() => {
416
- pollFn().catch(console.error);
414
+ this.#runPoll(subscriptionId).catch((error) => {
415
+ log('Subscription poll failed', { subscriptionId, error });
416
+ });
417
417
  }, pollInterval);
418
418
  // Store subscription
419
419
  this.#activeSubscriptions.set(subscriptionId, {
@@ -424,7 +424,7 @@ export class PriceDataSource {
424
424
  onAssetsUpdate: subscriptionRequest.onAssetsUpdate,
425
425
  });
426
426
  // Initial fetch
427
- await pollFn();
427
+ await this.#runPoll(subscriptionId);
428
428
  }
429
429
  /**
430
430
  * Unsubscribe from price updates.
@@ -433,10 +433,41 @@ export class PriceDataSource {
433
433
  */
434
434
  async unsubscribe(subscriptionId) {
435
435
  const subscription = this.#activeSubscriptions.get(subscriptionId);
436
- if (subscription) {
437
- subscription.cleanup();
438
- this.#activeSubscriptions.delete(subscriptionId);
436
+ if (!subscription) {
437
+ return;
438
+ }
439
+ subscription.cleanup();
440
+ this.#activeSubscriptions.delete(subscriptionId);
441
+ if (this.#activeSubscriptions.size === 0) {
442
+ await this.#marketStats.releaseSubscriptions();
443
+ return;
444
+ }
445
+ await this.#reconcileMarketStats();
446
+ }
447
+ /**
448
+ * Drop market-stats channels and open them again for the current currency.
449
+ * Called when the selected currency changes so batches match `assetsPrice`.
450
+ */
451
+ async resubscribeForCurrencyChange() {
452
+ if (this.#activeSubscriptions.size === 0) {
453
+ return;
454
+ }
455
+ await this.#marketStats.releaseSubscriptions();
456
+ await this.#reconcileMarketStats();
457
+ }
458
+ /**
459
+ * Align market-stats channels with the price-fetch set and the `wssSupport`
460
+ * already stored in `assetsPrice`.
461
+ *
462
+ * Called after the spot-price response is in `assetsPrice`. A balance
463
+ * update reconciles from `AssetsController` once that write has landed.
464
+ * The price poll reconciles at the end of its own tick.
465
+ */
466
+ async reconcileMarketStreams() {
467
+ if (this.#activeSubscriptions.size === 0) {
468
+ return;
439
469
  }
470
+ await this.#reconcileMarketStats();
440
471
  }
441
472
  /**
442
473
  * Invalidate the price freshness cache, forcing the next fetch to call the
@@ -454,7 +485,52 @@ export class PriceDataSource {
454
485
  subscription.cleanup();
455
486
  }
456
487
  this.#activeSubscriptions.clear();
488
+ this.#marketStats.destroy();
457
489
  this.#deduper.destroy();
458
490
  }
491
+ /**
492
+ * One poll tick: REST-fetch every tracked asset, then open market-stats
493
+ * channels for assets the response marks `wssSupport`.
494
+ *
495
+ * @param subscriptionId - Active subscription to poll.
496
+ */
497
+ async #runPoll(subscriptionId) {
498
+ const subscription = this.#activeSubscriptions.get(subscriptionId);
499
+ if (!subscription) {
500
+ return;
501
+ }
502
+ try {
503
+ const fetchResponse = await this.fetch(subscription.request);
504
+ if (fetchResponse.assetsPrice &&
505
+ Object.keys(fetchResponse.assetsPrice).length > 0) {
506
+ await subscription.onAssetsUpdate({
507
+ ...fetchResponse,
508
+ updateMode: 'merge',
509
+ });
510
+ }
511
+ await this.#reconcileMarketStats();
512
+ }
513
+ catch (error) {
514
+ log('Subscription poll failed', { subscriptionId, error });
515
+ }
516
+ }
517
+ async #reconcileMarketStats() {
518
+ const assetIds = new Set();
519
+ for (const subscription of this.#activeSubscriptions.values()) {
520
+ const ids = await this.#filterToSupportedPriceableAssets(this.#getAssetIdsFromBalanceState(subscription.request));
521
+ for (const assetId of ids) {
522
+ assetIds.add(assetId);
523
+ }
524
+ }
525
+ await this.#marketStats.reconcile(this.#candidatesFor([...assetIds]));
526
+ }
527
+ #candidatesFor(assetIds) {
528
+ const prices = this.#getAssetsState().assetsPrice ?? {};
529
+ return assetIds.map((assetId) => ({
530
+ assetId,
531
+ wssSupport: prices[assetId] !== undefined &&
532
+ readSpotPriceStreamEligibility(prices[assetId]),
533
+ }));
534
+ }
459
535
  }
460
536
  //# sourceMappingURL=PriceDataSource.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"PriceDataSource.js","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAS3C,OAAO,EA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,OAAO,EAAE,CAAC;QACzB,CAAC;QACD,IAAI,CAAC,oBAAoB,CAAC,KAAK,EAAE,CAAC;QAClC,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import type {\n PriceV2SupportedNetworksResponse,\n SupportedCurrency,\n V3SpotPricesResponse,\n} from '@metamask/core-backend';\nimport { ApiPlatformClient } from '@metamask/core-backend';\n\nimport { projectLogger, createModuleLogger } from '../logger.js';\nimport { forDataTypes } from '../types.js';\nimport type {\n Caip19AssetId,\n DataRequest,\n DataResponse,\n FungibleAssetPrice,\n Middleware,\n AssetsControllerState,\n} from '../types.js';\nimport { DedupingBatchFetcher } from '../utils/dedupingBatchFetcher.js';\nimport {\n filterAssetsBySupportedNetworks,\n getAssetIdsForPriceFetch,\n getUnpricedResponseAssetIds,\n isPriceableAsset,\n} from '../utils/getAssetIdsForPriceFetch.js';\nimport { fetchWithTimeout } from '../utils/index.js';\nimport type { SubscriptionRequest } from './AbstractDataSource.js';\nimport { reduceInBatchesSerially } from './evm-rpc-services/index.js';\n\n// ============================================================================\n// CONSTANTS\n// ============================================================================\n\nconst CONTROLLER_NAME = 'PriceDataSource';\nconst DEFAULT_POLL_INTERVAL = 60_000; // 1 minute for price updates\nconst DEFAULT_FETCH_TIMEOUT_MS = 15_000;\n\n/**\n * Fraction of the poll interval used to cap the freshness TTL. Kept strictly\n * below 1 so an asset fetched on one poll is reliably stale by the next poll;\n * the margin absorbs network latency and timer jitter (see the cap in\n * `subscribe`).\n */\nconst FRESHNESS_TTL_POLL_RATIO = 0.9;\n\n/** Maximum number of asset IDs per Price API request. */\nconst PRICE_API_BATCH_SIZE = 50;\n\nconst log = createModuleLogger(projectLogger, CONTROLLER_NAME);\n\n// ============================================================================\n// HELPERS\n// ============================================================================\n\n/**\n * Extracts the CAIP-2 chain IDs the Price API v3 spot-prices endpoint\n * supports from a `/v2/supportedNetworks` response.\n *\n * The endpoint returns `partialSupport` as an object keyed by spot-price\n * endpoint (`{ spotPricesV2, spotPricesV3 }`). Since this data source only\n * calls `/v3/spot-prices`, only `spotPricesV3` is relevant. A legacy\n * array-shaped `partialSupport` is still accepted so a transient schema\n * change does not disable price fetching.\n *\n * @param response - The supported networks response.\n * @param response.fullSupport - Chains supported by every endpoint.\n * @param response.partialSupport - Chains supported by specific endpoints.\n * @returns Unique CAIP-2 chain IDs supported by v3 spot prices.\n */\nfunction getV3SpotPriceSupportedChainIds(response: {\n fullSupport?: string[];\n partialSupport?:\n | string[]\n | Partial<PriceV2SupportedNetworksResponse['partialSupport']>;\n}): Set<string> {\n const { fullSupport, partialSupport } = response;\n const partial = Array.isArray(partialSupport)\n ? partialSupport\n : (partialSupport?.spotPricesV3 ?? []);\n return new Set([...(fullSupport ?? []), ...partial]);\n}\n\n// ============================================================================\n// OPTIONS\n// ============================================================================\n\n/** Optional configuration for PriceDataSource. */\nexport type PriceDataSourceConfig = {\n /** Polling interval in ms (default: 60000) */\n pollInterval?: number;\n /**\n * Timeout in ms for a single Price API call (default: 15000). When it fires,\n * the batch rejects so the caller can proceed without prices.\n */\n fetchTimeoutMs?: number;\n /**\n * Minimum age (ms) before a price is considered stale and re-fetched.\n * Assets fetched more recently than this are skipped to avoid redundant\n * API calls from overlapping middleware / subscription / manual triggers.\n * Defaults to pollInterval (60 000 ms).\n */\n priceFreshnessTtlMs?: number;\n};\n\nexport type PriceDataSourceOptions = PriceDataSourceConfig & {\n /** ApiPlatformClient for API calls with caching */\n queryApiClient: ApiPlatformClient;\n /** Function returning the currently-active ISO 4217 currency code */\n getSelectedCurrency: () => SupportedCurrency;\n /** Current AssetsController state. Used for balance-based pricing and freshness checks. */\n getAssetsState: () => AssetsControllerState;\n};\n\n// ============================================================================\n// HELPER FUNCTIONS\n// ============================================================================\n\n/**\n * Asset reference patterns that should NOT be sent to the Price API.\n * These are internal resource tracking values without market prices.\n */\nexport { isPriceableAsset } from '../utils/getAssetIdsForPriceFetch.js';\n\n/** Market data item from spot prices response (same as FungibleAssetPrice without lastUpdated) */\ntype SpotPriceMarketData = Omit<\n FungibleAssetPrice,\n 'lastUpdated' | 'assetPriceType'\n>;\n\n/**\n * Type guard to check if market data has a valid price\n *\n * @param data - The data to check.\n * @returns True if data is valid SpotPriceMarketData.\n */\nfunction isValidMarketData(data: unknown): data is SpotPriceMarketData {\n return (\n typeof data === 'object' &&\n data !== null &&\n typeof (data as Record<string, unknown>).price === 'number'\n );\n}\n\n// ============================================================================\n// PRICE DATA SOURCE\n// ============================================================================\n\n/**\n * PriceDataSource fetches asset prices from the Price API.\n *\n * This data source:\n * - Fetches prices from Price API v3 spot-prices endpoint\n * - Supports one-time fetch and subscription-based polling\n * - In subscribe mode, uses constructor `getAssetsState` to read assetsBalance and fetch prices\n *\n * Usage: Create with queryApiClient and getAssetsState; subscribe() polls prices for held assets.\n */\nexport class PriceDataSource {\n static readonly controllerName = CONTROLLER_NAME;\n\n getName(): string {\n return PriceDataSource.controllerName;\n }\n\n readonly #getSelectedCurrency: () => SupportedCurrency;\n\n readonly #pollInterval: number;\n\n /** ApiPlatformClient for cached API calls */\n readonly #apiClient: ApiPlatformClient;\n\n readonly #fetchTimeoutMs: number;\n\n /**\n * Deduplicates price fetches by asset ID: skips assets fetched within the\n * freshness TTL and joins concurrent in-flight fetches for the same asset so\n * overlapping triggers (middleware + subscription poll) don't issue duplicate\n * API requests.\n */\n readonly #deduper: DedupingBatchFetcher<Caip19AssetId, FungibleAssetPrice>;\n\n readonly #getAssetsState: () => AssetsControllerState;\n\n /** Active subscriptions by ID */\n readonly #activeSubscriptions: Map<\n string,\n {\n cleanup: () => void;\n request: DataRequest;\n onAssetsUpdate: (response: DataResponse) => void | Promise<void>;\n }\n > = new Map();\n\n constructor(options: PriceDataSourceOptions) {\n this.#getSelectedCurrency = options.getSelectedCurrency;\n this.#pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL;\n this.#apiClient = options.queryApiClient;\n this.#fetchTimeoutMs = options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;\n this.#getAssetsState = options.getAssetsState;\n this.#deduper = new DedupingBatchFetcher({\n fetchBatch: (\n assetIds,\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> =>\n this.#executeBatchFetch(assetIds),\n freshnessTtlMs: options.priceFreshnessTtlMs ?? this.#pollInterval,\n });\n }\n\n // ============================================================================\n // MIDDLEWARE\n // ============================================================================\n\n /**\n * Get the middleware for enriching responses with price data.\n *\n * This middleware:\n * 1. Selects response balances that still need a price.\n * {@link getUnpricedResponseAssetIds} skips hidden, non-priceable, and\n * already-priced assets, and assets on chains the Price API does not support\n * 2. Fetches those prices. A price asked for within the freshness window is\n * skipped, unless the request forces an update\n * 3. Merges fetched prices into the response and continues the chain. A\n * failed fetch leaves the response balances unchanged\n *\n * @returns The middleware function for the assets pipeline.\n */\n get assetsMiddleware(): Middleware {\n return forDataTypes(['price'], async (ctx, next) => {\n const { response, request } = ctx;\n const unpricedAssetIds = await getUnpricedResponseAssetIds({\n state: this.#getAssetsState(),\n response,\n getSupportedNetworks: () => this.#getSupportedNetworks(),\n });\n if (unpricedAssetIds.length === 0) {\n return next(ctx);\n }\n\n if (request.forceUpdate) {\n this.#deduper.invalidateKeys(unpricedAssetIds);\n }\n\n try {\n const spotPrices = await this.#fetchSpotPrices(unpricedAssetIds);\n response.assetsPrice = {\n ...(response.assetsPrice ?? {}),\n ...spotPrices,\n };\n } catch (error) {\n log('Failed to fetch prices via middleware', { error });\n }\n\n // Call next() at the end to continue the middleware chain\n return next(ctx);\n });\n }\n\n /**\n * Fetch spot prices for an explicit asset list, bypassing the freshness cache.\n *\n * @param assetIds - CAIP-19 asset IDs to price.\n * @returns Prices keyed by asset ID. Empty when none are priceable or supported.\n */\n async fetchAssetPrices(\n assetIds: Caip19AssetId[],\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> {\n const supportedAssetIds =\n await this.#filterToSupportedPriceableAssets(assetIds);\n if (supportedAssetIds.length === 0) {\n return {};\n }\n\n this.#deduper.invalidateKeys(supportedAssetIds);\n return this.#fetchSpotPrices(supportedAssetIds);\n }\n\n // ============================================================================\n // HELPERS\n // ============================================================================\n\n /**\n * Fetch spot prices for a single batch of asset IDs (must be ≤ PRICE_API_BATCH_SIZE).\n *\n * @param assetIds - Array of CAIP-19 asset IDs (already within batch size limit).\n * @param selectedCurrency - The user's selected display currency.\n * @returns Raw spot-prices responses for the selected currency and USD.\n */\n async #fetchSpotPricesBatch(\n assetIds: string[],\n selectedCurrency: SupportedCurrency,\n ): Promise<{\n selectedCurrencyPrices: V3SpotPricesResponse;\n usdPrices: V3SpotPricesResponse;\n }> {\n if (selectedCurrency === 'usd') {\n const selectedCurrencyPrices = await fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: selectedCurrency,\n includeMarketData: true,\n }),\n this.#fetchTimeoutMs,\n );\n return { selectedCurrencyPrices, usdPrices: selectedCurrencyPrices };\n }\n\n const [selectedCurrencyPrices, usdPrices] = await Promise.all([\n fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: selectedCurrency,\n includeMarketData: true,\n }),\n this.#fetchTimeoutMs,\n ),\n fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: 'usd',\n includeMarketData: true,\n }),\n this.#fetchTimeoutMs,\n ),\n ]);\n\n return { selectedCurrencyPrices, usdPrices };\n }\n\n /**\n * Execute the actual batched API call for a set of asset IDs and return\n * parsed price results. Used as the `fetchBatch` callback for the deduper,\n * so it does NOT check freshness or inflight state — that is handled by\n * {@link DedupingBatchFetcher}.\n *\n * @param assetIds - Asset IDs to fetch (already filtered/deduplicated).\n * @returns Parsed prices keyed by CAIP-19 asset ID.\n */\n async #executeBatchFetch(\n assetIds: Caip19AssetId[],\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> {\n const selectedCurrency = this.#getSelectedCurrency();\n\n type BatchResult = {\n selectedCurrencyPrices: V3SpotPricesResponse;\n usdPrices: V3SpotPricesResponse;\n };\n\n const batchResults = await reduceInBatchesSerially<string, BatchResult[]>({\n values: assetIds,\n batchSize: PRICE_API_BATCH_SIZE,\n eachBatch: async (workingResult, batch) => {\n const result = await this.#fetchSpotPricesBatch(\n batch,\n selectedCurrency,\n );\n return [...(workingResult as BatchResult[]), result];\n },\n initialResult: [],\n });\n\n const fetchedAt = Date.now();\n const prices: Record<Caip19AssetId, FungibleAssetPrice> = {};\n\n for (const { selectedCurrencyPrices, usdPrices } of batchResults) {\n for (const [assetId, marketData] of Object.entries(\n selectedCurrencyPrices,\n )) {\n const usdMarketData = usdPrices[assetId];\n\n if (\n !isValidMarketData(marketData) ||\n !isValidMarketData(usdMarketData)\n ) {\n continue;\n }\n\n prices[assetId as Caip19AssetId] = {\n ...marketData,\n assetPriceType: 'fungible',\n usdPrice: usdMarketData.price,\n lastUpdated: fetchedAt,\n };\n }\n }\n\n return prices;\n }\n\n /**\n * Fetch spot prices for all provided asset IDs, deduplicating via the\n * deduper (freshness TTL + per-asset inflight coalescing).\n *\n * @param assetIds - Array of CAIP-19 asset IDs.\n * @returns Spot prices response (only contains entries for assets that were\n * actually fetched or joined from inflight).\n */\n async #fetchSpotPrices(\n assetIds: Caip19AssetId[],\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> {\n return this.#deduper.fetch(assetIds);\n }\n\n /**\n * Get unique asset IDs from the assetsBalance state.\n * Filters by accounts and chains from the request.\n *\n * @param request - Data request with accounts and chainIds filters.\n * @returns Array of CAIP-19 asset IDs from balance state.\n */\n #getAssetIdsFromBalanceState(request: DataRequest): Caip19AssetId[] {\n try {\n return [\n ...getAssetIdsForPriceFetch({\n state: this.#getAssetsState(),\n request,\n }),\n ];\n } catch (error) {\n log('Failed to get asset IDs from balance state', { error });\n return [];\n }\n }\n\n /**\n * Drop non-priceable assets, then assets on chains the price API does not\n * support. An empty supported-network set keeps every priceable asset.\n *\n * @param assetIds - Candidate CAIP-19 asset IDs.\n * @returns Priceable IDs on a supported chain.\n */\n async #filterToSupportedPriceableAssets(\n assetIds: Caip19AssetId[],\n ): Promise<Caip19AssetId[]> {\n const priceableAssetIds = assetIds.filter(isPriceableAsset);\n if (priceableAssetIds.length === 0) {\n return [];\n }\n\n const supportedNetworks = await this.#getSupportedNetworks();\n return this.#filterAssetsByNetwork(priceableAssetIds, supportedNetworks);\n }\n\n /**\n * Price API networks supported by the v3 spot-prices endpoint\n * (`fullSupport` plus `partialSupport.spotPricesV3`).\n *\n * @returns CAIP-2 chain IDs; empty on error.\n */\n async #getSupportedNetworks(): Promise<Set<string>> {\n try {\n const response = await fetchWithTimeout(\n (): Promise<PriceV2SupportedNetworksResponse> =>\n this.#apiClient.prices.fetchPriceV2SupportedNetworks(),\n this.#fetchTimeoutMs,\n );\n\n return getV3SpotPriceSupportedChainIds(response);\n } catch (error) {\n log('Failed to fetch price supported networks', { error });\n return new Set();\n }\n }\n\n /**\n * Keeps asset IDs whose chain is in `supportedNetworks`.\n *\n * @param assetIds - CAIP-19 asset IDs.\n * @param supportedNetworks - Supported CAIP-2 chain IDs.\n * @returns Matching IDs, or all IDs if the set is empty.\n */\n #filterAssetsByNetwork(\n assetIds: Caip19AssetId[],\n supportedNetworks: Set<string>,\n ): Caip19AssetId[] {\n return filterAssetsBySupportedNetworks(assetIds, supportedNetworks);\n }\n\n // ============================================================================\n // FETCH\n // ============================================================================\n\n /**\n * Fetch prices for visible assets on the accounts and chains in the request:\n * saved balances and custom assets. Metadata with no balance is skipped.\n * Unlike the middleware, this includes assets that already have a stored\n * price so the poll can refresh them. The freshness cache skips recent ones.\n *\n * @param request - The data request specifying accounts and chains.\n * @returns DataResponse containing asset prices.\n */\n async fetch(request: DataRequest): Promise<DataResponse> {\n const response: DataResponse = {};\n\n const assetIds = await this.#filterToSupportedPriceableAssets(\n this.#getAssetIdsFromBalanceState(request),\n );\n if (assetIds.length === 0) {\n return response;\n }\n\n try {\n const spotPrices = await this.#fetchSpotPrices(assetIds);\n\n response.assetsPrice = {\n ...(response.assetsPrice ?? {}),\n ...spotPrices,\n };\n } catch (error) {\n log('Failed to fetch prices', { error });\n }\n\n return response;\n }\n\n // ============================================================================\n // SUBSCRIBE\n // ============================================================================\n\n /**\n * Subscribe to price updates.\n * Sets up polling that fetches prices for all assets in assetsBalance state.\n *\n * @param subscriptionRequest - The subscription request configuration.\n */\n async subscribe(subscriptionRequest: SubscriptionRequest): Promise<void> {\n const { request, subscriptionId, isUpdate } = subscriptionRequest;\n\n // Handle subscription update: refresh request and fetch immediately so\n // newly held / still-unpriced assets (e.g. seeded natives) do not wait\n // for the next poll tick. Deduper freshness TTL skips recently priced IDs.\n if (isUpdate) {\n const existing = this.#activeSubscriptions.get(subscriptionId);\n if (existing) {\n existing.request = request;\n existing.onAssetsUpdate = subscriptionRequest.onAssetsUpdate;\n\n try {\n const fetchResponse = await this.fetch(request);\n if (\n fetchResponse.assetsPrice &&\n Object.keys(fetchResponse.assetsPrice).length > 0\n ) {\n await existing.onAssetsUpdate({\n ...fetchResponse,\n updateMode: 'merge',\n });\n }\n } catch (error) {\n log('Subscription update fetch failed', { subscriptionId, error });\n }\n return;\n }\n }\n\n // Clean up existing subscription\n await this.unsubscribe(subscriptionId);\n\n const pollInterval = request.updateInterval ?? this.#pollInterval;\n\n // Cap the freshness TTL strictly below the effective poll interval.\n // `fetchedAt` is stamped when a fetch completes (slightly after the tick\n // that triggered it), so a TTL equal to the poll interval would leave the\n // asset still \"fresh\" at the next tick, making the subscription re-fetch\n // only every other poll. The margin also absorbs network latency / jitter.\n this.#deduper.freshnessTtlMs = Math.min(\n this.#deduper.freshnessTtlMs,\n Math.floor(pollInterval * FRESHNESS_TTL_POLL_RATIO),\n );\n\n // Create poll function - fetches prices using constructor getAssetsState.\n // The freshness TTL naturally gates re-fetches: assets fetched less than\n // `priceFreshnessTtlMs` ago are skipped, preventing duplicates when middleware\n // or other triggers already fetched the same assets between polls.\n // Concurrent middleware calls will join the inflight promise rather than\n // issuing duplicate requests.\n const pollFn = async (): Promise<void> => {\n try {\n const subscription = this.#activeSubscriptions.get(subscriptionId);\n if (!subscription) {\n return;\n }\n\n const fetchResponse = await this.fetch(subscription.request);\n\n // Only report if we got prices\n if (\n fetchResponse.assetsPrice &&\n Object.keys(fetchResponse.assetsPrice).length > 0\n ) {\n await subscription.onAssetsUpdate({\n ...fetchResponse,\n // merge overwrites existing spot prices on each poll; update would\n // seed-only and leave the first price forever.\n updateMode: 'merge',\n });\n }\n } catch (error) {\n log('Subscription poll failed', { subscriptionId, error });\n }\n };\n\n // Set up polling\n const timer = setInterval(() => {\n pollFn().catch(console.error);\n }, pollInterval);\n\n // Store subscription\n this.#activeSubscriptions.set(subscriptionId, {\n cleanup: () => {\n clearInterval(timer);\n },\n request,\n onAssetsUpdate: subscriptionRequest.onAssetsUpdate,\n });\n\n // Initial fetch\n await pollFn();\n }\n\n /**\n * Unsubscribe from price updates.\n *\n * @param subscriptionId - The ID of the subscription to cancel.\n */\n async unsubscribe(subscriptionId: string): Promise<void> {\n const subscription = this.#activeSubscriptions.get(subscriptionId);\n if (subscription) {\n subscription.cleanup();\n this.#activeSubscriptions.delete(subscriptionId);\n }\n }\n\n /**\n * Invalidate the price freshness cache, forcing the next fetch to call the\n * API regardless of TTL. Use when external state changes (e.g. selected\n * currency) require a full refresh.\n */\n invalidatePriceCache(): void {\n this.#deduper.invalidate();\n }\n\n /**\n * Destroy the data source and clean up all subscriptions.\n */\n destroy(): void {\n for (const subscription of this.#activeSubscriptions.values()) {\n subscription.cleanup();\n }\n this.#activeSubscriptions.clear();\n this.#deduper.destroy();\n }\n}\n"]}
1
+ {"version":3,"file":"PriceDataSource.js","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAS3C,OAAO,EAAE,oBAAoB,EAAE,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IAAI,CAAC,qBAAqB,EAAE,CAAC;QACrC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,CAAC,0BAA0B,EAAE,EAAE,cAAc,EAAE,KAAK,EAAE,CAAC,CAAC;QAC7D,CAAC;IACH,CAAC;IAED,KAAK,CAAC,qBAAqB;QACzB,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAiB,CAAC;QAC1C,KAAK,MAAM,YAAY,IAAI,IAAI,CAAC,oBAAoB,CAAC,MAAM,EAAE,EAAE,CAAC;YAC9D,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,iCAAiC,CACtD,IAAI,CAAC,4BAA4B,CAAC,YAAY,CAAC,OAAO,CAAC,CACxD,CAAC;YACF,KAAK,MAAM,OAAO,IAAI,GAAG,EAAE,CAAC;gBAC1B,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;YACxB,CAAC;QACH,CAAC;QAED,MAAM,IAAI,CAAC,YAAY,CAAC,SAAS,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;IACxE,CAAC;IAED,cAAc,CAAC,QAAyB;QACtC,MAAM,MAAM,GAAG,IAAI,CAAC,eAAe,EAAE,CAAC,WAAW,IAAI,EAAE,CAAC;QACxD,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;YAChC,OAAO;YACP,UAAU,EACR,MAAM,CAAC,OAAO,CAAC,KAAK,SAAS;gBAC7B,8BAA8B,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;SAClD,CAAC,CAAC,CAAC;IACN,CAAC;CACF","sourcesContent":["import type {\n PriceV2SupportedNetworksResponse,\n SupportedCurrency,\n V3SpotPricesResponse,\n} from '@metamask/core-backend';\nimport { ApiPlatformClient } from '@metamask/core-backend';\n\nimport { projectLogger, createModuleLogger } from '../logger.js';\nimport { forDataTypes } from '../types.js';\nimport type {\n Caip19AssetId,\n DataRequest,\n DataResponse,\n FungibleAssetPrice,\n Middleware,\n AssetsControllerState,\n} from '../types.js';\nimport { DedupingBatchFetcher } from '../utils/dedupingBatchFetcher.js';\nimport {\n filterAssetsBySupportedNetworks,\n getAssetIdsForPriceFetch,\n getUnpricedResponseAssetIds,\n isPriceableAsset,\n} from '../utils/getAssetIdsForPriceFetch.js';\nimport { fetchWithTimeout } from '../utils/index.js';\nimport type { SubscriptionRequest } from './AbstractDataSource.js';\nimport { reduceInBatchesSerially } from './evm-rpc-services/index.js';\nimport type {\n MarketStatsPriceStreamMessenger,\n StreamCandidate,\n} from './MarketStatsPriceStream.js';\nimport {\n MarketStatsPriceStream,\n readSpotPriceStreamEligibility,\n} from './MarketStatsPriceStream.js';\n\n// ============================================================================\n// CONSTANTS\n// ============================================================================\n\nconst CONTROLLER_NAME = 'PriceDataSource';\nconst DEFAULT_POLL_INTERVAL = 60_000; // 1 minute for price updates\nconst DEFAULT_FETCH_TIMEOUT_MS = 15_000;\n\n/**\n * Fraction of the poll interval used to cap the freshness TTL. Kept strictly\n * below 1 so an asset fetched on one poll is reliably stale by the next poll;\n * the margin absorbs network latency and timer jitter (see the cap in\n * `subscribe`).\n */\nconst FRESHNESS_TTL_POLL_RATIO = 0.9;\n\n/** Maximum number of asset IDs per Price API request. */\nconst PRICE_API_BATCH_SIZE = 50;\n\nconst log = createModuleLogger(projectLogger, CONTROLLER_NAME);\n\n// ============================================================================\n// HELPERS\n// ============================================================================\n\n/**\n * Extracts the CAIP-2 chain IDs the Price API v3 spot-prices endpoint\n * supports from a `/v2/supportedNetworks` response.\n *\n * The endpoint returns `partialSupport` as an object keyed by spot-price\n * endpoint (`{ spotPricesV2, spotPricesV3 }`). Since this data source only\n * calls `/v3/spot-prices`, only `spotPricesV3` is relevant. A legacy\n * array-shaped `partialSupport` is still accepted so a transient schema\n * change does not disable price fetching.\n *\n * @param response - The supported networks response.\n * @param response.fullSupport - Chains supported by every endpoint.\n * @param response.partialSupport - Chains supported by specific endpoints.\n * @returns Unique CAIP-2 chain IDs supported by v3 spot prices.\n */\nfunction getV3SpotPriceSupportedChainIds(response: {\n fullSupport?: string[];\n partialSupport?:\n | string[]\n | Partial<PriceV2SupportedNetworksResponse['partialSupport']>;\n}): Set<string> {\n const { fullSupport, partialSupport } = response;\n const partial = Array.isArray(partialSupport)\n ? partialSupport\n : (partialSupport?.spotPricesV3 ?? []);\n return new Set([...(fullSupport ?? []), ...partial]);\n}\n\n// ============================================================================\n// OPTIONS\n// ============================================================================\n\n/** Optional configuration for PriceDataSource. */\nexport type PriceDataSourceConfig = {\n /** Polling interval in ms (default: 60000) */\n pollInterval?: number;\n /**\n * Timeout in ms for a single Price API call (default: 15000). When it fires,\n * the batch rejects so the caller can proceed without prices.\n */\n fetchTimeoutMs?: number;\n /**\n * Minimum age (ms) before a price is considered stale and re-fetched.\n * Assets fetched more recently than this are skipped to avoid redundant\n * API calls from overlapping middleware / subscription / manual triggers.\n * Defaults to pollInterval (60 000 ms).\n */\n priceFreshnessTtlMs?: number;\n};\n\nexport type { MarketStatsPriceStreamMessenger } from './MarketStatsPriceStream.js';\n\nexport type PriceDataSourceOptions = PriceDataSourceConfig & {\n /** ApiPlatformClient for API calls with caching */\n queryApiClient: ApiPlatformClient;\n /** Function returning the currently-active ISO 4217 currency code */\n getSelectedCurrency: () => SupportedCurrency;\n /** Current AssetsController state. Used for balance-based pricing and freshness checks. */\n getAssetsState: () => AssetsControllerState;\n /**\n * Messenger that can call MarketStatsService. When the service is registered,\n * assets with `wssSupport` stream as well as polling. When it is not\n * registered, every asset stays on the poll.\n */\n messenger: MarketStatsPriceStreamMessenger;\n};\n\n// ============================================================================\n// HELPER FUNCTIONS\n// ============================================================================\n\n/**\n * Asset reference patterns that should NOT be sent to the Price API.\n * These are internal resource tracking values without market prices.\n */\nexport { isPriceableAsset } from '../utils/getAssetIdsForPriceFetch.js';\n\n/** Market data item from spot prices response (same as FungibleAssetPrice without lastUpdated) */\ntype SpotPriceMarketData = Omit<\n FungibleAssetPrice,\n 'lastUpdated' | 'assetPriceType'\n>;\n\n/**\n * Type guard to check if market data has a valid price\n *\n * @param data - The data to check.\n * @returns True if data is valid SpotPriceMarketData.\n */\nfunction isValidMarketData(data: unknown): data is SpotPriceMarketData {\n return (\n typeof data === 'object' &&\n data !== null &&\n typeof (data as Record<string, unknown>).price === 'number'\n );\n}\n\n// ============================================================================\n// PRICE DATA SOURCE\n// ============================================================================\n\n/**\n * PriceDataSource fetches asset prices from the Price API.\n *\n * This data source:\n * - Fetches prices from Price API v3 spot-prices endpoint\n * - Supports one-time fetch and subscription-based polling\n * - In subscribe mode, uses constructor `getAssetsState` to read assetsBalance and fetch prices\n * - Streams the same assets the price poll tracks, when the spot-price\n * response marks them `wssSupport: true`, on market-stats.v1. The poll\n * itself is the same as before: every tracked asset, on the same interval.\n * Socket ticks are not written into controller state. The UI reads\n * `MarketStatsService:pricesUpdated`.\n *\n * Usage: Create with queryApiClient, messenger, and getAssetsState; subscribe() polls prices for held assets.\n */\nexport class PriceDataSource {\n static readonly controllerName = CONTROLLER_NAME;\n\n getName(): string {\n return PriceDataSource.controllerName;\n }\n\n readonly #getSelectedCurrency: () => SupportedCurrency;\n\n readonly #pollInterval: number;\n\n /** ApiPlatformClient for cached API calls */\n readonly #apiClient: ApiPlatformClient;\n\n readonly #fetchTimeoutMs: number;\n\n /**\n * Deduplicates price fetches by asset ID: skips assets fetched within the\n * freshness TTL and joins concurrent in-flight fetches for the same asset so\n * overlapping triggers (middleware + subscription poll) don't issue duplicate\n * API requests.\n */\n readonly #deduper: DedupingBatchFetcher<Caip19AssetId, FungibleAssetPrice>;\n\n readonly #getAssetsState: () => AssetsControllerState;\n\n readonly #marketStats: MarketStatsPriceStream;\n\n /** Active subscriptions by ID */\n readonly #activeSubscriptions: Map<\n string,\n {\n cleanup: () => void;\n request: DataRequest;\n onAssetsUpdate: (response: DataResponse) => void | Promise<void>;\n }\n > = new Map();\n\n constructor(options: PriceDataSourceOptions) {\n this.#getSelectedCurrency = options.getSelectedCurrency;\n this.#pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL;\n this.#apiClient = options.queryApiClient;\n this.#fetchTimeoutMs = options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;\n this.#getAssetsState = options.getAssetsState;\n this.#marketStats = new MarketStatsPriceStream({\n messenger: options.messenger,\n getSelectedCurrency: (): SupportedCurrency => this.#getSelectedCurrency(),\n });\n this.#deduper = new DedupingBatchFetcher({\n fetchBatch: (\n assetIds,\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> =>\n this.#executeBatchFetch(assetIds),\n freshnessTtlMs: options.priceFreshnessTtlMs ?? this.#pollInterval,\n });\n }\n\n // ============================================================================\n // MIDDLEWARE\n // ============================================================================\n\n /**\n * Get the middleware for enriching responses with price data.\n *\n * This middleware:\n * 1. Selects response balances that still need a price.\n * {@link getUnpricedResponseAssetIds} skips hidden, non-priceable, and\n * already-priced assets, and assets on chains the Price API does not support\n * 2. Fetches those prices. A price asked for within the freshness window is\n * skipped, unless the request forces an update\n * 3. Merges fetched prices into the response and continues the chain. A\n * failed fetch leaves the response balances unchanged\n *\n * @returns The middleware function for the assets pipeline.\n */\n get assetsMiddleware(): Middleware {\n return forDataTypes(['price'], async (ctx, next) => {\n const { response, request } = ctx;\n const unpricedAssetIds = await getUnpricedResponseAssetIds({\n state: this.#getAssetsState(),\n response,\n getSupportedNetworks: () => this.#getSupportedNetworks(),\n });\n if (unpricedAssetIds.length === 0) {\n return next(ctx);\n }\n\n if (request.forceUpdate) {\n this.#deduper.invalidateKeys(unpricedAssetIds);\n }\n\n try {\n const spotPrices = await this.#fetchSpotPrices(unpricedAssetIds);\n response.assetsPrice = {\n ...(response.assetsPrice ?? {}),\n ...spotPrices,\n };\n } catch (error) {\n log('Failed to fetch prices via middleware', { error });\n }\n\n // Call next() at the end to continue the middleware chain\n return next(ctx);\n });\n }\n\n /**\n * Fetch spot prices for an explicit asset list, bypassing the freshness cache.\n *\n * @param assetIds - CAIP-19 asset IDs to price.\n * @returns Prices keyed by asset ID. Empty when none are priceable or supported.\n */\n async fetchAssetPrices(\n assetIds: Caip19AssetId[],\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> {\n const supportedAssetIds =\n await this.#filterToSupportedPriceableAssets(assetIds);\n if (supportedAssetIds.length === 0) {\n return {};\n }\n\n this.#deduper.invalidateKeys(supportedAssetIds);\n return this.#fetchSpotPrices(supportedAssetIds);\n }\n\n // ============================================================================\n // HELPERS\n // ============================================================================\n\n /**\n * Fetch spot prices for a single batch of asset IDs (must be ≤ PRICE_API_BATCH_SIZE).\n *\n * @param assetIds - Array of CAIP-19 asset IDs (already within batch size limit).\n * @param selectedCurrency - The user's selected display currency.\n * @returns Raw spot-prices responses for the selected currency and USD.\n */\n async #fetchSpotPricesBatch(\n assetIds: string[],\n selectedCurrency: SupportedCurrency,\n ): Promise<{\n selectedCurrencyPrices: V3SpotPricesResponse;\n usdPrices: V3SpotPricesResponse;\n }> {\n if (selectedCurrency === 'usd') {\n const selectedCurrencyPrices = await fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: selectedCurrency,\n includeMarketData: true,\n includeWssSupportField: true,\n }),\n this.#fetchTimeoutMs,\n );\n return { selectedCurrencyPrices, usdPrices: selectedCurrencyPrices };\n }\n\n const [selectedCurrencyPrices, usdPrices] = await Promise.all([\n fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: selectedCurrency,\n includeMarketData: true,\n includeWssSupportField: true,\n }),\n this.#fetchTimeoutMs,\n ),\n fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: 'usd',\n includeMarketData: true,\n includeWssSupportField: true,\n }),\n this.#fetchTimeoutMs,\n ),\n ]);\n\n return { selectedCurrencyPrices, usdPrices };\n }\n\n /**\n * Execute the actual batched API call for a set of asset IDs and return\n * parsed price results. Used as the `fetchBatch` callback for the deduper,\n * so it does NOT check freshness or inflight state — that is handled by\n * {@link DedupingBatchFetcher}.\n *\n * @param assetIds - Asset IDs to fetch (already filtered/deduplicated).\n * @returns Parsed prices keyed by CAIP-19 asset ID.\n */\n async #executeBatchFetch(\n assetIds: Caip19AssetId[],\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> {\n const selectedCurrency = this.#getSelectedCurrency();\n\n type BatchResult = {\n selectedCurrencyPrices: V3SpotPricesResponse;\n usdPrices: V3SpotPricesResponse;\n };\n\n const batchResults = await reduceInBatchesSerially<string, BatchResult[]>({\n values: assetIds,\n batchSize: PRICE_API_BATCH_SIZE,\n eachBatch: async (workingResult, batch) => {\n const result = await this.#fetchSpotPricesBatch(\n batch,\n selectedCurrency,\n );\n return [...(workingResult as BatchResult[]), result];\n },\n initialResult: [],\n });\n\n const fetchedAt = Date.now();\n const prices: Record<Caip19AssetId, FungibleAssetPrice> = {};\n\n for (const { selectedCurrencyPrices, usdPrices } of batchResults) {\n for (const [assetId, marketData] of Object.entries(\n selectedCurrencyPrices,\n )) {\n const usdMarketData = usdPrices[assetId];\n\n if (\n !isValidMarketData(marketData) ||\n !isValidMarketData(usdMarketData)\n ) {\n continue;\n }\n\n prices[assetId as Caip19AssetId] = {\n ...marketData,\n assetPriceType: 'fungible',\n usdPrice: usdMarketData.price,\n lastUpdated: fetchedAt,\n };\n }\n }\n\n return prices;\n }\n\n /**\n * Fetch spot prices for all provided asset IDs, deduplicating via the\n * deduper (freshness TTL + per-asset inflight coalescing).\n *\n * @param assetIds - Array of CAIP-19 asset IDs.\n * @returns Spot prices response (only contains entries for assets that were\n * actually fetched or joined from inflight).\n */\n async #fetchSpotPrices(\n assetIds: Caip19AssetId[],\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> {\n return this.#deduper.fetch(assetIds);\n }\n\n /**\n * Get unique asset IDs from the assetsBalance state.\n * Filters by accounts and chains from the request.\n *\n * @param request - Data request with accounts and chainIds filters.\n * @returns Array of CAIP-19 asset IDs from balance state.\n */\n #getAssetIdsFromBalanceState(request: DataRequest): Caip19AssetId[] {\n try {\n return [\n ...getAssetIdsForPriceFetch({\n state: this.#getAssetsState(),\n request,\n }),\n ];\n } catch (error) {\n log('Failed to get asset IDs from balance state', { error });\n return [];\n }\n }\n\n /**\n * Drop non-priceable assets, then assets on chains the price API does not\n * support. An empty supported-network set keeps every priceable asset.\n *\n * @param assetIds - Candidate CAIP-19 asset IDs.\n * @returns Priceable IDs on a supported chain.\n */\n async #filterToSupportedPriceableAssets(\n assetIds: Caip19AssetId[],\n ): Promise<Caip19AssetId[]> {\n const priceableAssetIds = assetIds.filter(isPriceableAsset);\n if (priceableAssetIds.length === 0) {\n return [];\n }\n\n const supportedNetworks = await this.#getSupportedNetworks();\n return this.#filterAssetsByNetwork(priceableAssetIds, supportedNetworks);\n }\n\n /**\n * Price API networks supported by the v3 spot-prices endpoint\n * (`fullSupport` plus `partialSupport.spotPricesV3`).\n *\n * @returns CAIP-2 chain IDs; empty on error.\n */\n async #getSupportedNetworks(): Promise<Set<string>> {\n try {\n const response = await fetchWithTimeout(\n (): Promise<PriceV2SupportedNetworksResponse> =>\n this.#apiClient.prices.fetchPriceV2SupportedNetworks(),\n this.#fetchTimeoutMs,\n );\n\n return getV3SpotPriceSupportedChainIds(response);\n } catch (error) {\n log('Failed to fetch price supported networks', { error });\n return new Set();\n }\n }\n\n /**\n * Keeps asset IDs whose chain is in `supportedNetworks`.\n *\n * @param assetIds - CAIP-19 asset IDs.\n * @param supportedNetworks - Supported CAIP-2 chain IDs.\n * @returns Matching IDs, or all IDs if the set is empty.\n */\n #filterAssetsByNetwork(\n assetIds: Caip19AssetId[],\n supportedNetworks: Set<string>,\n ): Caip19AssetId[] {\n return filterAssetsBySupportedNetworks(assetIds, supportedNetworks);\n }\n\n // ============================================================================\n // FETCH\n // ============================================================================\n\n /**\n * Fetch prices for visible assets on the accounts and chains in the request:\n * saved balances and custom assets. Metadata with no balance is skipped.\n * Unlike the middleware, this includes assets that already have a stored\n * price so the poll can refresh them. The freshness cache skips recent ones.\n *\n * @param request - The data request specifying accounts and chains.\n * @returns DataResponse containing asset prices.\n */\n async fetch(request: DataRequest): Promise<DataResponse> {\n const assetIds = await this.#filterToSupportedPriceableAssets(\n this.#getAssetIdsFromBalanceState(request),\n );\n return this.#fetchAssetIdList(assetIds);\n }\n\n /**\n * Fetch spot prices for an explicit id list. Empty when there is nothing to\n * price or the Price API call fails.\n *\n * @param assetIds - CAIP-19 asset IDs already filtered to priceable assets.\n * @returns DataResponse containing asset prices.\n */\n async #fetchAssetIdList(assetIds: Caip19AssetId[]): Promise<DataResponse> {\n const response: DataResponse = {};\n if (assetIds.length === 0) {\n return response;\n }\n\n try {\n const spotPrices = await this.#fetchSpotPrices(assetIds);\n response.assetsPrice = {\n ...(response.assetsPrice ?? {}),\n ...spotPrices,\n };\n } catch (error) {\n log('Failed to fetch prices', { error });\n }\n\n return response;\n }\n\n // ============================================================================\n // SUBSCRIBE\n // ============================================================================\n\n /**\n * Subscribe to price updates.\n * Polls the Price API, and streams assets that support market-stats.v1.\n *\n * @param subscriptionRequest - The subscription request configuration.\n */\n async subscribe(subscriptionRequest: SubscriptionRequest): Promise<void> {\n const { request, subscriptionId, isUpdate } = subscriptionRequest;\n\n // Handle subscription update: refresh request and fetch immediately so\n // newly held / still-unpriced assets (e.g. seeded natives) do not wait\n // for the next poll tick. Deduper freshness TTL skips recently priced IDs.\n if (isUpdate) {\n const existing = this.#activeSubscriptions.get(subscriptionId);\n if (existing) {\n existing.request = request;\n existing.onAssetsUpdate = subscriptionRequest.onAssetsUpdate;\n\n try {\n const fetchResponse = await this.fetch(request);\n if (\n fetchResponse.assetsPrice &&\n Object.keys(fetchResponse.assetsPrice).length > 0\n ) {\n await existing.onAssetsUpdate({\n ...fetchResponse,\n updateMode: 'merge',\n });\n }\n await this.#reconcileMarketStats();\n } catch (error) {\n log('Subscription update fetch failed', { subscriptionId, error });\n }\n return;\n }\n }\n\n // Clean up existing subscription\n await this.unsubscribe(subscriptionId);\n\n const pollInterval = request.updateInterval ?? this.#pollInterval;\n\n // Cap the freshness TTL strictly below the effective poll interval.\n // `fetchedAt` is stamped when a fetch completes (slightly after the tick\n // that triggered it), so a TTL equal to the poll interval would leave the\n // asset still \"fresh\" at the next tick, making the subscription re-fetch\n // only every other poll. The margin also absorbs network latency / jitter.\n this.#deduper.freshnessTtlMs = Math.min(\n this.#deduper.freshnessTtlMs,\n Math.floor(pollInterval * FRESHNESS_TTL_POLL_RATIO),\n );\n\n // Each tick prices every tracked asset, the same as the poll without\n // market stats. An open channel does not skip one.\n const timer = setInterval(() => {\n this.#runPoll(subscriptionId).catch((error: unknown) => {\n log('Subscription poll failed', { subscriptionId, error });\n });\n }, pollInterval);\n\n // Store subscription\n this.#activeSubscriptions.set(subscriptionId, {\n cleanup: () => {\n clearInterval(timer);\n },\n request,\n onAssetsUpdate: subscriptionRequest.onAssetsUpdate,\n });\n\n // Initial fetch\n await this.#runPoll(subscriptionId);\n }\n\n /**\n * Unsubscribe from price updates.\n *\n * @param subscriptionId - The ID of the subscription to cancel.\n */\n async unsubscribe(subscriptionId: string): Promise<void> {\n const subscription = this.#activeSubscriptions.get(subscriptionId);\n if (!subscription) {\n return;\n }\n\n subscription.cleanup();\n this.#activeSubscriptions.delete(subscriptionId);\n\n if (this.#activeSubscriptions.size === 0) {\n await this.#marketStats.releaseSubscriptions();\n return;\n }\n\n await this.#reconcileMarketStats();\n }\n\n /**\n * Drop market-stats channels and open them again for the current currency.\n * Called when the selected currency changes so batches match `assetsPrice`.\n */\n async resubscribeForCurrencyChange(): Promise<void> {\n if (this.#activeSubscriptions.size === 0) {\n return;\n }\n\n await this.#marketStats.releaseSubscriptions();\n await this.#reconcileMarketStats();\n }\n\n /**\n * Align market-stats channels with the price-fetch set and the `wssSupport`\n * already stored in `assetsPrice`.\n *\n * Called after the spot-price response is in `assetsPrice`. A balance\n * update reconciles from `AssetsController` once that write has landed.\n * The price poll reconciles at the end of its own tick.\n */\n async reconcileMarketStreams(): Promise<void> {\n if (this.#activeSubscriptions.size === 0) {\n return;\n }\n await this.#reconcileMarketStats();\n }\n\n /**\n * Invalidate the price freshness cache, forcing the next fetch to call the\n * API regardless of TTL. Use when external state changes (e.g. selected\n * currency) require a full refresh.\n */\n invalidatePriceCache(): void {\n this.#deduper.invalidate();\n }\n\n /**\n * Destroy the data source and clean up all subscriptions.\n */\n destroy(): void {\n for (const subscription of this.#activeSubscriptions.values()) {\n subscription.cleanup();\n }\n this.#activeSubscriptions.clear();\n this.#marketStats.destroy();\n this.#deduper.destroy();\n }\n\n /**\n * One poll tick: REST-fetch every tracked asset, then open market-stats\n * channels for assets the response marks `wssSupport`.\n *\n * @param subscriptionId - Active subscription to poll.\n */\n async #runPoll(subscriptionId: string): Promise<void> {\n const subscription = this.#activeSubscriptions.get(subscriptionId);\n if (!subscription) {\n return;\n }\n\n try {\n const fetchResponse = await this.fetch(subscription.request);\n if (\n fetchResponse.assetsPrice &&\n Object.keys(fetchResponse.assetsPrice).length > 0\n ) {\n await subscription.onAssetsUpdate({\n ...fetchResponse,\n updateMode: 'merge',\n });\n }\n\n await this.#reconcileMarketStats();\n } catch (error) {\n log('Subscription poll failed', { subscriptionId, error });\n }\n }\n\n async #reconcileMarketStats(): Promise<void> {\n const assetIds = new Set<Caip19AssetId>();\n for (const subscription of this.#activeSubscriptions.values()) {\n const ids = await this.#filterToSupportedPriceableAssets(\n this.#getAssetIdsFromBalanceState(subscription.request),\n );\n for (const assetId of ids) {\n assetIds.add(assetId);\n }\n }\n\n await this.#marketStats.reconcile(this.#candidatesFor([...assetIds]));\n }\n\n #candidatesFor(assetIds: Caip19AssetId[]): StreamCandidate[] {\n const prices = this.#getAssetsState().assetsPrice ?? {};\n return assetIds.map((assetId) => ({\n assetId,\n wssSupport:\n prices[assetId] !== undefined &&\n readSpotPriceStreamEligibility(prices[assetId]),\n }));\n }\n}\n"]}
@@ -3,7 +3,7 @@ export { AccountsApiDataSource, type AccountsApiDataSourceConfig, type AccountsA
3
3
  export { AccountActivityDataSource, createAccountActivityDataSource, type AccountActivityDataSourceOptions, type AccountActivityDataSourceState, type AccountActivityDataSourceAllowedEvents, } from './AccountActivityDataSource.js';
4
4
  export { RpcDataSource, createRpcDataSource, type RpcDataSourceConfig, type RpcDataSourceOptions, type RpcDataSourceState, type RpcDataSourceAllowedActions, type RpcDataSourceAllowedEvents, type ChainStatus, } from './RpcDataSource.js';
5
5
  export { TokenDataSource, type TokenDataSourceOptions, type TokenDataSourceAllowedActions, } from './TokenDataSource.js';
6
- export { PriceDataSource, type PriceDataSourceConfig, type PriceDataSourceOptions, } from './PriceDataSource.js';
6
+ export { PriceDataSource, type PriceDataSourceConfig, type PriceDataSourceOptions, type MarketStatsPriceStreamMessenger, } from './PriceDataSource.js';
7
7
  export { SnapDataSource, createSnapDataSource, SNAP_DATA_SOURCE_NAME, KEYRING_PERMISSION, getChainIdsCaveat, extractChainFromAssetId, type SnapDataSourceState, type SnapDataSourceOptions, type SnapDataSourceAllowedActions, type SnapDataSourceAllowedEvents, } from './SnapDataSource.js';
8
8
  export { StakedBalanceDataSource, type StakedBalanceDataSourceConfig, type StakedBalanceDataSourceOptions, } from './StakedBalanceDataSource.js';
9
9
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/data-sources/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,KAAK,eAAe,EACpB,KAAK,mBAAmB,GACzB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EACL,qBAAqB,EACrB,KAAK,2BAA2B,EAChC,KAAK,4BAA4B,EACjC,KAAK,0BAA0B,EAC/B,KAAK,mCAAmC,GACzC,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,yBAAyB,EACzB,+BAA+B,EAC/B,KAAK,gCAAgC,EACrC,KAAK,8BAA8B,EACnC,KAAK,sCAAsC,GAC5C,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,KAAK,2BAA2B,EAChC,KAAK,0BAA0B,EAC/B,KAAK,WAAW,GACjB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,eAAe,EACf,KAAK,sBAAsB,EAC3B,KAAK,6BAA6B,GACnC,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,eAAe,EACf,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,GAC5B,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,qBAAqB,EAErB,kBAAkB,EAElB,iBAAiB,EACjB,uBAAuB,EAEvB,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAC1B,KAAK,4BAA4B,EACjC,KAAK,2BAA2B,GACjC,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,uBAAuB,EACvB,KAAK,6BAA6B,EAClC,KAAK,8BAA8B,GACpC,MAAM,8BAA8B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/data-sources/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,KAAK,eAAe,EACpB,KAAK,mBAAmB,GACzB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EACL,qBAAqB,EACrB,KAAK,2BAA2B,EAChC,KAAK,4BAA4B,EACjC,KAAK,0BAA0B,EAC/B,KAAK,mCAAmC,GACzC,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,yBAAyB,EACzB,+BAA+B,EAC/B,KAAK,gCAAgC,EACrC,KAAK,8BAA8B,EACnC,KAAK,sCAAsC,GAC5C,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,KAAK,2BAA2B,EAChC,KAAK,0BAA0B,EAC/B,KAAK,WAAW,GACjB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,eAAe,EACf,KAAK,sBAAsB,EAC3B,KAAK,6BAA6B,GACnC,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,eAAe,EACf,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,EAC3B,KAAK,+BAA+B,GACrC,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,qBAAqB,EAErB,kBAAkB,EAElB,iBAAiB,EACjB,uBAAuB,EAEvB,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAC1B,KAAK,4BAA4B,EACjC,KAAK,2BAA2B,GACjC,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,uBAAuB,EACvB,KAAK,6BAA6B,EAClC,KAAK,8BAA8B,GACpC,MAAM,8BAA8B,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/data-sources/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,GAGnB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EACL,qBAAqB,GAKtB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,yBAAyB,EACzB,+BAA+B,GAIhC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,aAAa,EACb,mBAAmB,GAOpB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,eAAe,GAGhB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,eAAe,GAGhB,MAAM,sBAAsB,CAAC;AAE9B,0FAA0F;AAC1F,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,qBAAqB;AACrB,YAAY;AACZ,kBAAkB;AAClB,oBAAoB;AACpB,iBAAiB,EACjB,uBAAuB,GAMxB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,uBAAuB,GAGxB,MAAM,8BAA8B,CAAC","sourcesContent":["export {\n AbstractDataSource,\n type DataSourceState,\n type SubscriptionRequest,\n} from './AbstractDataSource.js';\n\nexport {\n AccountsApiDataSource,\n type AccountsApiDataSourceConfig,\n type AccountsApiDataSourceOptions,\n type AccountsApiDataSourceState,\n type AccountsApiDataSourceAllowedActions,\n} from './AccountsApiDataSource.js';\n\nexport {\n AccountActivityDataSource,\n createAccountActivityDataSource,\n type AccountActivityDataSourceOptions,\n type AccountActivityDataSourceState,\n type AccountActivityDataSourceAllowedEvents,\n} from './AccountActivityDataSource.js';\n\nexport {\n RpcDataSource,\n createRpcDataSource,\n type RpcDataSourceConfig,\n type RpcDataSourceOptions,\n type RpcDataSourceState,\n type RpcDataSourceAllowedActions,\n type RpcDataSourceAllowedEvents,\n type ChainStatus,\n} from './RpcDataSource.js';\n\nexport {\n TokenDataSource,\n type TokenDataSourceOptions,\n type TokenDataSourceAllowedActions,\n} from './TokenDataSource.js';\n\nexport {\n PriceDataSource,\n type PriceDataSourceConfig,\n type PriceDataSourceOptions,\n} from './PriceDataSource.js';\n\n// Unified Snap Data Source (dynamically discovers keyring snaps via PermissionController)\nexport {\n SnapDataSource,\n createSnapDataSource,\n SNAP_DATA_SOURCE_NAME,\n // Constants\n KEYRING_PERMISSION,\n // Utility functions\n getChainIdsCaveat,\n extractChainFromAssetId,\n // Types\n type SnapDataSourceState,\n type SnapDataSourceOptions,\n type SnapDataSourceAllowedActions,\n type SnapDataSourceAllowedEvents,\n} from './SnapDataSource.js';\n\nexport {\n StakedBalanceDataSource,\n type StakedBalanceDataSourceConfig,\n type StakedBalanceDataSourceOptions,\n} from './StakedBalanceDataSource.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/data-sources/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,GAGnB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EACL,qBAAqB,GAKtB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,yBAAyB,EACzB,+BAA+B,GAIhC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,aAAa,EACb,mBAAmB,GAOpB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,eAAe,GAGhB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,eAAe,GAIhB,MAAM,sBAAsB,CAAC;AAE9B,0FAA0F;AAC1F,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,qBAAqB;AACrB,YAAY;AACZ,kBAAkB;AAClB,oBAAoB;AACpB,iBAAiB,EACjB,uBAAuB,GAMxB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,uBAAuB,GAGxB,MAAM,8BAA8B,CAAC","sourcesContent":["export {\n AbstractDataSource,\n type DataSourceState,\n type SubscriptionRequest,\n} from './AbstractDataSource.js';\n\nexport {\n AccountsApiDataSource,\n type AccountsApiDataSourceConfig,\n type AccountsApiDataSourceOptions,\n type AccountsApiDataSourceState,\n type AccountsApiDataSourceAllowedActions,\n} from './AccountsApiDataSource.js';\n\nexport {\n AccountActivityDataSource,\n createAccountActivityDataSource,\n type AccountActivityDataSourceOptions,\n type AccountActivityDataSourceState,\n type AccountActivityDataSourceAllowedEvents,\n} from './AccountActivityDataSource.js';\n\nexport {\n RpcDataSource,\n createRpcDataSource,\n type RpcDataSourceConfig,\n type RpcDataSourceOptions,\n type RpcDataSourceState,\n type RpcDataSourceAllowedActions,\n type RpcDataSourceAllowedEvents,\n type ChainStatus,\n} from './RpcDataSource.js';\n\nexport {\n TokenDataSource,\n type TokenDataSourceOptions,\n type TokenDataSourceAllowedActions,\n} from './TokenDataSource.js';\n\nexport {\n PriceDataSource,\n type PriceDataSourceConfig,\n type PriceDataSourceOptions,\n type MarketStatsPriceStreamMessenger,\n} from './PriceDataSource.js';\n\n// Unified Snap Data Source (dynamically discovers keyring snaps via PermissionController)\nexport {\n SnapDataSource,\n createSnapDataSource,\n SNAP_DATA_SOURCE_NAME,\n // Constants\n KEYRING_PERMISSION,\n // Utility functions\n getChainIdsCaveat,\n extractChainFromAssetId,\n // Types\n type SnapDataSourceState,\n type SnapDataSourceOptions,\n type SnapDataSourceAllowedActions,\n type SnapDataSourceAllowedEvents,\n} from './SnapDataSource.js';\n\nexport {\n StakedBalanceDataSource,\n type StakedBalanceDataSourceConfig,\n type StakedBalanceDataSourceOptions,\n} from './StakedBalanceDataSource.js';\n"]}
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export { DEFAULT_TRACKED_ASSETS_BY_CHAIN, CHAINS_WITH_DEFAULT_TRACKED_ASSETS, DE
4
4
  export type { PendingTokenMetadata } from './AssetsController.js';
5
5
  export { SNAPS_ASSETS_MIGRATION_FLAG_KEYS, SNAPS_ASSETS_MIGRATION_NAMESPACES, SnapsAssetsMigrationStage, getSnapsAssetsMigrationNamespace, isMigrationStageActive, isSnapsAssetsMigrationNamespace, parseSnapsAssetsMigrationStage, } from './utils/snaps-assets-migration.js';
6
6
  export type { SnapsAssetsMigrationNamespace } from './utils/snaps-assets-migration.js';
7
- export type { AssetsControllerState, AssetsControllerMessenger, AssetsControllerOptions, AssetsControllerGetStateAction, AssetsControllerActions, AssetsControllerStateChangeEvent, AssetsControllerBalanceChangedEvent, AssetsControllerPriceChangedEvent, AssetsControllerEvents, } from './AssetsController.js';
7
+ export type { AssetsControllerState, AssetsControllerMessenger, AssetsControllerOptions, AssetsControllerGetStateAction, AssetsControllerActions, AssetsControllerStateChangeEvent, AssetsControllerBalanceChangedEvent, AssetsControllerEvents, } from './AssetsController.js';
8
8
  export type { AssetsControllerGetAssetsAction, AssetsControllerGetAssetsBalanceAction, AssetsControllerGetAssetMetadataAction, AssetsControllerGetAccountAssetByIDAction, AssetsControllerGetAccountAssetsByIDsAction, AssetsControllerGetAccountAssetsByScopeAction, AssetsControllerGetAssetsPriceAction, AssetsControllerSyncAssetsPricesAction, AssetsControllerAddCustomAssetAction, AssetsControllerRemoveCustomAssetAction, AssetsControllerGetCustomAssetsAction, AssetsControllerHideAssetAction, AssetsControllerUnhideAssetAction, AssetsControllerGetExchangeRatesForBridgeAction, AssetsControllerGetStateForTransactionPayAction, AssetsControllerSetSelectedCurrencyAction, } from './AssetsController-method-action-types.js';
9
9
  export type { Caip19AssetId, AccountId, ChainId, AssetType, TokenStandard, TokenFees, HoneypotStatus, StorageSlots, LocalizedDescription, BaseAssetMetadata, FungibleAssetMetadata, ERC721AssetMetadata, ERC1155AssetMetadata, AssetMetadata, BaseAssetPrice, FungibleAssetPrice, NFTAssetPrice, AssetPrice, FungibleAssetBalance, ERC721AssetBalance, ERC1155AssetBalance, AssetBalance, AccountWithSupportedChains, DataType, DataRequest, DataResponse, AssetsUpdateMode, AssetsLoadingStatus, Context, NextFunction, Middleware, AssetsDataSource, FetchContext, FetchNextFunction, FetchMiddleware, SubscriptionResponse, Asset, BalanceChangeEvent, PriceChangeEvent, MetadataChangeEvent, } from './types.js';
10
10
  export { AbstractDataSource } from './data-sources/index.js';
@@ -16,9 +16,11 @@ export type { RpcDataSourceConfig, RpcDataSourceOptions, RpcDataSourceState, Cha
16
16
  export { SnapDataSource, createSnapDataSource, SNAP_DATA_SOURCE_NAME, KEYRING_PERMISSION, getChainIdsCaveat, extractChainFromAssetId, } from './data-sources/index.js';
17
17
  export type { SnapDataSourceState, SnapDataSourceOptions, } from './data-sources/index.js';
18
18
  export { TokenDataSource, PriceDataSource } from './data-sources/index.js';
19
- export type { TokenDataSourceOptions, PriceDataSourceConfig, PriceDataSourceOptions, } from './data-sources/index.js';
19
+ export type { TokenDataSourceOptions, PriceDataSourceConfig, PriceDataSourceOptions, MarketStatsPriceStreamMessenger, } from './data-sources/index.js';
20
20
  export { RpcFallbackMiddleware } from './middlewares/index.js';
21
21
  export type { RpcFallbackMiddlewareOptions } from './middlewares/index.js';
22
+ export { MarketStatsStore, marketStatsAssetKey, readLiveQuote, } from './store/MarketStatsStore.js';
23
+ export type { LiveQuote, LivePriceMap } from './store/MarketStatsStore.js';
22
24
  export { normalizeAssetId, formatExchangeRatesForBridge, formatStateForTransactionPay, } from './utils/index.js';
23
25
  export type { AccountForLegacyFormat, BridgeExchangeRatesFormat, FormatExchangeRatesForBridgeParams, FormatStateForTransactionPayParams, LegacyToken, TransactionPayLegacyFormat, } from './utils/index.js';
24
26
  export { calculateBalanceForAllWallets, calculateBalanceChangeForAccountGroup, getAggregatedBalanceForAccount, getGroupIdForAccount, getInternalAccountsForGroup, } from './selectors/balance.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gBAAgB,EAChB,+BAA+B,GAChC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,EAClC,sBAAsB,EACtB,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,GACxB,MAAM,eAAe,CAAC;AACvB,YAAY,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAGlE,OAAO,EACL,gCAAgC,EAChC,iCAAiC,EACjC,yBAAyB,EACzB,gCAAgC,EAChC,sBAAsB,EACtB,+BAA+B,EAC/B,8BAA8B,GAC/B,MAAM,mCAAmC,CAAC;AAC3C,YAAY,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAGvF,YAAY,EACV,qBAAqB,EACrB,yBAAyB,EACzB,uBAAuB,EACvB,8BAA8B,EAC9B,uBAAuB,EACvB,gCAAgC,EAChC,mCAAmC,EACnC,iCAAiC,EACjC,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EACV,+BAA+B,EAC/B,sCAAsC,EACtC,sCAAsC,EACtC,yCAAyC,EACzC,2CAA2C,EAC3C,6CAA6C,EAC7C,oCAAoC,EACpC,sCAAsC,EACtC,oCAAoC,EACpC,uCAAuC,EACvC,qCAAqC,EACrC,+BAA+B,EAC/B,iCAAiC,EACjC,+CAA+C,EAC/C,+CAA+C,EAC/C,yCAAyC,GAC1C,MAAM,2CAA2C,CAAC;AAGnD,Y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2B,GAC5B,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EACL,iCAAiC,EACjC,sCAAsC,EACtC,4BAA4B,EAC5B,uBAAuB,EACvB,mDAAmD,EACnD,yCAAyC,EACzC,0BAA0B,EAC1B,+BAA+B,EAC/B,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,wBAAwB,CAAC;AAEhC,YAAY,EACV,mBAAmB,EACnB,YAAY,EACZ,sBAAsB,EACtB,2BAA2B,EAC3B,iBAAiB,EACjB,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,aAAa,GACd,MAAM,wBAAwB,CAAC"}
package/dist/index.js CHANGED
@@ -20,6 +20,8 @@ getChainIdsCaveat, extractChainFromAssetId, } from './data-sources/index.js';
20
20
  export { TokenDataSource, PriceDataSource } from './data-sources/index.js';
21
21
  // Middlewares
22
22
  export { RpcFallbackMiddleware } from './middlewares/index.js';
23
+ // Market-stats quote cache. The UI holds this. AssetsController state does not.
24
+ export { MarketStatsStore, marketStatsAssetKey, readLiveQuote, } from './store/MarketStatsStore.js';
23
25
  // Utilities
24
26
  export { normalizeAssetId, formatExchangeRatesForBridge, formatStateForTransactionPay, } from './utils/index.js';
25
27
  // Selectors
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,yBAAyB;AACzB,OAAO,EACL,gBAAgB,EAChB,+BAA+B,GAChC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,EAClC,sBAAsB,EACtB,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,GACxB,MAAM,eAAe,CAAC;AAGvB,4CAA4C;AAC5C,OAAO,EACL,gCAAgC,EAChC,iCAAiC,EACjC,yBAAyB,EACzB,gCAAgC,EAChC,sBAAsB,EACtB,+BAA+B,EAC/B,8BAA8B,GAC/B,MAAM,mCAAmC,CAAC;AAwF3C,sCAAsC;AACtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAO7D,6BAA6B;AAC7B,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAQhE,qBAAqB;AACrB,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAS7E,gFAAgF;AAChF,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,qBAAqB;AACrB,YAAY;AACZ,kBAAkB;AAClB,oBAAoB;AACpB,iBAAiB,EACjB,uBAAuB,GACxB,MAAM,yBAAyB,CAAC;AAOjC,0BAA0B;AAC1B,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAQ3E,cAAc;AACd,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAG/D,YAAY;AACZ,OAAO,EACL,gBAAgB,EAChB,4BAA4B,EAC5B,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC;AAU1B,YAAY;AACZ,OAAO,EACL,6BAA6B,EAC7B,qCAAqC,EACrC,8BAA8B,EAC9B,oBAAoB,EACpB,2BAA2B,GAC5B,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EACL,iCAAiC,EACjC,sCAAsC,EACtC,4BAA4B,EAC5B,uBAAuB,EACvB,mDAAmD,EACnD,yCAAyC,EACzC,0BAA0B,EAC1B,+BAA+B,EAC/B,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,wBAAwB,CAAC","sourcesContent":["// Main controller export\nexport {\n AssetsController,\n getDefaultAssetsControllerState,\n} from './AssetsController.js';\nexport { AssetsDataSourceError } from './errors.js';\nexport {\n DEFAULT_TRACKED_ASSETS_BY_CHAIN,\n CHAINS_WITH_DEFAULT_TRACKED_ASSETS,\n DEFAULT_ASSET_METADATA,\n buildDefaultAssetsInfo,\n getDefaultTrackedAssetsForChain,\n getDefaultAssetMetadata,\n} from './defaults.js';\nexport type { PendingTokenMetadata } from './AssetsController.js';\n\n// Snaps → AssetsController assets migration\nexport {\n SNAPS_ASSETS_MIGRATION_FLAG_KEYS,\n SNAPS_ASSETS_MIGRATION_NAMESPACES,\n SnapsAssetsMigrationStage,\n getSnapsAssetsMigrationNamespace,\n isMigrationStageActive,\n isSnapsAssetsMigrationNamespace,\n parseSnapsAssetsMigrationStage,\n} from './utils/snaps-assets-migration.js';\nexport type { SnapsAssetsMigrationNamespace } from './utils/snaps-assets-migration.js';\n\n// State and messenger types\nexport type {\n AssetsControllerState,\n AssetsControllerMessenger,\n AssetsControllerOptions,\n AssetsControllerGetStateAction,\n AssetsControllerActions,\n AssetsControllerStateChangeEvent,\n AssetsControllerBalanceChangedEvent,\n AssetsControllerPriceChangedEvent,\n AssetsControllerEvents,\n} from './AssetsController.js';\nexport type {\n AssetsControllerGetAssetsAction,\n AssetsControllerGetAssetsBalanceAction,\n AssetsControllerGetAssetMetadataAction,\n AssetsControllerGetAccountAssetByIDAction,\n AssetsControllerGetAccountAssetsByIDsAction,\n AssetsControllerGetAccountAssetsByScopeAction,\n AssetsControllerGetAssetsPriceAction,\n AssetsControllerSyncAssetsPricesAction,\n AssetsControllerAddCustomAssetAction,\n AssetsControllerRemoveCustomAssetAction,\n AssetsControllerGetCustomAssetsAction,\n AssetsControllerHideAssetAction,\n AssetsControllerUnhideAssetAction,\n AssetsControllerGetExchangeRatesForBridgeAction,\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerSetSelectedCurrencyAction,\n} from './AssetsController-method-action-types.js';\n\n// Core types\nexport type {\n // CAIP types\n Caip19AssetId,\n AccountId,\n ChainId,\n // Asset types\n AssetType,\n TokenStandard,\n // Contract data types\n TokenFees,\n HoneypotStatus,\n StorageSlots,\n LocalizedDescription,\n // Metadata types\n BaseAssetMetadata,\n FungibleAssetMetadata,\n ERC721AssetMetadata,\n ERC1155AssetMetadata,\n AssetMetadata,\n // Price types\n BaseAssetPrice,\n FungibleAssetPrice,\n NFTAssetPrice,\n AssetPrice,\n // Balance types\n FungibleAssetBalance,\n ERC721AssetBalance,\n ERC1155AssetBalance,\n AssetBalance,\n // Data source types\n AccountWithSupportedChains,\n DataType,\n DataRequest,\n DataResponse,\n AssetsUpdateMode,\n AssetsLoadingStatus,\n // Middleware types\n Context,\n NextFunction,\n Middleware,\n AssetsDataSource,\n FetchContext,\n FetchNextFunction,\n FetchMiddleware,\n SubscriptionResponse,\n // Combined asset type\n Asset,\n // Event types\n BalanceChangeEvent,\n PriceChangeEvent,\n MetadataChangeEvent,\n} from './types.js';\n\n// Data sources - base class and types\nexport { AbstractDataSource } from './data-sources/index.js';\n\nexport type {\n DataSourceState,\n SubscriptionRequest,\n} from './data-sources/index.js';\n\n// Data sources - AccountsApi\nexport { AccountsApiDataSource } from './data-sources/index.js';\n\nexport type {\n AccountsApiDataSourceConfig,\n AccountsApiDataSourceOptions,\n AccountsApiDataSourceState,\n} from './data-sources/index.js';\n\n// Data sources - RPC\nexport { RpcDataSource, createRpcDataSource } from './data-sources/index.js';\n\nexport type {\n RpcDataSourceConfig,\n RpcDataSourceOptions,\n RpcDataSourceState,\n ChainStatus,\n} from './data-sources/index.js';\n\n// Data sources - Unified Snap Data Source (dynamically discovers keyring snaps)\nexport {\n SnapDataSource,\n createSnapDataSource,\n SNAP_DATA_SOURCE_NAME,\n // Constants\n KEYRING_PERMISSION,\n // Utility functions\n getChainIdsCaveat,\n extractChainFromAssetId,\n} from './data-sources/index.js';\n\nexport type {\n SnapDataSourceState,\n SnapDataSourceOptions,\n} from './data-sources/index.js';\n\n// Enrichment data sources\nexport { TokenDataSource, PriceDataSource } from './data-sources/index.js';\n\nexport type {\n TokenDataSourceOptions,\n PriceDataSourceConfig,\n PriceDataSourceOptions,\n} from './data-sources/index.js';\n\n// Middlewares\nexport { RpcFallbackMiddleware } from './middlewares/index.js';\nexport type { RpcFallbackMiddlewareOptions } from './middlewares/index.js';\n\n// Utilities\nexport {\n normalizeAssetId,\n formatExchangeRatesForBridge,\n formatStateForTransactionPay,\n} from './utils/index.js';\nexport type {\n AccountForLegacyFormat,\n BridgeExchangeRatesFormat,\n FormatExchangeRatesForBridgeParams,\n FormatStateForTransactionPayParams,\n LegacyToken,\n TransactionPayLegacyFormat,\n} from './utils/index.js';\n\n// Selectors\nexport {\n calculateBalanceForAllWallets,\n calculateBalanceChangeForAccountGroup,\n getAggregatedBalanceForAccount,\n getGroupIdForAccount,\n getInternalAccountsForGroup,\n} from './selectors/balance.js';\n\nexport {\n getAccountBackgroundLoadingStatus,\n getAccountGroupBackgroundLoadingStatus,\n getAccountGroupLoadingStatus,\n getAccountLoadingStatus,\n getIsAssetsBackgroundLoadingForSelectedAccountGroup,\n getIsAssetsLoadingForSelectedAccountGroup,\n isAccountBackgroundLoading,\n isAccountGroupBackgroundLoading,\n isAccountGroupLoading,\n isAccountLoading,\n} from './selectors/loading.js';\n\nexport type {\n AccountGroupBalance,\n AccountsById,\n AggregatedBalanceEntry,\n AggregatedBalanceForAccount,\n AllWalletsBalance,\n BalanceChangePeriod,\n BalanceChangeResult,\n EnabledNetworkMap,\n WalletBalance,\n} from './selectors/balance.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,yBAAyB;AACzB,OAAO,EACL,gBAAgB,EAChB,+BAA+B,GAChC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,EAClC,sBAAsB,EACtB,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,GACxB,MAAM,eAAe,CAAC;AAGvB,4CAA4C;AAC5C,OAAO,EACL,gCAAgC,EAChC,iCAAiC,EACjC,yBAAyB,EACzB,gCAAgC,EAChC,sBAAsB,EACtB,+BAA+B,EAC/B,8BAA8B,GAC/B,MAAM,mCAAmC,CAAC;AAuF3C,sCAAsC;AACtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAO7D,6BAA6B;AAC7B,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAQhE,qBAAqB;AACrB,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAS7E,gFAAgF;AAChF,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,qBAAqB;AACrB,YAAY;AACZ,kBAAkB;AAClB,oBAAoB;AACpB,iBAAiB,EACjB,uBAAuB,GACxB,MAAM,yBAAyB,CAAC;AAOjC,0BAA0B;AAC1B,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAS3E,cAAc;AACd,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAG/D,gFAAgF;AAChF,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,aAAa,GACd,MAAM,6BAA6B,CAAC;AAGrC,YAAY;AACZ,OAAO,EACL,gBAAgB,EAChB,4BAA4B,EAC5B,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC;AAU1B,YAAY;AACZ,OAAO,EACL,6BAA6B,EAC7B,qCAAqC,EACrC,8BAA8B,EAC9B,oBAAoB,EACpB,2BAA2B,GAC5B,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EACL,iCAAiC,EACjC,sCAAsC,EACtC,4BAA4B,EAC5B,uBAAuB,EACvB,mDAAmD,EACnD,yCAAyC,EACzC,0BAA0B,EAC1B,+BAA+B,EAC/B,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,wBAAwB,CAAC","sourcesContent":["// Main controller export\nexport {\n AssetsController,\n getDefaultAssetsControllerState,\n} from './AssetsController.js';\nexport { AssetsDataSourceError } from './errors.js';\nexport {\n DEFAULT_TRACKED_ASSETS_BY_CHAIN,\n CHAINS_WITH_DEFAULT_TRACKED_ASSETS,\n DEFAULT_ASSET_METADATA,\n buildDefaultAssetsInfo,\n getDefaultTrackedAssetsForChain,\n getDefaultAssetMetadata,\n} from './defaults.js';\nexport type { PendingTokenMetadata } from './AssetsController.js';\n\n// Snaps → AssetsController assets migration\nexport {\n SNAPS_ASSETS_MIGRATION_FLAG_KEYS,\n SNAPS_ASSETS_MIGRATION_NAMESPACES,\n SnapsAssetsMigrationStage,\n getSnapsAssetsMigrationNamespace,\n isMigrationStageActive,\n isSnapsAssetsMigrationNamespace,\n parseSnapsAssetsMigrationStage,\n} from './utils/snaps-assets-migration.js';\nexport type { SnapsAssetsMigrationNamespace } from './utils/snaps-assets-migration.js';\n\n// State and messenger types\nexport type {\n AssetsControllerState,\n AssetsControllerMessenger,\n AssetsControllerOptions,\n AssetsControllerGetStateAction,\n AssetsControllerActions,\n AssetsControllerStateChangeEvent,\n AssetsControllerBalanceChangedEvent,\n AssetsControllerEvents,\n} from './AssetsController.js';\nexport type {\n AssetsControllerGetAssetsAction,\n AssetsControllerGetAssetsBalanceAction,\n AssetsControllerGetAssetMetadataAction,\n AssetsControllerGetAccountAssetByIDAction,\n AssetsControllerGetAccountAssetsByIDsAction,\n AssetsControllerGetAccountAssetsByScopeAction,\n AssetsControllerGetAssetsPriceAction,\n AssetsControllerSyncAssetsPricesAction,\n AssetsControllerAddCustomAssetAction,\n AssetsControllerRemoveCustomAssetAction,\n AssetsControllerGetCustomAssetsAction,\n AssetsControllerHideAssetAction,\n AssetsControllerUnhideAssetAction,\n AssetsControllerGetExchangeRatesForBridgeAction,\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerSetSelectedCurrencyAction,\n} from './AssetsController-method-action-types.js';\n\n// Core types\nexport type {\n // CAIP types\n Caip19AssetId,\n AccountId,\n ChainId,\n // Asset types\n AssetType,\n TokenStandard,\n // Contract data types\n TokenFees,\n HoneypotStatus,\n StorageSlots,\n LocalizedDescription,\n // Metadata types\n BaseAssetMetadata,\n FungibleAssetMetadata,\n ERC721AssetMetadata,\n ERC1155AssetMetadata,\n AssetMetadata,\n // Price types\n BaseAssetPrice,\n FungibleAssetPrice,\n NFTAssetPrice,\n AssetPrice,\n // Balance types\n FungibleAssetBalance,\n ERC721AssetBalance,\n ERC1155AssetBalance,\n AssetBalance,\n // Data source types\n AccountWithSupportedChains,\n DataType,\n DataRequest,\n DataResponse,\n AssetsUpdateMode,\n AssetsLoadingStatus,\n // Middleware types\n Context,\n NextFunction,\n Middleware,\n AssetsDataSource,\n FetchContext,\n FetchNextFunction,\n FetchMiddleware,\n SubscriptionResponse,\n // Combined asset type\n Asset,\n // Event types\n BalanceChangeEvent,\n PriceChangeEvent,\n MetadataChangeEvent,\n} from './types.js';\n\n// Data sources - base class and types\nexport { AbstractDataSource } from './data-sources/index.js';\n\nexport type {\n DataSourceState,\n SubscriptionRequest,\n} from './data-sources/index.js';\n\n// Data sources - AccountsApi\nexport { AccountsApiDataSource } from './data-sources/index.js';\n\nexport type {\n AccountsApiDataSourceConfig,\n AccountsApiDataSourceOptions,\n AccountsApiDataSourceState,\n} from './data-sources/index.js';\n\n// Data sources - RPC\nexport { RpcDataSource, createRpcDataSource } from './data-sources/index.js';\n\nexport type {\n RpcDataSourceConfig,\n RpcDataSourceOptions,\n RpcDataSourceState,\n ChainStatus,\n} from './data-sources/index.js';\n\n// Data sources - Unified Snap Data Source (dynamically discovers keyring snaps)\nexport {\n SnapDataSource,\n createSnapDataSource,\n SNAP_DATA_SOURCE_NAME,\n // Constants\n KEYRING_PERMISSION,\n // Utility functions\n getChainIdsCaveat,\n extractChainFromAssetId,\n} from './data-sources/index.js';\n\nexport type {\n SnapDataSourceState,\n SnapDataSourceOptions,\n} from './data-sources/index.js';\n\n// Enrichment data sources\nexport { TokenDataSource, PriceDataSource } from './data-sources/index.js';\n\nexport type {\n TokenDataSourceOptions,\n PriceDataSourceConfig,\n PriceDataSourceOptions,\n MarketStatsPriceStreamMessenger,\n} from './data-sources/index.js';\n\n// Middlewares\nexport { RpcFallbackMiddleware } from './middlewares/index.js';\nexport type { RpcFallbackMiddlewareOptions } from './middlewares/index.js';\n\n// Market-stats quote cache. The UI holds this. AssetsController state does not.\nexport {\n MarketStatsStore,\n marketStatsAssetKey,\n readLiveQuote,\n} from './store/MarketStatsStore.js';\nexport type { LiveQuote, LivePriceMap } from './store/MarketStatsStore.js';\n\n// Utilities\nexport {\n normalizeAssetId,\n formatExchangeRatesForBridge,\n formatStateForTransactionPay,\n} from './utils/index.js';\nexport type {\n AccountForLegacyFormat,\n BridgeExchangeRatesFormat,\n FormatExchangeRatesForBridgeParams,\n FormatStateForTransactionPayParams,\n LegacyToken,\n TransactionPayLegacyFormat,\n} from './utils/index.js';\n\n// Selectors\nexport {\n calculateBalanceForAllWallets,\n calculateBalanceChangeForAccountGroup,\n getAggregatedBalanceForAccount,\n getGroupIdForAccount,\n getInternalAccountsForGroup,\n} from './selectors/balance.js';\n\nexport {\n getAccountBackgroundLoadingStatus,\n getAccountGroupBackgroundLoadingStatus,\n getAccountGroupLoadingStatus,\n getAccountLoadingStatus,\n getIsAssetsBackgroundLoadingForSelectedAccountGroup,\n getIsAssetsLoadingForSelectedAccountGroup,\n isAccountBackgroundLoading,\n isAccountGroupBackgroundLoading,\n isAccountGroupLoading,\n isAccountLoading,\n} from './selectors/loading.js';\n\nexport type {\n AccountGroupBalance,\n AccountsById,\n AggregatedBalanceEntry,\n AggregatedBalanceForAccount,\n AllWalletsBalance,\n BalanceChangePeriod,\n BalanceChangeResult,\n EnabledNetworkMap,\n WalletBalance,\n} from './selectors/balance.js';\n"]}
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Quote cache for `MarketStatsService:pricesUpdated`.
3
+ *
4
+ * The UI holds one instance. A tick updates this object and does not write
5
+ * `AssetsController` state, so it does not persist and does not notify the
6
+ * controller. Polled prices stay in `assetsPrice` and show when this map has
7
+ * no quote.
8
+ */
9
+ export type LiveQuote = {
10
+ price: number;
11
+ pricePercentChange1d?: number;
12
+ };
13
+ export type LivePriceMap = ReadonlyMap<string, LiveQuote>;
14
+ /**
15
+ * Key a market-stats asset id the same way on the tick and on the lookup.
16
+ * EVM ERC-20 addresses are checksummed. Anything else is kept as given.
17
+ *
18
+ * @param assetId - CAIP-19 asset id, or any other string the caller uses as a key.
19
+ * @returns The map key.
20
+ */
21
+ export declare function marketStatsAssetKey(assetId: string): string;
22
+ /**
23
+ * Quote for one asset. The id is keyed with {@link marketStatsAssetKey}.
24
+ *
25
+ * @param quotes - Current quote map.
26
+ * @param assetId - CAIP-19 asset id.
27
+ * @returns The streamed quote, or undefined.
28
+ */
29
+ export declare function readLiveQuote(quotes: LivePriceMap, assetId: string | undefined): LiveQuote | undefined;
30
+ /**
31
+ * Latest market-stats quotes for one currency.
32
+ */
33
+ export declare class MarketStatsStore {
34
+ #private;
35
+ /**
36
+ * Stable reference so `useSyncExternalStore` can take it directly.
37
+ *
38
+ * @returns The current quote map. The same reference until a tick changes it.
39
+ */
40
+ readonly getSnapshot: () => LivePriceMap;
41
+ /**
42
+ * @param listener - Called after the quote map changes.
43
+ * @returns Unsubscribe.
44
+ */
45
+ readonly subscribe: (listener: () => void) => (() => void);
46
+ /**
47
+ * Remember the selected currency and drop quotes from the previous one.
48
+ * Does not notify. Callers invoke this during render, and the currency
49
+ * selector is what re-renders every reader. That render already reads the
50
+ * empty map.
51
+ *
52
+ * @param currency - Selected currency. Case is ignored.
53
+ */
54
+ setCurrency(currency: string): void;
55
+ /**
56
+ * Merge one `MarketStatsService:pricesUpdated` payload.
57
+ * Entries in another currency are ignored. The argument is the object
58
+ * passed to `publish`. The extension unwraps its forwarded argument list
59
+ * before calling this.
60
+ *
61
+ * @param payload - Published `{ updates }` object.
62
+ */
63
+ ingestPrices(payload: unknown): void;
64
+ /**
65
+ * A chain reported down leaves the map so the polled price shows until the
66
+ * next tick for that chain.
67
+ *
68
+ * @param payload - Published `MarketStatsService:chainStatusChanged` object.
69
+ */
70
+ ingestChainStatus(payload: unknown): void;
71
+ }
72
+ //# sourceMappingURL=MarketStatsStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MarketStatsStore.d.ts","sourceRoot":"","sources":["../../src/store/MarketStatsStore.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAMH,MAAM,MAAM,SAAS,GAAG;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG,WAAW,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAE1D;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAK3D;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,YAAY,EACpB,OAAO,EAAE,MAAM,GAAG,SAAS,GAC1B,SAAS,GAAG,SAAS,CAKvB;AAqBD;;GAEG;AACH,qBAAa,gBAAgB;;IAO3B;;;;OAIG;IACH,QAAQ,CAAC,WAAW,QAAO,YAAY,CAAiB;IAExD;;;OAGG;IACH,QAAQ,CAAC,SAAS,aAAc,MAAM,IAAI,KAAG,CAAC,MAAM,IAAI,CAAC,CAKvD;IAEF;;;;;;;OAOG;IACH,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAUlC;IAED;;;;;;;OAOG;IACH,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CA6CnC;IAED;;;;;OAKG;IACH,iBAAiB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAgCxC;CAQF"}