@metamask-previews/assets-controller 20.4.1-preview-cf24e3cc8 → 20.4.1-preview-c552582c8

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.
@@ -100,11 +100,11 @@ export declare class PriceDataSource {
100
100
  */
101
101
  subscribe(subscriptionRequest: SubscriptionRequest): Promise<void>;
102
102
  /**
103
- * Unsubscribe from price updates.
103
+ * Stop the price poll and release market-stats channels.
104
104
  *
105
- * @param subscriptionId - The ID of the subscription to cancel.
105
+ * @param _subscriptionId - Ignored. The controller passes its subscription key.
106
106
  */
107
- unsubscribe(subscriptionId: string): Promise<void>;
107
+ unsubscribe(_subscriptionId?: string): Promise<void>;
108
108
  /**
109
109
  * Drop market-stats channels and open them again for the current currency.
110
110
  * Called when the selected currency changes so batches match `assetsPrice`.
@@ -1 +1 @@
1
- {"version":3,"file":"PriceDataSource.d.ts","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,iBAAiB,EAElB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAI3D,OAAO,KAAK,EACV,aAAa,EACb,WAAW,EACX,YAAY,EACZ,kBAAkB,EAClB,UAAU,EACV,qBAAqB,EACtB,MAAM,aAAa,CAAC;AASrB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAEnE,OAAO,KAAK,EACV,+BAA+B,EAEhC,MAAM,6BAA6B,CAAC;AA+DrC,kDAAkD;AAClD,MAAM,MAAM,qBAAqB,GAAG;IAClC,8CAA8C;IAC9C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;;;OAKG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B,CAAC;AAEF,YAAY,EAAE,+BAA+B,EAAE,MAAM,6BAA6B,C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IAAI,UAAU,CA6BjC;IAED;;;;;OAKG;IACG,gBAAgB,CACpB,QAAQ,EAAE,aAAa,EAAE,GACxB,OAAO,CAAC,MAAM,CAAC,aAAa,EAAE,kBAAkB,CAAC,CAAC,CASpD;IAkND;;;;;;;;OAQG;IACG,KAAK,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,YAAY,CAAC,CAKvD;IAgCD;;;;;OAKG;IACG,SAAS,CAAC,mBAAmB,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAqCvE;IAED;;;;OAIG;IACG,WAAW,CAAC,eAAe,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAQzD;IAED;;;OAGG;IACG,4BAA4B,IAAI,OAAO,CAAC,IAAI,CAAC,CAOlD;IAED;;;;;;;OAOG;IACG,sBAAsB,IAAI,OAAO,CAAC,IAAI,CAAC,CAK5C;IAED;;;;OAIG;IACH,oBAAoB,IAAI,IAAI,CAE3B;IAED;;OAEG;IACH,OAAO,IAAI,IAAI,CAKd;CAmDF"}
@@ -102,8 +102,8 @@ export class PriceDataSource {
102
102
  #deduper;
103
103
  #getAssetsState;
104
104
  #marketStats;
105
- /** Active subscriptions by ID */
106
- #activeSubscriptions = new Map();
105
+ /** The one price poll. The controller keeps a single PriceDataSource subscription. */
106
+ #subscription = null;
107
107
  constructor(options) {
108
108
  this.#getSelectedCurrency = options.getSelectedCurrency;
109
109
  this.#pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL;
@@ -373,83 +373,55 @@ export class PriceDataSource {
373
373
  * @param subscriptionRequest - The subscription request configuration.
374
374
  */
375
375
  async subscribe(subscriptionRequest) {
376
- const { request, subscriptionId, isUpdate } = subscriptionRequest;
377
- // Handle subscription update: refresh request and fetch immediately so
378
- // newly held / still-unpriced assets (e.g. seeded natives) do not wait
379
- // for the next poll tick. Deduper freshness TTL skips recently priced IDs.
380
- if (isUpdate) {
381
- const existing = this.#activeSubscriptions.get(subscriptionId);
382
- if (existing) {
383
- existing.request = request;
384
- existing.onAssetsUpdate = subscriptionRequest.onAssetsUpdate;
385
- try {
386
- const fetchResponse = await this.fetch(request);
387
- if (fetchResponse.assetsPrice &&
388
- Object.keys(fetchResponse.assetsPrice).length > 0) {
389
- await existing.onAssetsUpdate({
390
- ...fetchResponse,
391
- updateMode: 'merge',
392
- });
393
- }
394
- await this.#reconcileMarketStats();
395
- }
396
- catch (error) {
397
- log('Subscription update fetch failed', { subscriptionId, error });
398
- }
399
- return;
400
- }
376
+ const { request, onAssetsUpdate } = subscriptionRequest;
377
+ if (this.#subscription) {
378
+ // Keep the interval. Refresh the request and fetch now so newly held
379
+ // assets do not wait for the next tick.
380
+ this.#subscription.request = request;
381
+ this.#subscription.onAssetsUpdate = onAssetsUpdate;
401
382
  }
402
- // Clean up existing subscription
403
- await this.unsubscribe(subscriptionId);
404
- const pollInterval = request.updateInterval ?? this.#pollInterval;
405
- // Cap the freshness TTL strictly below the effective poll interval.
406
- // `fetchedAt` is stamped when a fetch completes (slightly after the tick
407
- // that triggered it), so a TTL equal to the poll interval would leave the
408
- // asset still "fresh" at the next tick, making the subscription re-fetch
409
- // only every other poll. The margin also absorbs network latency / jitter.
410
- this.#deduper.freshnessTtlMs = Math.min(this.#deduper.freshnessTtlMs, Math.floor(pollInterval * FRESHNESS_TTL_POLL_RATIO));
411
- // Each tick prices every tracked asset, the same as the poll without
412
- // market stats. An open channel does not skip one.
413
- const timer = setInterval(() => {
414
- this.#runPoll(subscriptionId).catch((error) => {
415
- log('Subscription poll failed', { subscriptionId, error });
416
- });
417
- }, pollInterval);
418
- // Store subscription
419
- this.#activeSubscriptions.set(subscriptionId, {
420
- cleanup: () => {
421
- clearInterval(timer);
422
- },
423
- request,
424
- onAssetsUpdate: subscriptionRequest.onAssetsUpdate,
425
- });
426
- // Initial fetch
427
- await this.#runPoll(subscriptionId);
383
+ else {
384
+ const pollInterval = request.updateInterval ?? this.#pollInterval;
385
+ // Cap the freshness TTL strictly below the effective poll interval.
386
+ // `fetchedAt` is stamped when a fetch completes (slightly after the tick
387
+ // that triggered it), so a TTL equal to the poll interval would leave the
388
+ // asset still "fresh" at the next tick, making the subscription re-fetch
389
+ // only every other poll. The margin also absorbs network latency / jitter.
390
+ this.#deduper.freshnessTtlMs = Math.min(this.#deduper.freshnessTtlMs, Math.floor(pollInterval * FRESHNESS_TTL_POLL_RATIO));
391
+ const timer = setInterval(() => {
392
+ this.#runPoll().catch((error) => {
393
+ log('Subscription poll failed', { error });
394
+ });
395
+ }, pollInterval);
396
+ this.#subscription = {
397
+ cleanup: () => {
398
+ clearInterval(timer);
399
+ },
400
+ request,
401
+ onAssetsUpdate,
402
+ };
403
+ }
404
+ await this.#runPoll();
428
405
  }
429
406
  /**
430
- * Unsubscribe from price updates.
407
+ * Stop the price poll and release market-stats channels.
431
408
  *
432
- * @param subscriptionId - The ID of the subscription to cancel.
409
+ * @param _subscriptionId - Ignored. The controller passes its subscription key.
433
410
  */
434
- async unsubscribe(subscriptionId) {
435
- const subscription = this.#activeSubscriptions.get(subscriptionId);
436
- if (!subscription) {
411
+ async unsubscribe(_subscriptionId) {
412
+ if (!this.#subscription) {
437
413
  return;
438
414
  }
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();
415
+ this.#subscription.cleanup();
416
+ this.#subscription = null;
417
+ await this.#marketStats.releaseSubscriptions();
446
418
  }
447
419
  /**
448
420
  * Drop market-stats channels and open them again for the current currency.
449
421
  * Called when the selected currency changes so batches match `assetsPrice`.
450
422
  */
451
423
  async resubscribeForCurrencyChange() {
452
- if (this.#activeSubscriptions.size === 0) {
424
+ if (!this.#subscription) {
453
425
  return;
454
426
  }
455
427
  await this.#marketStats.releaseSubscriptions();
@@ -464,7 +436,7 @@ export class PriceDataSource {
464
436
  * The price poll reconciles at the end of its own tick.
465
437
  */
466
438
  async reconcileMarketStreams() {
467
- if (this.#activeSubscriptions.size === 0) {
439
+ if (!this.#subscription) {
468
440
  return;
469
441
  }
470
442
  await this.#reconcileMarketStats();
@@ -481,21 +453,17 @@ export class PriceDataSource {
481
453
  * Destroy the data source and clean up all subscriptions.
482
454
  */
483
455
  destroy() {
484
- for (const subscription of this.#activeSubscriptions.values()) {
485
- subscription.cleanup();
486
- }
487
- this.#activeSubscriptions.clear();
456
+ this.#subscription?.cleanup();
457
+ this.#subscription = null;
488
458
  this.#marketStats.destroy();
489
459
  this.#deduper.destroy();
490
460
  }
491
461
  /**
492
462
  * One poll tick: REST-fetch every tracked asset, then open market-stats
493
463
  * channels for assets the response marks `wssSupport`.
494
- *
495
- * @param subscriptionId - Active subscription to poll.
496
464
  */
497
- async #runPoll(subscriptionId) {
498
- const subscription = this.#activeSubscriptions.get(subscriptionId);
465
+ async #runPoll() {
466
+ const subscription = this.#subscription;
499
467
  if (!subscription) {
500
468
  return;
501
469
  }
@@ -511,18 +479,16 @@ export class PriceDataSource {
511
479
  await this.#reconcileMarketStats();
512
480
  }
513
481
  catch (error) {
514
- log('Subscription poll failed', { subscriptionId, error });
482
+ log('Subscription poll failed', { error });
515
483
  }
516
484
  }
517
485
  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
- }
486
+ const subscription = this.#subscription;
487
+ if (!subscription) {
488
+ return;
524
489
  }
525
- await this.#marketStats.reconcile(this.#candidatesFor([...assetIds]));
490
+ const assetIds = await this.#filterToSupportedPriceableAssets(this.#getAssetIdsFromBalanceState(subscription.request));
491
+ await this.#marketStats.reconcile(this.#candidatesFor(assetIds));
526
492
  }
527
493
  #candidatesFor(assetIds) {
528
494
  const prices = this.#getAssetsState().assetsPrice ?? {};
@@ -1 +1 @@
1
- {"version":3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ACN,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"]}
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,MAAM,kCAAkC,CAAC;AACxE,OAAO,EACL,+BAA+B,EAC/B,wBAAwB,EACxB,2BAA2B,EAC3B,gBAAgB,GACjB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAErD,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAKtE,OAAO,EACL,sBAAsB,EACtB,8BAA8B,GAC/B,MAAM,6BAA6B,CAAC;AAErC,+EAA+E;AAC/E,YAAY;AACZ,+EAA+E;AAE/E,MAAM,eAAe,GAAG,iBAAiB,CAAC;AAC1C,MAAM,qBAAqB,GAAG,MAAM,CAAC,CAAC,6BAA6B;AACnE,MAAM,wBAAwB,GAAG,MAAM,CAAC;AAExC;;;;;GAKG;AACH,MAAM,wBAAwB,GAAG,GAAG,CAAC;AAErC,yDAAyD;AACzD,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAEhC,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,eAAe,CAAC,CAAC;AAE/D,+EAA+E;AAC/E,UAAU;AACV,+EAA+E;AAE/E;;;;;;;;;;;;;;GAcG;AACH,SAAS,+BAA+B,CAAC,QAKxC;IACC,MAAM,EAAE,WAAW,EAAE,cAAc,EAAE,GAAG,QAAQ,CAAC;IACjD,MAAM,OAAO,GAAG,KAAK,CAAC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["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 /** The one price poll. The controller keeps a single PriceDataSource subscription. */\n #subscription: {\n cleanup: () => void;\n request: DataRequest;\n onAssetsUpdate: (response: DataResponse) => void | Promise<void>;\n } | null = null;\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, onAssetsUpdate } = subscriptionRequest;\n\n if (this.#subscription) {\n // Keep the interval. Refresh the request and fetch now so newly held\n // assets do not wait for the next tick.\n this.#subscription.request = request;\n this.#subscription.onAssetsUpdate = onAssetsUpdate;\n } else {\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 const timer = setInterval(() => {\n this.#runPoll().catch((error: unknown) => {\n log('Subscription poll failed', { error });\n });\n }, pollInterval);\n\n this.#subscription = {\n cleanup: (): void => {\n clearInterval(timer);\n },\n request,\n onAssetsUpdate,\n };\n }\n\n await this.#runPoll();\n }\n\n /**\n * Stop the price poll and release market-stats channels.\n *\n * @param _subscriptionId - Ignored. The controller passes its subscription key.\n */\n async unsubscribe(_subscriptionId?: string): Promise<void> {\n if (!this.#subscription) {\n return;\n }\n\n this.#subscription.cleanup();\n this.#subscription = null;\n await this.#marketStats.releaseSubscriptions();\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.#subscription) {\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.#subscription) {\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 this.#subscription?.cleanup();\n this.#subscription = null;\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 async #runPoll(): Promise<void> {\n const subscription = this.#subscription;\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', { error });\n }\n }\n\n async #reconcileMarketStats(): Promise<void> {\n const subscription = this.#subscription;\n if (!subscription) {\n return;\n }\n\n const assetIds = await this.#filterToSupportedPriceableAssets(\n this.#getAssetIdsFromBalanceState(subscription.request),\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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/assets-controller",
3
- "version": "20.4.1-preview-cf24e3cc8",
3
+ "version": "20.4.1-preview-c552582c8",
4
4
  "description": "Tracks assets balances/prices and handles token detection across all digital assets",
5
5
  "keywords": [
6
6
  "Ethereum",