@metamask-previews/assets-controller 20.4.1-preview-c552582c8 → 20.4.1-preview-2da314d6d
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +0 -9
- package/README.md +0 -3
- package/dist/AssetsController-method-action-types.d.ts +2 -2
- package/dist/AssetsController-method-action-types.js.map +1 -1
- package/dist/AssetsController.d.ts +12 -6
- package/dist/AssetsController.d.ts.map +1 -1
- package/dist/AssetsController.js +16 -21
- package/dist/AssetsController.js.map +1 -1
- package/dist/data-sources/AccountActivityDataSource.d.ts +2 -4
- package/dist/data-sources/AccountActivityDataSource.d.ts.map +1 -1
- package/dist/data-sources/AccountActivityDataSource.js +1 -3
- package/dist/data-sources/AccountActivityDataSource.js.map +1 -1
- package/dist/data-sources/PriceDataSource.d.ts +5 -32
- package/dist/data-sources/PriceDataSource.d.ts.map +1 -1
- package/dist/data-sources/PriceDataSource.js +91 -133
- package/dist/data-sources/PriceDataSource.js.map +1 -1
- package/dist/data-sources/index.d.ts +1 -1
- package/dist/data-sources/index.d.ts.map +1 -1
- package/dist/data-sources/index.js.map +1 -1
- package/dist/index.d.ts +2 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -2
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +0 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
- package/dist/data-sources/MarketStatsPriceStream.d.ts +0 -67
- package/dist/data-sources/MarketStatsPriceStream.d.ts.map +0 -1
- package/dist/data-sources/MarketStatsPriceStream.js +0 -181
- package/dist/data-sources/MarketStatsPriceStream.js.map +0 -1
- package/dist/store/MarketStatsStore.d.ts +0 -72
- package/dist/store/MarketStatsStore.d.ts.map +0 -1
- package/dist/store/MarketStatsStore.js +0 -182
- package/dist/store/MarketStatsStore.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PriceDataSource.js","sourceRoot":"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,WAAW,CAAC,CAAC,MAAM,GAAG,CAAC,EACjD,CAAC;gBACD,MAAM,YAAY,CAAC,cAAc,CAAC;oBAChC,GAAG,aAAa;oBAChB,UAAU,EAAE,OAAO;iBACpB,CAAC,CAAC;YACL,CAAC;YAED,MAAM,IAAI,CAAC,qBAAqB,EAAE,CAAC;QACrC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,CAAC,0BAA0B,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC7C,CAAC;IACH,CAAC;IAED,KAAK,CAAC,qBAAqB;QACzB,MAAM,YAAY,GAAG,IAAI,CAAC,aAAa,CAAC;QACxC,IAAI,CAAC,YAAY,EAAE,CAAC;YAClB,OAAO;QACT,CAAC;QAED,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,iCAAiC,CAC3D,IAAI,CAAC,4BAA4B,CAAC,YAAY,CAAC,OAAO,CAAC,CACxD,CAAC;QACF,MAAM,IAAI,CAAC,YAAY,CAAC,SAAS,CAAC,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC,CAAC;IACnE,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 /** 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"]}
|
|
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;AAEtE,+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,+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YACvB,CAAC;YACD,OAAO;YACP,cAAc,EAAE,mBAAmB,CAAC,cAAc;SACnD,CAAC,CAAC;QAEH,gBAAgB;QAChB,MAAM,MAAM,EAAE,CAAC;IACjB,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,WAAW,CAAC,cAAsB;QACtC,MAAM,YAAY,GAAG,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;QACnE,IAAI,YAAY,EAAE,CAAC;YACjB,YAAY,CAAC,OAAO,EAAE,CAAC;YACvB,IAAI,CAAC,oBAAoB,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;QACnD,CAAC;IACH,CAAC;IAED;;;;OAIG;IACH,oBAAoB;QAClB,IAAI,CAAC,QAAQ,CAAC,UAAU,EAAE,CAAC;IAC7B,CAAC;IAED;;OAEG;IACH,OAAO;QACL,KAAK,MAAM,YAAY,IAAI,IAAI,CAAC,oBAAoB,CAAC,MAAM,EAAE,EAAE,CAAC;YAC9D,YAAY,CAAC,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"]}
|
|
@@ -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,
|
|
6
|
+
export { PriceDataSource, type PriceDataSourceConfig, type PriceDataSourceOptions, } 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,
|
|
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 +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,
|
|
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"]}
|
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, AssetsControllerEvents, } from './AssetsController.js';
|
|
7
|
+
export type { AssetsControllerState, AssetsControllerMessenger, AssetsControllerOptions, AssetsControllerGetStateAction, AssetsControllerActions, AssetsControllerStateChangeEvent, AssetsControllerBalanceChangedEvent, AssetsControllerPriceChangedEvent, 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,11 +16,9 @@ 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,
|
|
19
|
+
export type { TokenDataSourceOptions, PriceDataSourceConfig, PriceDataSourceOptions, } 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';
|
|
24
22
|
export { normalizeAssetId, formatExchangeRatesForBridge, formatStateForTransactionPay, } from './utils/index.js';
|
|
25
23
|
export type { AccountForLegacyFormat, BridgeExchangeRatesFormat, FormatExchangeRatesForBridgeParams, FormatStateForTransactionPayParams, LegacyToken, TransactionPayLegacyFormat, } from './utils/index.js';
|
|
26
24
|
export { calculateBalanceForAllWallets, calculateBalanceChangeForAccountGroup, getAggregatedBalanceForAccount, getGroupIdForAccount, getInternalAccountsForGroup, } from './selectors/balance.js';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -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,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EACV,+BAA+B,EAC/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C;AAGjC,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE3E,YAAY,EACV,sBAAsB,EACtB,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,yBAAyB,CAAC;AAGjC,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,YAAY,EAAE,4BAA4B,EAAE,MAAM,wBAAwB,CAAC;AAG3E,OAAO,EACL,gBAAgB,EAChB,4BAA4B,EAC5B,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EACV,sBAAsB,EACtB,yBAAyB,EACzB,kCAAkC,EAClC,kCAAkC,EAClC,WAAW,EACX,0BAA0B,GAC3B,MAAM,kBAAkB,CAAC;AAG1B,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;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,8 +20,6 @@ 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';
|
|
25
23
|
// Utilities
|
|
26
24
|
export { normalizeAssetId, formatExchangeRatesForBridge, formatStateForTransactionPay, } from './utils/index.js';
|
|
27
25
|
// 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;
|
|
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"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -200,11 +200,6 @@ export type FungibleAssetPrice = BaseAssetPrice & {
|
|
|
200
200
|
pricePercentChange1y?: number;
|
|
201
201
|
/** Current price in USD */
|
|
202
202
|
usdPrice: number;
|
|
203
|
-
/**
|
|
204
|
-
* True when this asset can stream on `market-stats.v1`.
|
|
205
|
-
* Absent or false keeps the asset on the `/v3/spot-prices` poll.
|
|
206
|
-
*/
|
|
207
|
-
wssSupport?: boolean;
|
|
208
203
|
};
|
|
209
204
|
/**
|
|
210
205
|
* Price data for NFT collections
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAChE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,IAAI,EAAE,MAA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G,EAAE,IAAI,EAAE,EAAE;QACzB,MAAM,cAAc,GAAG,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC;QAC7C,MAAM,SAAS,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;QAEtE,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;QACnB,CAAC;QAED,OAAO,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { SupportedCurrency } from '@metamask/core-backend';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { CaipAssetType, CaipChainId, Json } from '@metamask/utils';\n\n/**\n * CAIP-19 compliant asset identifier\n * Format: \"{chainId}/{assetNamespace}:{assetReference}[/tokenId]\"\n *\n * Examples:\n * - Native: \"eip155:1/slip44:60\" (ETH)\n * - ERC20: \"eip155:1/erc20:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\" (USDC)\n * - ERC721: \"eip155:1/erc721:0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D/1234\" (BAYC #1234)\n * - SPL: \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\"\n */\nexport type Caip19AssetId = CaipAssetType;\n\n/**\n * InternalAccount UUID from AccountsController\n * Not the blockchain address!\n */\nexport type AccountId = string;\n\n/**\n * CAIP-2 chain identifier\n */\nexport type ChainId = CaipChainId;\n\n// ============================================================================\n// ASSET TYPES - Defined by metadata structure\n// ============================================================================\n\n/**\n * Asset types define the metadata structure, not blockchain implementation.\n * - \"fungible\" includes: native, erc20, spl - all share balance, symbol, decimals\n * - \"nft\" includes: erc721, erc1155 - include tokenId, image, attributes\n */\nexport type AssetType = 'fungible' | 'nft' | 'collectible';\n\n/**\n * Token standards - blockchain implementation details\n */\nexport type TokenStandard =\n | 'native'\n | 'erc20'\n | 'erc721'\n | 'erc1155'\n | 'spl'\n | string;\n\n// ============================================================================\n// METADATA TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * UI preferences for an asset (stored in assetPreferences state, not in metadata).\n */\nexport type AssetPreferences = {\n /** Whether the asset is hidden from display */\n hidden?: boolean;\n};\n\n/**\n * Base metadata attributes shared by ALL asset types.\n */\nexport type BaseAssetMetadata = {\n /** Token standard - how it's implemented on the blockchain */\n type: TokenStandard;\n /** Display symbol (e.g., \"ETH\", \"USDC\") */\n symbol: string;\n /** Full name (e.g., \"Ethereum\", \"USD Coin\") */\n name: string;\n /** Token decimals (18 for ETH, 6 for USDC, etc.) */\n decimals: number;\n /** Logo URL or data URI */\n image?: string;\n};\n\n// ============================================================================\n// TOKEN CONTRACT DATA TYPES\n// ============================================================================\n\n/** Fee information for token transfers */\nexport type TokenFees = {\n avgFee: number;\n maxFee: number;\n minFee: number;\n};\n\n/** Honeypot detection status */\nexport type HoneypotStatus = {\n honeypotIs: boolean;\n goPlus?: boolean;\n};\n\n/** Storage slot information for the contract */\nexport type StorageSlots = {\n balance: number;\n approval: number;\n};\n\n/** Localized description */\nexport type LocalizedDescription = {\n en: string;\n};\n\n// ============================================================================\n// ASSET METADATA TYPES\n// ============================================================================\n\n/**\n * Metadata for fungible tokens.\n * Structure mirrors V3AssetResponse from the Tokens API.\n *\n * Differences from V3AssetResponse:\n * - `type` is derived from assetId namespace (not in API response)\n * - `image` maps from API's `iconUrl`\n * - `assetId` is not stored (used as the key)\n */\nexport type FungibleAssetMetadata = {\n /** Token type derived from assetId namespace */\n type: 'native' | 'erc20' | 'spl';\n /** CoinGecko ID for price lookups */\n coingeckoId?: string;\n /** Number of token list occurrences */\n occurrences?: number;\n /** DEX/aggregator integrations */\n aggregators?: string[];\n /** Asset labels/tags (e.g., \"stable_coin\") */\n labels?: string[];\n /** Whether the token supports ERC-20 permit */\n erc20Permit?: boolean;\n /** Fee information for token transfers */\n fees?: TokenFees;\n /** Honeypot detection status */\n honeypotStatus?: HoneypotStatus;\n /** Storage slot information for the contract */\n storage?: StorageSlots;\n /** Whether the contract is verified */\n isContractVerified?: boolean;\n /** Localized description */\n description?: LocalizedDescription;\n} & BaseAssetMetadata;\n\n/**\n * Metadata for ERC721 NFTs\n * Asset Type: \"nft\"\n */\nexport type ERC721AssetMetadata = {\n type: 'erc721';\n decimals: 0;\n /** Collection name */\n collectionName?: string;\n /** Collection size */\n collectionSize?: number;\n /** NFT traits/attributes - must be Json-serializable */\n traits?: Record<string, Json>;\n /** Rarity score */\n rarity?: number;\n /** Verification status */\n verified?: boolean;\n} & BaseAssetMetadata;\n\n/**\n * Metadata for ERC1155 multi-tokens\n */\nexport type ERC1155AssetMetadata = {\n type: 'erc1155';\n /** Token URI */\n tokenUri?: string;\n /** Token category */\n category?: string;\n /** Spam detection flag */\n isSpam?: boolean;\n} & BaseAssetMetadata;\n\n/**\n * Union type representing all possible asset metadata types.\n * All types must be JSON-serializable.\n */\nexport type AssetMetadata =\n | FungibleAssetMetadata\n | ERC721AssetMetadata\n | ERC1155AssetMetadata\n | (BaseAssetMetadata & { [key: string]: Json });\n\n// ============================================================================\n// PRICE TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * Base price attributes.\n */\nexport type BaseAssetPrice = {\n /** Current price in selected currency */\n price: number;\n /** Timestamp of last price update */\n lastUpdated: number;\n};\n\n/**\n * Price data for fungible tokens (native, ERC20, SPL)\n * Matches V3SpotPricesResponse from the Price API.\n */\nexport type FungibleAssetPrice = BaseAssetPrice & {\n assetPriceType: 'fungible';\n /** CoinGecko ID */\n id?: string;\n /** Market capitalization */\n marketCap?: number;\n /** All-time high price */\n allTimeHigh?: number;\n /** All-time low price */\n allTimeLow?: number;\n /** 24h trading volume */\n totalVolume?: number;\n /** 24h high price */\n high1d?: number;\n /** 24h low price */\n low1d?: number;\n /** Circulating supply */\n circulatingSupply?: number;\n /** Fully diluted market cap */\n dilutedMarketCap?: number;\n /** 24h market cap change percentage */\n marketCapPercentChange1d?: number;\n /** 24h price change in USD */\n priceChange1d?: number;\n /** 5m price change percentage */\n pricePercentChange5m?: number;\n /** 1h price change percentage */\n pricePercentChange1h?: number;\n /** 4h price change percentage */\n pricePercentChange4h?: number;\n /** 24h price change percentage */\n pricePercentChange1d?: number;\n /** 7d price change percentage */\n pricePercentChange7d?: number;\n /** 14d price change percentage */\n pricePercentChange14d?: number;\n /** 30d price change percentage */\n pricePercentChange30d?: number;\n /** 200d price change percentage */\n pricePercentChange200d?: number;\n /** 1y price change percentage */\n pricePercentChange1y?: number;\n /** Current price in USD */\n usdPrice: number;\n /**\n * True when this asset can stream on `market-stats.v1`.\n * Absent or false keeps the asset on the `/v3/spot-prices` poll.\n */\n wssSupport?: boolean;\n};\n\n/**\n * Price data for NFT collections\n */\nexport type NFTAssetPrice = BaseAssetPrice & {\n assetPriceType: 'nft';\n /** Floor price */\n floorPrice?: number;\n /** Last sale price */\n lastSalePrice?: number;\n /** Collection trading volume */\n collectionVolume?: number;\n /** Average price */\n averagePrice?: number;\n /** Number of sales in 24h */\n sales24h?: number;\n};\n\n/**\n * Union type representing all possible asset price types.\n * All types must be JSON-serializable.\n */\nexport type AssetPrice = FungibleAssetPrice | NFTAssetPrice;\n\n// ============================================================================\n// BALANCE TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * Balance data for fungible tokens (native, ERC20, SPL).\n */\nexport type FungibleAssetBalance = {\n /** Converted balance amount (e.g., \"1000\" for 1000 USDC) */\n amount: string;\n /**\n * Network-specific balance fields, when the source provides them. Stellar\n * native rows carry `spendableBalance` / `minimumReserveBalance`, and\n * trustlines carry `limit` / `authorized` / `sponsored`.\n */\n metadata?: Json;\n};\n\n/**\n * Balance data for ERC721 NFTs.\n * Each tokenId has its own CAIP-19 asset ID, so always \"1\".\n */\nexport type ERC721AssetBalance = {\n /** Always \"1\" for ERC721 (non-fungible) */\n amount: '1';\n};\n\n/**\n * Balance data for ERC1155 multi-tokens.\n */\nexport type ERC1155AssetBalance = {\n /** Quantity owned of this specific tokenId */\n amount: string;\n};\n\n/**\n * Union type representing all possible asset balance types.\n * All types must be JSON-serializable.\n */\nexport type AssetBalance =\n | FungibleAssetBalance\n | ERC721AssetBalance\n | ERC1155AssetBalance\n | { amount: string; [key: string]: Json };\n\n// ============================================================================\n// DATA SOURCE TYPES\n// ============================================================================\n\n/**\n * Data type dimension - what kind of data\n */\nexport type DataType = 'balance' | 'metadata' | 'price';\n\n/**\n * Account with its supported chains (enabled chains ∩ account scope).\n * Pre-computed by the controller so data sources do not need to implement\n * account-scope logic; they iterate over supportedChains for each account.\n */\nexport type AccountWithSupportedChains = {\n account: InternalAccount;\n supportedChains: ChainId[];\n};\n\n/**\n * Request for data from data sources\n */\nexport type DataRequest = {\n /** Accounts with their supported chains (enabled ∩ account scope). Data sources use this instead of computing accountSupportsChain. */\n accountsWithSupportedChains: AccountWithSupportedChains[];\n /** CAIP-2 chain IDs (union of chains in this request) */\n chainIds: ChainId[];\n /** Filter by asset types */\n assetTypes?: AssetType[];\n /** Which data to fetch */\n dataTypes: DataType[];\n /**\n * Optional scoped CAIP-19 asset IDs for this fetch (not the full pin list).\n * v5 force-update and v5 RPC fallback put pins here. v6 omits it: natives,\n * pins, and default tracked assets are read from controller state as\n * `includeAssetIds`; detected ERC-20 balances come back with the chain\n * snapshot. RPC fallback additionally refetches existing balances.\n */\n customAssets?: Caip19AssetId[];\n /** Force fresh fetch, bypass cache */\n forceUpdate?: boolean;\n /**\n * Bypass server-side HTTP caches in addition to the client-side ones that\n * `forceUpdate` already skips. Data sources backed by cached HTTP APIs\n * (e.g. the Accounts API with its 60s cache) append a random `bypassServerCache`\n * query param so the server re-reads instead of replaying a stale snapshot.\n * Use sparingly — e.g. right after a transaction confirms.\n */\n bypassServerCache?: boolean;\n /** Hint for polling interval (ms) - used by data sources that implement polling */\n updateInterval?: number;\n};\n\n/**\n * Response from data sources\n */\nexport type DataResponse = {\n /** Metadata for assets (shared across accounts) */\n assetsInfo?: Record<Caip19AssetId, AssetMetadata>;\n /** Price data for assets (shared across accounts) */\n assetsPrice?: Record<Caip19AssetId, AssetPrice>;\n /** Balance data per account */\n assetsBalance?: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;\n /** Errors encountered, keyed by chain ID (chain-axis fallback + telemetry) */\n errors?: Record<ChainId, string>;\n /**\n * How to apply this response to state. See {@link AssetsUpdateMode}.\n * Defaults to `'merge'` if omitted.\n */\n updateMode?: AssetsUpdateMode;\n /**\n * When set with `updateMode: 'merge'`, balances on chains present in\n * `assetsBalance` replace the prior chain slice (stale tokens on those chains\n * are dropped). Custom assets on covered chains are preserved. Used for\n * Accounts API v5 `getAssets({ forceUpdate: true })`. Accounts API v6 uses\n * `updateMode: 'full'` instead.\n */\n replaceCoveredChainBalances?: boolean;\n};\n\n/**\n * Type of {@link DataResponse.updateMode}: how the controller applies the response to state.\n *\n * - **full**: Response is the full set for covered chains (those present in\n * `assetsBalance`). Assets in state on those chains but not in the response\n * are cleared, including custom assets (Accounts API v6 returns pins via\n * `includeAssetIds`). A chain the source could not answer in full is reported\n * in `errors` and left out of `assetsBalance` entirely, so it is never\n * covered. Use for Accounts API v6 and RpcDataSource v6 snapshots.\n * - **merge**: Only assets present in the response are updated; nothing is\n * removed, unless {@link DataResponse.replaceCoveredChainBalances} is set\n * (Accounts API v5 force refresh). Metadata and prices from the response\n * are applied. Use for event-driven updates and Accounts API v5.\n */\nexport type AssetsUpdateMode = 'full' | 'merge';\n\nexport type AssetsLoadingStatus = 'loading' | 'loaded';\n\n// ============================================================================\n// DATA SOURCE <-> CONTROLLER (DIRECT CALLS, NO MESSENGER PER SOURCE)\n// ============================================================================\n\n/**\n * Callbacks for data sources to report to AssetsController.\n * Passed to data sources so they report by direct call instead of messenger.\n */\nexport type AssetsControllerReport = {\n onActiveChainsUpdate: (dataSourceId: string, activeChains: ChainId[]) => void;\n onAssetsUpdate: (response: DataResponse, sourceId: string) => Promise<void>;\n};\n\n/** Request passed from controller to data source when subscribing */\nexport type DataSourceSubscriptionRequest = {\n request: DataRequest;\n subscriptionId: string;\n isUpdate: boolean;\n};\n\n/**\n * Interface for balance data sources that the controller calls directly.\n * No messenger is required for controller <-> data source communication.\n */\nexport type BalanceDataSource = {\n getAssetsMiddleware: () => Middleware;\n subscribe: (request: DataSourceSubscriptionRequest) => Promise<void>;\n unsubscribe: (subscriptionId: string) => Promise<void>;\n getName: () => string;\n};\n\n/**\n * Interface for the price data source (subscribe/unsubscribe + middleware).\n * Controller calls these methods directly.\n */\nexport type PriceDataSourceInterface = {\n getAssetsMiddleware: () => Middleware;\n subscribe: (request: DataSourceSubscriptionRequest) => Promise<void>;\n unsubscribe: (subscriptionId: string) => Promise<void>;\n};\n\n/**\n * Middleware-only source (e.g. detection, token enrichment).\n * Controller calls getAssetsMiddleware() directly.\n */\nexport type MiddlewareDataSource = {\n getAssetsMiddleware: () => Middleware;\n};\n\n// ============================================================================\n// CONTROLLER STATE\n// ============================================================================\n\n/**\n * State structure for AssetsController following normalized design.\n *\n * All values must stay JSON-serializable. UI preferences (e.g. hidden) live in\n * assetPreferences, not in metadata.\n *\n * Keys use CAIP identifiers:\n * - assetsInfo keys: CAIP-19 asset IDs (e.g., \"eip155:1/erc20:0x...\")\n * - assetsBalance outer keys: Account IDs (InternalAccount.id UUIDs)\n * - assetsBalance inner keys: CAIP-19 asset IDs\n * - assetsPrice keys: CAIP-19 asset IDs\n * - customAssets outer keys: Account IDs (InternalAccount.id UUIDs)\n * - customAssets inner values: CAIP-19 asset IDs array\n * - assetPreferences keys: CAIP-19 asset IDs\n */\nexport type AssetsControllerState = {\n /** Shared metadata for all assets (stored once per asset) */\n assetsInfo: Record<Caip19AssetId, AssetMetadata>;\n /** Per-account balance data */\n assetsBalance: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;\n /** Price data for assets */\n assetsPrice: Record<Caip19AssetId, AssetPrice>;\n /** Custom assets added by users per account */\n customAssets: Record<AccountId, Caip19AssetId[]>;\n /** UI preferences per asset (e.g. hidden) - separate from metadata */\n assetPreferences: Record<Caip19AssetId, AssetPreferences>;\n /** Currently-active ISO 4217 currency code */\n selectedCurrency: SupportedCurrency;\n assetsLoadingStatus?: Record<AccountId, AssetsLoadingStatus>;\n /**\n * Per-account status of the background (Snap + RPC) fetch that runs after\n * the initial balance has resolved. Tracked on every forced fetch.\n */\n assetsBackgroundLoadingStatus?: Record<AccountId, AssetsLoadingStatus>;\n};\n\n// ============================================================================\n// UNIFIED MIDDLEWARE TYPES\n// ============================================================================\n\n/**\n * Base context for all middleware operations.\n * Contains the common interface shared by fetch and subscribe.\n */\nexport type Context = {\n /** The data request */\n request: DataRequest;\n /** The response data (mutated by middlewares) */\n response: DataResponse;\n /**\n * Optional breakdown of latency (ms) per data source, e.g. from parallel\n * middlewares. Keys are source names (often \"MiddlewareName.SourceName\").\n * Merged into the controller's durationByDataSource for tracing.\n */\n durationByDataSource?: Record<string, number>;\n};\n\n/**\n * Next function for middleware chain\n */\nexport type NextFunction = (context: Context) => Promise<Context>;\n\n/**\n * Middleware function - works for both fetch and subscribe operations.\n */\nexport type Middleware = (\n context: Context,\n next: NextFunction,\n) => Promise<Context>;\n\n/**\n * An assets data source: any object that can participate in the assets\n * middleware chain with a display name (e.g. for tracing). Used by\n * createParallelMiddleware and by the controller when executing the chain.\n */\nexport type AssetsDataSource = {\n getName(): string;\n assetsMiddleware: Middleware;\n};\n\n/**\n * Wraps a middleware to only execute if specific dataTypes are requested.\n *\n * @param dataTypes - DataTypes that must be in the request for middleware to run\n * @param middleware - The middleware to conditionally execute\n * @returns A middleware that skips execution if none of the dataTypes are requested\n *\n * @example\n * ```typescript\n * // Only runs for metadata requests\n * const metadataMiddleware = forDataTypes(['metadata'], async (ctx, next) => {\n * const result = await next(ctx);\n * // Enrich metadata...\n * return result;\n * });\n *\n * // Runs for balance or price requests\n * const balanceOrPriceMiddleware = forDataTypes(['balance', 'price'], async (ctx, next) => {\n * const result = await next(ctx);\n * // Process balances or prices...\n * return result;\n * });\n * ```\n */\nexport function forDataTypes(\n dataTypes: DataType[],\n middleware: Middleware,\n): Middleware {\n return async (ctx, next) => {\n const requestedTypes = ctx.request.dataTypes;\n const shouldRun = dataTypes.some((dt) => requestedTypes.includes(dt));\n\n if (!shouldRun) {\n return next(ctx);\n }\n\n return middleware(ctx, next);\n };\n}\n\n/**\n * Context for fetch operations.\n * Extends base Context - no additional fields needed for fetch.\n */\nexport type FetchContext = Context;\n\n// Legacy aliases for backwards compatibility\nexport type FetchNextFunction = NextFunction;\nexport type FetchMiddleware = Middleware;\n\n/**\n * Subscription response returned when subscribing to asset updates.\n */\nexport type SubscriptionResponse = {\n /** Chains actively subscribed */\n chains: ChainId[];\n /** Account ID being watched */\n accountId: AccountId;\n /** Asset types being watched */\n assetTypes: AssetType[];\n /** Data types being kept fresh */\n dataTypes: DataType[];\n /** Cleanup function */\n unsubscribe: () => void;\n};\n\n// ============================================================================\n// COMBINED ASSET TYPE (for UI)\n// ============================================================================\n\n/**\n * Combined asset type matching state structure: balance, metadata, price\n */\nexport type Asset = {\n /** CAIP-19 asset ID */\n id: Caip19AssetId;\n /** CAIP-2 chain ID (extracted from id) */\n chainId: ChainId;\n /** Balance data */\n balance: AssetBalance;\n /** Metadata (symbol, name, decimals, etc.) */\n metadata: AssetMetadata;\n /** Price data */\n price: AssetPrice;\n /** Computed fiat value (balance × price) */\n fiatValue: number;\n};\n\n// ============================================================================\n// EVENT TYPES\n// ============================================================================\n\n/**\n * Event emitted when balances change\n */\nexport type BalanceChangeEvent = {\n accountId: AccountId;\n assetId: Caip19AssetId;\n previousAmount: string;\n newAmount: string;\n timestamp: number;\n};\n\n/**\n * Event emitted when prices change\n */\nexport type PriceChangeEvent = {\n assetIds: Caip19AssetId[];\n timestamp: number;\n};\n\n/**\n * Event emitted when metadata changes\n */\nexport type MetadataChangeEvent = {\n assetId: Caip19AssetId;\n changes: Partial<AssetMetadata>;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAoiBA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,YAAY,CAC1B,SAAqB,EACrB,UAAsB;IAEtB,OAAO,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACzB,MAAM,cAAc,GAAG,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC;QAC7C,MAAM,SAAS,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;QAEtE,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;QACnB,CAAC;QAED,OAAO,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { SupportedCurrency } from '@metamask/core-backend';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { CaipAssetType, CaipChainId, Json } from '@metamask/utils';\n\n/**\n * CAIP-19 compliant asset identifier\n * Format: \"{chainId}/{assetNamespace}:{assetReference}[/tokenId]\"\n *\n * Examples:\n * - Native: \"eip155:1/slip44:60\" (ETH)\n * - ERC20: \"eip155:1/erc20:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\" (USDC)\n * - ERC721: \"eip155:1/erc721:0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D/1234\" (BAYC #1234)\n * - SPL: \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\"\n */\nexport type Caip19AssetId = CaipAssetType;\n\n/**\n * InternalAccount UUID from AccountsController\n * Not the blockchain address!\n */\nexport type AccountId = string;\n\n/**\n * CAIP-2 chain identifier\n */\nexport type ChainId = CaipChainId;\n\n// ============================================================================\n// ASSET TYPES - Defined by metadata structure\n// ============================================================================\n\n/**\n * Asset types define the metadata structure, not blockchain implementation.\n * - \"fungible\" includes: native, erc20, spl - all share balance, symbol, decimals\n * - \"nft\" includes: erc721, erc1155 - include tokenId, image, attributes\n */\nexport type AssetType = 'fungible' | 'nft' | 'collectible';\n\n/**\n * Token standards - blockchain implementation details\n */\nexport type TokenStandard =\n | 'native'\n | 'erc20'\n | 'erc721'\n | 'erc1155'\n | 'spl'\n | string;\n\n// ============================================================================\n// METADATA TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * UI preferences for an asset (stored in assetPreferences state, not in metadata).\n */\nexport type AssetPreferences = {\n /** Whether the asset is hidden from display */\n hidden?: boolean;\n};\n\n/**\n * Base metadata attributes shared by ALL asset types.\n */\nexport type BaseAssetMetadata = {\n /** Token standard - how it's implemented on the blockchain */\n type: TokenStandard;\n /** Display symbol (e.g., \"ETH\", \"USDC\") */\n symbol: string;\n /** Full name (e.g., \"Ethereum\", \"USD Coin\") */\n name: string;\n /** Token decimals (18 for ETH, 6 for USDC, etc.) */\n decimals: number;\n /** Logo URL or data URI */\n image?: string;\n};\n\n// ============================================================================\n// TOKEN CONTRACT DATA TYPES\n// ============================================================================\n\n/** Fee information for token transfers */\nexport type TokenFees = {\n avgFee: number;\n maxFee: number;\n minFee: number;\n};\n\n/** Honeypot detection status */\nexport type HoneypotStatus = {\n honeypotIs: boolean;\n goPlus?: boolean;\n};\n\n/** Storage slot information for the contract */\nexport type StorageSlots = {\n balance: number;\n approval: number;\n};\n\n/** Localized description */\nexport type LocalizedDescription = {\n en: string;\n};\n\n// ============================================================================\n// ASSET METADATA TYPES\n// ============================================================================\n\n/**\n * Metadata for fungible tokens.\n * Structure mirrors V3AssetResponse from the Tokens API.\n *\n * Differences from V3AssetResponse:\n * - `type` is derived from assetId namespace (not in API response)\n * - `image` maps from API's `iconUrl`\n * - `assetId` is not stored (used as the key)\n */\nexport type FungibleAssetMetadata = {\n /** Token type derived from assetId namespace */\n type: 'native' | 'erc20' | 'spl';\n /** CoinGecko ID for price lookups */\n coingeckoId?: string;\n /** Number of token list occurrences */\n occurrences?: number;\n /** DEX/aggregator integrations */\n aggregators?: string[];\n /** Asset labels/tags (e.g., \"stable_coin\") */\n labels?: string[];\n /** Whether the token supports ERC-20 permit */\n erc20Permit?: boolean;\n /** Fee information for token transfers */\n fees?: TokenFees;\n /** Honeypot detection status */\n honeypotStatus?: HoneypotStatus;\n /** Storage slot information for the contract */\n storage?: StorageSlots;\n /** Whether the contract is verified */\n isContractVerified?: boolean;\n /** Localized description */\n description?: LocalizedDescription;\n} & BaseAssetMetadata;\n\n/**\n * Metadata for ERC721 NFTs\n * Asset Type: \"nft\"\n */\nexport type ERC721AssetMetadata = {\n type: 'erc721';\n decimals: 0;\n /** Collection name */\n collectionName?: string;\n /** Collection size */\n collectionSize?: number;\n /** NFT traits/attributes - must be Json-serializable */\n traits?: Record<string, Json>;\n /** Rarity score */\n rarity?: number;\n /** Verification status */\n verified?: boolean;\n} & BaseAssetMetadata;\n\n/**\n * Metadata for ERC1155 multi-tokens\n */\nexport type ERC1155AssetMetadata = {\n type: 'erc1155';\n /** Token URI */\n tokenUri?: string;\n /** Token category */\n category?: string;\n /** Spam detection flag */\n isSpam?: boolean;\n} & BaseAssetMetadata;\n\n/**\n * Union type representing all possible asset metadata types.\n * All types must be JSON-serializable.\n */\nexport type AssetMetadata =\n | FungibleAssetMetadata\n | ERC721AssetMetadata\n | ERC1155AssetMetadata\n | (BaseAssetMetadata & { [key: string]: Json });\n\n// ============================================================================\n// PRICE TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * Base price attributes.\n */\nexport type BaseAssetPrice = {\n /** Current price in selected currency */\n price: number;\n /** Timestamp of last price update */\n lastUpdated: number;\n};\n\n/**\n * Price data for fungible tokens (native, ERC20, SPL)\n * Matches V3SpotPricesResponse from the Price API.\n */\nexport type FungibleAssetPrice = BaseAssetPrice & {\n assetPriceType: 'fungible';\n /** CoinGecko ID */\n id?: string;\n /** Market capitalization */\n marketCap?: number;\n /** All-time high price */\n allTimeHigh?: number;\n /** All-time low price */\n allTimeLow?: number;\n /** 24h trading volume */\n totalVolume?: number;\n /** 24h high price */\n high1d?: number;\n /** 24h low price */\n low1d?: number;\n /** Circulating supply */\n circulatingSupply?: number;\n /** Fully diluted market cap */\n dilutedMarketCap?: number;\n /** 24h market cap change percentage */\n marketCapPercentChange1d?: number;\n /** 24h price change in USD */\n priceChange1d?: number;\n /** 5m price change percentage */\n pricePercentChange5m?: number;\n /** 1h price change percentage */\n pricePercentChange1h?: number;\n /** 4h price change percentage */\n pricePercentChange4h?: number;\n /** 24h price change percentage */\n pricePercentChange1d?: number;\n /** 7d price change percentage */\n pricePercentChange7d?: number;\n /** 14d price change percentage */\n pricePercentChange14d?: number;\n /** 30d price change percentage */\n pricePercentChange30d?: number;\n /** 200d price change percentage */\n pricePercentChange200d?: number;\n /** 1y price change percentage */\n pricePercentChange1y?: number;\n /** Current price in USD */\n usdPrice: number;\n};\n\n/**\n * Price data for NFT collections\n */\nexport type NFTAssetPrice = BaseAssetPrice & {\n assetPriceType: 'nft';\n /** Floor price */\n floorPrice?: number;\n /** Last sale price */\n lastSalePrice?: number;\n /** Collection trading volume */\n collectionVolume?: number;\n /** Average price */\n averagePrice?: number;\n /** Number of sales in 24h */\n sales24h?: number;\n};\n\n/**\n * Union type representing all possible asset price types.\n * All types must be JSON-serializable.\n */\nexport type AssetPrice = FungibleAssetPrice | NFTAssetPrice;\n\n// ============================================================================\n// BALANCE TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * Balance data for fungible tokens (native, ERC20, SPL).\n */\nexport type FungibleAssetBalance = {\n /** Converted balance amount (e.g., \"1000\" for 1000 USDC) */\n amount: string;\n /**\n * Network-specific balance fields, when the source provides them. Stellar\n * native rows carry `spendableBalance` / `minimumReserveBalance`, and\n * trustlines carry `limit` / `authorized` / `sponsored`.\n */\n metadata?: Json;\n};\n\n/**\n * Balance data for ERC721 NFTs.\n * Each tokenId has its own CAIP-19 asset ID, so always \"1\".\n */\nexport type ERC721AssetBalance = {\n /** Always \"1\" for ERC721 (non-fungible) */\n amount: '1';\n};\n\n/**\n * Balance data for ERC1155 multi-tokens.\n */\nexport type ERC1155AssetBalance = {\n /** Quantity owned of this specific tokenId */\n amount: string;\n};\n\n/**\n * Union type representing all possible asset balance types.\n * All types must be JSON-serializable.\n */\nexport type AssetBalance =\n | FungibleAssetBalance\n | ERC721AssetBalance\n | ERC1155AssetBalance\n | { amount: string; [key: string]: Json };\n\n// ============================================================================\n// DATA SOURCE TYPES\n// ============================================================================\n\n/**\n * Data type dimension - what kind of data\n */\nexport type DataType = 'balance' | 'metadata' | 'price';\n\n/**\n * Account with its supported chains (enabled chains ∩ account scope).\n * Pre-computed by the controller so data sources do not need to implement\n * account-scope logic; they iterate over supportedChains for each account.\n */\nexport type AccountWithSupportedChains = {\n account: InternalAccount;\n supportedChains: ChainId[];\n};\n\n/**\n * Request for data from data sources\n */\nexport type DataRequest = {\n /** Accounts with their supported chains (enabled ∩ account scope). Data sources use this instead of computing accountSupportsChain. */\n accountsWithSupportedChains: AccountWithSupportedChains[];\n /** CAIP-2 chain IDs (union of chains in this request) */\n chainIds: ChainId[];\n /** Filter by asset types */\n assetTypes?: AssetType[];\n /** Which data to fetch */\n dataTypes: DataType[];\n /**\n * Optional scoped CAIP-19 asset IDs for this fetch (not the full pin list).\n * v5 force-update and v5 RPC fallback put pins here. v6 omits it: natives,\n * pins, and default tracked assets are read from controller state as\n * `includeAssetIds`; detected ERC-20 balances come back with the chain\n * snapshot. RPC fallback additionally refetches existing balances.\n */\n customAssets?: Caip19AssetId[];\n /** Force fresh fetch, bypass cache */\n forceUpdate?: boolean;\n /**\n * Bypass server-side HTTP caches in addition to the client-side ones that\n * `forceUpdate` already skips. Data sources backed by cached HTTP APIs\n * (e.g. the Accounts API with its 60s cache) append a random `bypassServerCache`\n * query param so the server re-reads instead of replaying a stale snapshot.\n * Use sparingly — e.g. right after a transaction confirms.\n */\n bypassServerCache?: boolean;\n /** Hint for polling interval (ms) - used by data sources that implement polling */\n updateInterval?: number;\n};\n\n/**\n * Response from data sources\n */\nexport type DataResponse = {\n /** Metadata for assets (shared across accounts) */\n assetsInfo?: Record<Caip19AssetId, AssetMetadata>;\n /** Price data for assets (shared across accounts) */\n assetsPrice?: Record<Caip19AssetId, AssetPrice>;\n /** Balance data per account */\n assetsBalance?: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;\n /** Errors encountered, keyed by chain ID (chain-axis fallback + telemetry) */\n errors?: Record<ChainId, string>;\n /**\n * How to apply this response to state. See {@link AssetsUpdateMode}.\n * Defaults to `'merge'` if omitted.\n */\n updateMode?: AssetsUpdateMode;\n /**\n * When set with `updateMode: 'merge'`, balances on chains present in\n * `assetsBalance` replace the prior chain slice (stale tokens on those chains\n * are dropped). Custom assets on covered chains are preserved. Used for\n * Accounts API v5 `getAssets({ forceUpdate: true })`. Accounts API v6 uses\n * `updateMode: 'full'` instead.\n */\n replaceCoveredChainBalances?: boolean;\n};\n\n/**\n * Type of {@link DataResponse.updateMode}: how the controller applies the response to state.\n *\n * - **full**: Response is the full set for covered chains (those present in\n * `assetsBalance`). Assets in state on those chains but not in the response\n * are cleared, including custom assets (Accounts API v6 returns pins via\n * `includeAssetIds`). A chain the source could not answer in full is reported\n * in `errors` and left out of `assetsBalance` entirely, so it is never\n * covered. Use for Accounts API v6 and RpcDataSource v6 snapshots.\n * - **merge**: Only assets present in the response are updated; nothing is\n * removed, unless {@link DataResponse.replaceCoveredChainBalances} is set\n * (Accounts API v5 force refresh). Metadata and prices from the response\n * are applied. Use for event-driven updates and Accounts API v5.\n */\nexport type AssetsUpdateMode = 'full' | 'merge';\n\nexport type AssetsLoadingStatus = 'loading' | 'loaded';\n\n// ============================================================================\n// DATA SOURCE <-> CONTROLLER (DIRECT CALLS, NO MESSENGER PER SOURCE)\n// ============================================================================\n\n/**\n * Callbacks for data sources to report to AssetsController.\n * Passed to data sources so they report by direct call instead of messenger.\n */\nexport type AssetsControllerReport = {\n onActiveChainsUpdate: (dataSourceId: string, activeChains: ChainId[]) => void;\n onAssetsUpdate: (response: DataResponse, sourceId: string) => Promise<void>;\n};\n\n/** Request passed from controller to data source when subscribing */\nexport type DataSourceSubscriptionRequest = {\n request: DataRequest;\n subscriptionId: string;\n isUpdate: boolean;\n};\n\n/**\n * Interface for balance data sources that the controller calls directly.\n * No messenger is required for controller <-> data source communication.\n */\nexport type BalanceDataSource = {\n getAssetsMiddleware: () => Middleware;\n subscribe: (request: DataSourceSubscriptionRequest) => Promise<void>;\n unsubscribe: (subscriptionId: string) => Promise<void>;\n getName: () => string;\n};\n\n/**\n * Interface for the price data source (subscribe/unsubscribe + middleware).\n * Controller calls these methods directly.\n */\nexport type PriceDataSourceInterface = {\n getAssetsMiddleware: () => Middleware;\n subscribe: (request: DataSourceSubscriptionRequest) => Promise<void>;\n unsubscribe: (subscriptionId: string) => Promise<void>;\n};\n\n/**\n * Middleware-only source (e.g. detection, token enrichment).\n * Controller calls getAssetsMiddleware() directly.\n */\nexport type MiddlewareDataSource = {\n getAssetsMiddleware: () => Middleware;\n};\n\n// ============================================================================\n// CONTROLLER STATE\n// ============================================================================\n\n/**\n * State structure for AssetsController following normalized design.\n *\n * All values must stay JSON-serializable. UI preferences (e.g. hidden) live in\n * assetPreferences, not in metadata.\n *\n * Keys use CAIP identifiers:\n * - assetsInfo keys: CAIP-19 asset IDs (e.g., \"eip155:1/erc20:0x...\")\n * - assetsBalance outer keys: Account IDs (InternalAccount.id UUIDs)\n * - assetsBalance inner keys: CAIP-19 asset IDs\n * - assetsPrice keys: CAIP-19 asset IDs\n * - customAssets outer keys: Account IDs (InternalAccount.id UUIDs)\n * - customAssets inner values: CAIP-19 asset IDs array\n * - assetPreferences keys: CAIP-19 asset IDs\n */\nexport type AssetsControllerState = {\n /** Shared metadata for all assets (stored once per asset) */\n assetsInfo: Record<Caip19AssetId, AssetMetadata>;\n /** Per-account balance data */\n assetsBalance: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;\n /** Price data for assets */\n assetsPrice: Record<Caip19AssetId, AssetPrice>;\n /** Custom assets added by users per account */\n customAssets: Record<AccountId, Caip19AssetId[]>;\n /** UI preferences per asset (e.g. hidden) - separate from metadata */\n assetPreferences: Record<Caip19AssetId, AssetPreferences>;\n /** Currently-active ISO 4217 currency code */\n selectedCurrency: SupportedCurrency;\n assetsLoadingStatus?: Record<AccountId, AssetsLoadingStatus>;\n /**\n * Per-account status of the background (Snap + RPC) fetch that runs after\n * the initial balance has resolved. Tracked on every forced fetch.\n */\n assetsBackgroundLoadingStatus?: Record<AccountId, AssetsLoadingStatus>;\n};\n\n// ============================================================================\n// UNIFIED MIDDLEWARE TYPES\n// ============================================================================\n\n/**\n * Base context for all middleware operations.\n * Contains the common interface shared by fetch and subscribe.\n */\nexport type Context = {\n /** The data request */\n request: DataRequest;\n /** The response data (mutated by middlewares) */\n response: DataResponse;\n /**\n * Optional breakdown of latency (ms) per data source, e.g. from parallel\n * middlewares. Keys are source names (often \"MiddlewareName.SourceName\").\n * Merged into the controller's durationByDataSource for tracing.\n */\n durationByDataSource?: Record<string, number>;\n};\n\n/**\n * Next function for middleware chain\n */\nexport type NextFunction = (context: Context) => Promise<Context>;\n\n/**\n * Middleware function - works for both fetch and subscribe operations.\n */\nexport type Middleware = (\n context: Context,\n next: NextFunction,\n) => Promise<Context>;\n\n/**\n * An assets data source: any object that can participate in the assets\n * middleware chain with a display name (e.g. for tracing). Used by\n * createParallelMiddleware and by the controller when executing the chain.\n */\nexport type AssetsDataSource = {\n getName(): string;\n assetsMiddleware: Middleware;\n};\n\n/**\n * Wraps a middleware to only execute if specific dataTypes are requested.\n *\n * @param dataTypes - DataTypes that must be in the request for middleware to run\n * @param middleware - The middleware to conditionally execute\n * @returns A middleware that skips execution if none of the dataTypes are requested\n *\n * @example\n * ```typescript\n * // Only runs for metadata requests\n * const metadataMiddleware = forDataTypes(['metadata'], async (ctx, next) => {\n * const result = await next(ctx);\n * // Enrich metadata...\n * return result;\n * });\n *\n * // Runs for balance or price requests\n * const balanceOrPriceMiddleware = forDataTypes(['balance', 'price'], async (ctx, next) => {\n * const result = await next(ctx);\n * // Process balances or prices...\n * return result;\n * });\n * ```\n */\nexport function forDataTypes(\n dataTypes: DataType[],\n middleware: Middleware,\n): Middleware {\n return async (ctx, next) => {\n const requestedTypes = ctx.request.dataTypes;\n const shouldRun = dataTypes.some((dt) => requestedTypes.includes(dt));\n\n if (!shouldRun) {\n return next(ctx);\n }\n\n return middleware(ctx, next);\n };\n}\n\n/**\n * Context for fetch operations.\n * Extends base Context - no additional fields needed for fetch.\n */\nexport type FetchContext = Context;\n\n// Legacy aliases for backwards compatibility\nexport type FetchNextFunction = NextFunction;\nexport type FetchMiddleware = Middleware;\n\n/**\n * Subscription response returned when subscribing to asset updates.\n */\nexport type SubscriptionResponse = {\n /** Chains actively subscribed */\n chains: ChainId[];\n /** Account ID being watched */\n accountId: AccountId;\n /** Asset types being watched */\n assetTypes: AssetType[];\n /** Data types being kept fresh */\n dataTypes: DataType[];\n /** Cleanup function */\n unsubscribe: () => void;\n};\n\n// ============================================================================\n// COMBINED ASSET TYPE (for UI)\n// ============================================================================\n\n/**\n * Combined asset type matching state structure: balance, metadata, price\n */\nexport type Asset = {\n /** CAIP-19 asset ID */\n id: Caip19AssetId;\n /** CAIP-2 chain ID (extracted from id) */\n chainId: ChainId;\n /** Balance data */\n balance: AssetBalance;\n /** Metadata (symbol, name, decimals, etc.) */\n metadata: AssetMetadata;\n /** Price data */\n price: AssetPrice;\n /** Computed fiat value (balance × price) */\n fiatValue: number;\n};\n\n// ============================================================================\n// EVENT TYPES\n// ============================================================================\n\n/**\n * Event emitted when balances change\n */\nexport type BalanceChangeEvent = {\n accountId: AccountId;\n assetId: Caip19AssetId;\n previousAmount: string;\n newAmount: string;\n timestamp: number;\n};\n\n/**\n * Event emitted when prices change\n */\nexport type PriceChangeEvent = {\n assetIds: Caip19AssetId[];\n timestamp: number;\n};\n\n/**\n * Event emitted when metadata changes\n */\nexport type MetadataChangeEvent = {\n assetId: Caip19AssetId;\n changes: Partial<AssetMetadata>;\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Subscribes the price-fetch set when the Price API marks it `wssSupport`.
|
|
3
|
-
*
|
|
4
|
-
* That set is balances and custom assets on the selected accounts and chains,
|
|
5
|
-
* minus hidden assets. Open channels live on MarketStatsService. The price
|
|
6
|
-
* poll is unchanged: it still fetches every tracked asset. This stream only
|
|
7
|
-
* adds the socket subscription. When MarketStatsService is not wired, the
|
|
8
|
-
* poll is the only price source.
|
|
9
|
-
*/
|
|
10
|
-
import type { MarketStatsServiceActions, MarketStatsServiceChainStatusChangedEvent, SupportedCurrency } from '@metamask/core-backend';
|
|
11
|
-
import type { Messenger } from '@metamask/messenger';
|
|
12
|
-
import type { Caip19AssetId } from '../types.js';
|
|
13
|
-
export type MarketStatsPriceStreamMessenger = Messenger<string, MarketStatsServiceActions, MarketStatsServiceChainStatusChangedEvent>;
|
|
14
|
-
export type StreamCandidate = {
|
|
15
|
-
assetId: Caip19AssetId;
|
|
16
|
-
wssSupport: boolean;
|
|
17
|
-
};
|
|
18
|
-
export type MarketStatsPriceStreamOptions = {
|
|
19
|
-
messenger: MarketStatsPriceStreamMessenger;
|
|
20
|
-
getSelectedCurrency: () => SupportedCurrency;
|
|
21
|
-
};
|
|
22
|
-
/**
|
|
23
|
-
* Read `wssSupport` off a spot-price entry.
|
|
24
|
-
*
|
|
25
|
-
* @param data - One asset's `/v3/spot-prices` entry.
|
|
26
|
-
* @returns Whether the asset can stream.
|
|
27
|
-
*/
|
|
28
|
-
export declare function readSpotPriceStreamEligibility(data: object): boolean;
|
|
29
|
-
/**
|
|
30
|
-
* Assets the Price API marks as streamable.
|
|
31
|
-
*
|
|
32
|
-
* @param candidates - Assets learned from the latest spot-price response.
|
|
33
|
-
* @returns Asset ids to subscribe.
|
|
34
|
-
*/
|
|
35
|
-
export declare function selectAssetsToStream(candidates: StreamCandidate[]): Caip19AssetId[];
|
|
36
|
-
/**
|
|
37
|
-
* True when the messenger has no MarketStatsService handler.
|
|
38
|
-
* Price updates then stay on the poll.
|
|
39
|
-
*
|
|
40
|
-
* @param error - Failure from `messenger.call`.
|
|
41
|
-
* @returns Whether streaming cannot be used in this process.
|
|
42
|
-
*/
|
|
43
|
-
export declare function isMarketStatsUnavailable(error: unknown): boolean;
|
|
44
|
-
/**
|
|
45
|
-
* Opens market-stats channels for the price-fetch set.
|
|
46
|
-
*/
|
|
47
|
-
export declare class MarketStatsPriceStream {
|
|
48
|
-
#private;
|
|
49
|
-
constructor(options: MarketStatsPriceStreamOptions);
|
|
50
|
-
/**
|
|
51
|
-
* Subscribe price-fetch assets marked `wssSupport`.
|
|
52
|
-
* Drop channels for assets that left that set.
|
|
53
|
-
*
|
|
54
|
-
* @param candidates - Price-fetch assets in the current subscription scope.
|
|
55
|
-
*/
|
|
56
|
-
reconcile(candidates: StreamCandidate[]): Promise<void>;
|
|
57
|
-
/**
|
|
58
|
-
* Drop one reference on each open channel for a price-fetch asset.
|
|
59
|
-
* Used when the selected currency changes, and when the price subscription ends.
|
|
60
|
-
*/
|
|
61
|
-
releaseSubscriptions(): Promise<void>;
|
|
62
|
-
/**
|
|
63
|
-
* Remove listeners and drop channels this stream opened.
|
|
64
|
-
*/
|
|
65
|
-
destroy(): void;
|
|
66
|
-
}
|
|
67
|
-
//# sourceMappingURL=MarketStatsPriceStream.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"MarketStatsPriceStream.d.ts","sourceRoot":"","sources":["../../src/data-sources/MarketStatsPriceStream.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EACV,yBAAyB,EACzB,yCAAyC,EACzC,iBAAiB,EAClB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAGrD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,MAAM,MAAM,+BAA+B,GAAG,SAAS,CACrD,MAAM,EACN,yBAAyB,EACzB,yCAAyC,CAC1C,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,OAAO,EAAE,aAAa,CAAC;IACvB,UAAU,EAAE,OAAO,CAAC;CACrB,CAAC;AAOF,MAAM,MAAM,6BAA6B,GAAG;IAC1C,SAAS,EAAE,+BAA+B,CAAC;IAC3C,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;CAC9C,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,8BAA8B,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEpE;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAClC,UAAU,EAAE,eAAe,EAAE,GAC5B,aAAa,EAAE,CAIjB;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAMhE;AAUD;;GAEG;AACH,qBAAa,sBAAsB;;IAajC,YAAY,OAAO,EAAE,6BAA6B,EAGjD;IAED;;;;;OAKG;IACG,SAAS,CAAC,UAAU,EAAE,eAAe,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAmD5D;IAED;;;OAGG;IACG,oBAAoB,IAAI,OAAO,CAAC,IAAI,CAAC,CAI1C;IAED;;OAEG;IACH,OAAO,IAAI,IAAI,CAId;CA8DF"}
|