@metamask-previews/assets-controller 21.0.0-preview-2caafa97d → 21.0.0-preview-826c10a
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 +10 -0
- package/README.md +3 -0
- 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 +6 -12
- package/dist/AssetsController.d.ts.map +1 -1
- package/dist/AssetsController.js +21 -16
- package/dist/AssetsController.js.map +1 -1
- package/dist/data-sources/AccountActivityDataSource.d.ts +4 -2
- package/dist/data-sources/AccountActivityDataSource.d.ts.map +1 -1
- package/dist/data-sources/AccountActivityDataSource.js +3 -1
- package/dist/data-sources/AccountActivityDataSource.js.map +1 -1
- package/dist/data-sources/MarketStatsPriceStream.d.ts +67 -0
- package/dist/data-sources/MarketStatsPriceStream.d.ts.map +1 -0
- package/dist/data-sources/MarketStatsPriceStream.js +181 -0
- package/dist/data-sources/MarketStatsPriceStream.js.map +1 -0
- package/dist/data-sources/PriceDataSource.d.ts +32 -5
- package/dist/data-sources/PriceDataSource.d.ts.map +1 -1
- package/dist/data-sources/PriceDataSource.js +133 -91
- 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 +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +5 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
|
@@ -4,6 +4,7 @@ import { DedupingBatchFetcher } from '../utils/dedupingBatchFetcher.js';
|
|
|
4
4
|
import { filterAssetsBySupportedNetworks, getAssetIdsForPriceFetch, getUnpricedResponseAssetIds, isPriceableAsset, } from '../utils/getAssetIdsForPriceFetch.js';
|
|
5
5
|
import { fetchWithTimeout } from '../utils/index.js';
|
|
6
6
|
import { reduceInBatchesSerially } from './evm-rpc-services/index.js';
|
|
7
|
+
import { MarketStatsPriceStream, readSpotPriceStreamEligibility, } from './MarketStatsPriceStream.js';
|
|
7
8
|
// ============================================================================
|
|
8
9
|
// CONSTANTS
|
|
9
10
|
// ============================================================================
|
|
@@ -74,8 +75,13 @@ function isValidMarketData(data) {
|
|
|
74
75
|
* - Fetches prices from Price API v3 spot-prices endpoint
|
|
75
76
|
* - Supports one-time fetch and subscription-based polling
|
|
76
77
|
* - In subscribe mode, uses constructor `getAssetsState` to read assetsBalance and fetch prices
|
|
78
|
+
* - Streams the same assets the price poll tracks, when the spot-price
|
|
79
|
+
* response marks them `wssSupport: true`, on market-stats.v1. The poll
|
|
80
|
+
* itself is the same as before: every tracked asset, on the same interval.
|
|
81
|
+
* Socket ticks are not written into controller state. The UI reads
|
|
82
|
+
* `MarketStatsService:pricesUpdated`.
|
|
77
83
|
*
|
|
78
|
-
* Usage: Create with queryApiClient and getAssetsState; subscribe() polls prices for held assets.
|
|
84
|
+
* Usage: Create with queryApiClient, messenger, and getAssetsState; subscribe() polls prices for held assets.
|
|
79
85
|
*/
|
|
80
86
|
export class PriceDataSource {
|
|
81
87
|
static controllerName = CONTROLLER_NAME;
|
|
@@ -95,14 +101,19 @@ export class PriceDataSource {
|
|
|
95
101
|
*/
|
|
96
102
|
#deduper;
|
|
97
103
|
#getAssetsState;
|
|
98
|
-
|
|
99
|
-
|
|
104
|
+
#marketStats;
|
|
105
|
+
/** The one price poll. The controller keeps a single PriceDataSource subscription. */
|
|
106
|
+
#subscription = null;
|
|
100
107
|
constructor(options) {
|
|
101
108
|
this.#getSelectedCurrency = options.getSelectedCurrency;
|
|
102
109
|
this.#pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL;
|
|
103
110
|
this.#apiClient = options.queryApiClient;
|
|
104
111
|
this.#fetchTimeoutMs = options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
|
|
105
112
|
this.#getAssetsState = options.getAssetsState;
|
|
113
|
+
this.#marketStats = new MarketStatsPriceStream({
|
|
114
|
+
messenger: options.messenger,
|
|
115
|
+
getSelectedCurrency: () => this.#getSelectedCurrency(),
|
|
116
|
+
});
|
|
106
117
|
this.#deduper = new DedupingBatchFetcher({
|
|
107
118
|
fetchBatch: (assetIds) => this.#executeBatchFetch(assetIds),
|
|
108
119
|
freshnessTtlMs: options.priceFreshnessTtlMs ?? this.#pollInterval,
|
|
@@ -182,6 +193,7 @@ export class PriceDataSource {
|
|
|
182
193
|
const selectedCurrencyPrices = await fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
|
|
183
194
|
currency: selectedCurrency,
|
|
184
195
|
includeMarketData: true,
|
|
196
|
+
includeWssSupportField: true,
|
|
185
197
|
}), this.#fetchTimeoutMs);
|
|
186
198
|
return { selectedCurrencyPrices, usdPrices: selectedCurrencyPrices };
|
|
187
199
|
}
|
|
@@ -189,10 +201,12 @@ export class PriceDataSource {
|
|
|
189
201
|
fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
|
|
190
202
|
currency: selectedCurrency,
|
|
191
203
|
includeMarketData: true,
|
|
204
|
+
includeWssSupportField: true,
|
|
192
205
|
}), this.#fetchTimeoutMs),
|
|
193
206
|
fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
|
|
194
207
|
currency: 'usd',
|
|
195
208
|
includeMarketData: true,
|
|
209
|
+
includeWssSupportField: true,
|
|
196
210
|
}), this.#fetchTimeoutMs),
|
|
197
211
|
]);
|
|
198
212
|
return { selectedCurrencyPrices, usdPrices };
|
|
@@ -322,8 +336,18 @@ export class PriceDataSource {
|
|
|
322
336
|
* @returns DataResponse containing asset prices.
|
|
323
337
|
*/
|
|
324
338
|
async fetch(request) {
|
|
325
|
-
const response = {};
|
|
326
339
|
const assetIds = await this.#filterToSupportedPriceableAssets(this.#getAssetIdsFromBalanceState(request));
|
|
340
|
+
return this.#fetchAssetIdList(assetIds);
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Fetch spot prices for an explicit id list. Empty when there is nothing to
|
|
344
|
+
* price or the Price API call fails.
|
|
345
|
+
*
|
|
346
|
+
* @param assetIds - CAIP-19 asset IDs already filtered to priceable assets.
|
|
347
|
+
* @returns DataResponse containing asset prices.
|
|
348
|
+
*/
|
|
349
|
+
async #fetchAssetIdList(assetIds) {
|
|
350
|
+
const response = {};
|
|
327
351
|
if (assetIds.length === 0) {
|
|
328
352
|
return response;
|
|
329
353
|
}
|
|
@@ -344,99 +368,78 @@ export class PriceDataSource {
|
|
|
344
368
|
// ============================================================================
|
|
345
369
|
/**
|
|
346
370
|
* Subscribe to price updates.
|
|
347
|
-
*
|
|
371
|
+
* Polls the Price API, and streams assets that support market-stats.v1.
|
|
348
372
|
*
|
|
349
373
|
* @param subscriptionRequest - The subscription request configuration.
|
|
350
374
|
*/
|
|
351
375
|
async subscribe(subscriptionRequest) {
|
|
352
|
-
const { request,
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
if (existing) {
|
|
359
|
-
existing.request = request;
|
|
360
|
-
existing.onAssetsUpdate = subscriptionRequest.onAssetsUpdate;
|
|
361
|
-
try {
|
|
362
|
-
const fetchResponse = await this.fetch(request);
|
|
363
|
-
if (fetchResponse.assetsPrice &&
|
|
364
|
-
Object.keys(fetchResponse.assetsPrice).length > 0) {
|
|
365
|
-
await existing.onAssetsUpdate({
|
|
366
|
-
...fetchResponse,
|
|
367
|
-
updateMode: 'merge',
|
|
368
|
-
});
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
catch (error) {
|
|
372
|
-
log('Subscription update fetch failed', { subscriptionId, error });
|
|
373
|
-
}
|
|
374
|
-
return;
|
|
375
|
-
}
|
|
376
|
+
const { request, onAssetsUpdate } = subscriptionRequest;
|
|
377
|
+
if (this.#subscription) {
|
|
378
|
+
// Keep the interval. Refresh the request and fetch now so newly held
|
|
379
|
+
// assets do not wait for the next tick.
|
|
380
|
+
this.#subscription.request = request;
|
|
381
|
+
this.#subscription.onAssetsUpdate = onAssetsUpdate;
|
|
376
382
|
}
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
// Only report if we got prices
|
|
400
|
-
if (fetchResponse.assetsPrice &&
|
|
401
|
-
Object.keys(fetchResponse.assetsPrice).length > 0) {
|
|
402
|
-
await subscription.onAssetsUpdate({
|
|
403
|
-
...fetchResponse,
|
|
404
|
-
// merge overwrites existing spot prices on each poll; update would
|
|
405
|
-
// seed-only and leave the first price forever.
|
|
406
|
-
updateMode: 'merge',
|
|
407
|
-
});
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
catch (error) {
|
|
411
|
-
log('Subscription poll failed', { subscriptionId, error });
|
|
412
|
-
}
|
|
413
|
-
};
|
|
414
|
-
// Set up polling
|
|
415
|
-
const timer = setInterval(() => {
|
|
416
|
-
pollFn().catch(console.error);
|
|
417
|
-
}, pollInterval);
|
|
418
|
-
// Store subscription
|
|
419
|
-
this.#activeSubscriptions.set(subscriptionId, {
|
|
420
|
-
cleanup: () => {
|
|
421
|
-
clearInterval(timer);
|
|
422
|
-
},
|
|
423
|
-
request,
|
|
424
|
-
onAssetsUpdate: subscriptionRequest.onAssetsUpdate,
|
|
425
|
-
});
|
|
426
|
-
// Initial fetch
|
|
427
|
-
await pollFn();
|
|
383
|
+
else {
|
|
384
|
+
const pollInterval = request.updateInterval ?? this.#pollInterval;
|
|
385
|
+
// Cap the freshness TTL strictly below the effective poll interval.
|
|
386
|
+
// `fetchedAt` is stamped when a fetch completes (slightly after the tick
|
|
387
|
+
// that triggered it), so a TTL equal to the poll interval would leave the
|
|
388
|
+
// asset still "fresh" at the next tick, making the subscription re-fetch
|
|
389
|
+
// only every other poll. The margin also absorbs network latency / jitter.
|
|
390
|
+
this.#deduper.freshnessTtlMs = Math.min(this.#deduper.freshnessTtlMs, Math.floor(pollInterval * FRESHNESS_TTL_POLL_RATIO));
|
|
391
|
+
const timer = setInterval(() => {
|
|
392
|
+
this.#runPoll().catch((error) => {
|
|
393
|
+
log('Subscription poll failed', { error });
|
|
394
|
+
});
|
|
395
|
+
}, pollInterval);
|
|
396
|
+
this.#subscription = {
|
|
397
|
+
cleanup: () => {
|
|
398
|
+
clearInterval(timer);
|
|
399
|
+
},
|
|
400
|
+
request,
|
|
401
|
+
onAssetsUpdate,
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
await this.#runPoll();
|
|
428
405
|
}
|
|
429
406
|
/**
|
|
430
|
-
*
|
|
407
|
+
* Stop the price poll and release market-stats channels.
|
|
431
408
|
*
|
|
432
|
-
* @param
|
|
409
|
+
* @param _subscriptionId - Ignored. The controller passes its subscription key.
|
|
433
410
|
*/
|
|
434
|
-
async unsubscribe(
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
subscription.cleanup();
|
|
438
|
-
this.#activeSubscriptions.delete(subscriptionId);
|
|
411
|
+
async unsubscribe(_subscriptionId) {
|
|
412
|
+
if (!this.#subscription) {
|
|
413
|
+
return;
|
|
439
414
|
}
|
|
415
|
+
this.#subscription.cleanup();
|
|
416
|
+
this.#subscription = null;
|
|
417
|
+
await this.#marketStats.releaseSubscriptions();
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Drop market-stats channels and open them again for the current currency.
|
|
421
|
+
* Called when the selected currency changes so batches match `assetsPrice`.
|
|
422
|
+
*/
|
|
423
|
+
async resubscribeForCurrencyChange() {
|
|
424
|
+
if (!this.#subscription) {
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
await this.#marketStats.releaseSubscriptions();
|
|
428
|
+
await this.#reconcileMarketStats();
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Align market-stats channels with the price-fetch set and the `wssSupport`
|
|
432
|
+
* already stored in `assetsPrice`.
|
|
433
|
+
*
|
|
434
|
+
* Called after the spot-price response is in `assetsPrice`. A balance
|
|
435
|
+
* update reconciles from `AssetsController` once that write has landed.
|
|
436
|
+
* The price poll reconciles at the end of its own tick.
|
|
437
|
+
*/
|
|
438
|
+
async reconcileMarketStreams() {
|
|
439
|
+
if (!this.#subscription) {
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
await this.#reconcileMarketStats();
|
|
440
443
|
}
|
|
441
444
|
/**
|
|
442
445
|
* Invalidate the price freshness cache, forcing the next fetch to call the
|
|
@@ -450,11 +453,50 @@ export class PriceDataSource {
|
|
|
450
453
|
* Destroy the data source and clean up all subscriptions.
|
|
451
454
|
*/
|
|
452
455
|
destroy() {
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
this.#activeSubscriptions.clear();
|
|
456
|
+
this.#subscription?.cleanup();
|
|
457
|
+
this.#subscription = null;
|
|
458
|
+
this.#marketStats.destroy();
|
|
457
459
|
this.#deduper.destroy();
|
|
458
460
|
}
|
|
461
|
+
/**
|
|
462
|
+
* One poll tick: REST-fetch every tracked asset, then open market-stats
|
|
463
|
+
* channels for assets the response marks `wssSupport`.
|
|
464
|
+
*/
|
|
465
|
+
async #runPoll() {
|
|
466
|
+
const subscription = this.#subscription;
|
|
467
|
+
if (!subscription) {
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
try {
|
|
471
|
+
const fetchResponse = await this.fetch(subscription.request);
|
|
472
|
+
if (fetchResponse.assetsPrice &&
|
|
473
|
+
Object.keys(fetchResponse.assetsPrice).length > 0) {
|
|
474
|
+
await subscription.onAssetsUpdate({
|
|
475
|
+
...fetchResponse,
|
|
476
|
+
updateMode: 'merge',
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
await this.#reconcileMarketStats();
|
|
480
|
+
}
|
|
481
|
+
catch (error) {
|
|
482
|
+
log('Subscription poll failed', { error });
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
async #reconcileMarketStats() {
|
|
486
|
+
const subscription = this.#subscription;
|
|
487
|
+
if (!subscription) {
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
const assetIds = await this.#filterToSupportedPriceableAssets(this.#getAssetIdsFromBalanceState(subscription.request));
|
|
491
|
+
await this.#marketStats.reconcile(this.#candidatesFor(assetIds));
|
|
492
|
+
}
|
|
493
|
+
#candidatesFor(assetIds) {
|
|
494
|
+
const prices = this.#getAssetsState().assetsPrice ?? {};
|
|
495
|
+
return assetIds.map((assetId) => ({
|
|
496
|
+
assetId,
|
|
497
|
+
wssSupport: prices[assetId] !== undefined &&
|
|
498
|
+
readSpotPriceStreamEligibility(prices[assetId]),
|
|
499
|
+
}));
|
|
500
|
+
}
|
|
459
501
|
}
|
|
460
502
|
//# sourceMappingURL=PriceDataSource.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PriceDataSource.js","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAS3C,OAAO,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,M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C;QAEF,iBAAiB;QACjB,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;YAC7B,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QAChC,CAAC,EAAE,YAAY,CAAC,CAAC;QAEjB,qBAAqB;QACrB,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,cAAc,EAAE;YAC5C,OAAO,EAAE,GAAG,EAAE;gBACZ,aAAa,CAAC,KAAK,CAAC,CAAC;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"]}
|
|
1
|
+
{"version":3,"file":"PriceDataSource.js","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAS3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EACL,+BAA+B,EAC/B,wBAAwB,EACxB,2BAA2B,EAC3B,gBAAgB,GACjB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAErD,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAKtE,OAAO,EACL,sBAAsB,EACtB,8BAA8B,GAC/B,MAAM,6BAA6B,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AQ,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"]}
|
|
@@ -3,7 +3,7 @@ export { AccountsApiDataSource, type AccountsApiDataSourceConfig, type AccountsA
|
|
|
3
3
|
export { AccountActivityDataSource, createAccountActivityDataSource, type AccountActivityDataSourceOptions, type AccountActivityDataSourceState, type AccountActivityDataSourceAllowedEvents, } from './AccountActivityDataSource.js';
|
|
4
4
|
export { RpcDataSource, createRpcDataSource, type RpcDataSourceConfig, type RpcDataSourceOptions, type RpcDataSourceState, type RpcDataSourceAllowedActions, type RpcDataSourceAllowedEvents, type ChainStatus, } from './RpcDataSource.js';
|
|
5
5
|
export { TokenDataSource, type TokenDataSourceOptions, type TokenDataSourceAllowedActions, } from './TokenDataSource.js';
|
|
6
|
-
export { PriceDataSource, type PriceDataSourceConfig, type PriceDataSourceOptions, } from './PriceDataSource.js';
|
|
6
|
+
export { PriceDataSource, type PriceDataSourceConfig, type PriceDataSourceOptions, type MarketStatsPriceStreamMessenger, } from './PriceDataSource.js';
|
|
7
7
|
export { SnapDataSource, createSnapDataSource, SNAP_DATA_SOURCE_NAME, KEYRING_PERMISSION, getChainIdsCaveat, extractChainFromAssetId, type SnapDataSourceState, type SnapDataSourceOptions, type SnapDataSourceAllowedActions, type SnapDataSourceAllowedEvents, } from './SnapDataSource.js';
|
|
8
8
|
export { StakedBalanceDataSource, type StakedBalanceDataSourceConfig, type StakedBalanceDataSourceOptions, } from './StakedBalanceDataSource.js';
|
|
9
9
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/data-sources/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,KAAK,eAAe,EACpB,KAAK,mBAAmB,GACzB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EACL,qBAAqB,EACrB,KAAK,2BAA2B,EAChC,KAAK,4BAA4B,EACjC,KAAK,0BAA0B,EAC/B,KAAK,mCAAmC,GACzC,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,yBAAyB,EACzB,+BAA+B,EAC/B,KAAK,gCAAgC,EACrC,KAAK,8BAA8B,EACnC,KAAK,sCAAsC,GAC5C,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,KAAK,2BAA2B,EAChC,KAAK,0BAA0B,EAC/B,KAAK,WAAW,GACjB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,eAAe,EACf,KAAK,sBAAsB,EAC3B,KAAK,6BAA6B,GACnC,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,eAAe,EACf,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/data-sources/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,KAAK,eAAe,EACpB,KAAK,mBAAmB,GACzB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EACL,qBAAqB,EACrB,KAAK,2BAA2B,EAChC,KAAK,4BAA4B,EACjC,KAAK,0BAA0B,EAC/B,KAAK,mCAAmC,GACzC,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,yBAAyB,EACzB,+BAA+B,EAC/B,KAAK,gCAAgC,EACrC,KAAK,8BAA8B,EACnC,KAAK,sCAAsC,GAC5C,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,KAAK,2BAA2B,EAChC,KAAK,0BAA0B,EAC/B,KAAK,WAAW,GACjB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,eAAe,EACf,KAAK,sBAAsB,EAC3B,KAAK,6BAA6B,GACnC,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,eAAe,EACf,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,EAC3B,KAAK,+BAA+B,GACrC,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,qBAAqB,EAErB,kBAAkB,EAElB,iBAAiB,EACjB,uBAAuB,EAEvB,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAC1B,KAAK,4BAA4B,EACjC,KAAK,2BAA2B,GACjC,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,uBAAuB,EACvB,KAAK,6BAA6B,EAClC,KAAK,8BAA8B,GACpC,MAAM,8BAA8B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/data-sources/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,GAGnB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EACL,qBAAqB,GAKtB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,yBAAyB,EACzB,+BAA+B,GAIhC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,aAAa,EACb,mBAAmB,GAOpB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,eAAe,GAGhB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,eAAe,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/data-sources/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,GAGnB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EACL,qBAAqB,GAKtB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,yBAAyB,EACzB,+BAA+B,GAIhC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,aAAa,EACb,mBAAmB,GAOpB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,eAAe,GAGhB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,eAAe,GAIhB,MAAM,sBAAsB,CAAC;AAE9B,0FAA0F;AAC1F,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,qBAAqB;AACrB,YAAY;AACZ,kBAAkB;AAClB,oBAAoB;AACpB,iBAAiB,EACjB,uBAAuB,GAMxB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,uBAAuB,GAGxB,MAAM,8BAA8B,CAAC","sourcesContent":["export {\n AbstractDataSource,\n type DataSourceState,\n type SubscriptionRequest,\n} from './AbstractDataSource.js';\n\nexport {\n AccountsApiDataSource,\n type AccountsApiDataSourceConfig,\n type AccountsApiDataSourceOptions,\n type AccountsApiDataSourceState,\n type AccountsApiDataSourceAllowedActions,\n} from './AccountsApiDataSource.js';\n\nexport {\n AccountActivityDataSource,\n createAccountActivityDataSource,\n type AccountActivityDataSourceOptions,\n type AccountActivityDataSourceState,\n type AccountActivityDataSourceAllowedEvents,\n} from './AccountActivityDataSource.js';\n\nexport {\n RpcDataSource,\n createRpcDataSource,\n type RpcDataSourceConfig,\n type RpcDataSourceOptions,\n type RpcDataSourceState,\n type RpcDataSourceAllowedActions,\n type RpcDataSourceAllowedEvents,\n type ChainStatus,\n} from './RpcDataSource.js';\n\nexport {\n TokenDataSource,\n type TokenDataSourceOptions,\n type TokenDataSourceAllowedActions,\n} from './TokenDataSource.js';\n\nexport {\n PriceDataSource,\n type PriceDataSourceConfig,\n type PriceDataSourceOptions,\n type MarketStatsPriceStreamMessenger,\n} from './PriceDataSource.js';\n\n// Unified Snap Data Source (dynamically discovers keyring snaps via PermissionController)\nexport {\n SnapDataSource,\n createSnapDataSource,\n SNAP_DATA_SOURCE_NAME,\n // Constants\n KEYRING_PERMISSION,\n // Utility functions\n getChainIdsCaveat,\n extractChainFromAssetId,\n // Types\n type SnapDataSourceState,\n type SnapDataSourceOptions,\n type SnapDataSourceAllowedActions,\n type SnapDataSourceAllowedEvents,\n} from './SnapDataSource.js';\n\nexport {\n StakedBalanceDataSource,\n type StakedBalanceDataSourceConfig,\n type StakedBalanceDataSourceOptions,\n} from './StakedBalanceDataSource.js';\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export { DEFAULT_TRACKED_ASSETS_BY_CHAIN, CHAINS_WITH_DEFAULT_TRACKED_ASSETS, DE
|
|
|
4
4
|
export type { PendingTokenMetadata } from './AssetsController.js';
|
|
5
5
|
export { SNAPS_ASSETS_MIGRATION_FLAG_KEYS, SNAPS_ASSETS_MIGRATION_NAMESPACES, SnapsAssetsMigrationStage, getSnapsAssetsMigrationNamespace, isMigrationStageActive, isSnapsAssetsMigrationNamespace, parseSnapsAssetsMigrationStage, } from './utils/snaps-assets-migration.js';
|
|
6
6
|
export type { SnapsAssetsMigrationNamespace } from './utils/snaps-assets-migration.js';
|
|
7
|
-
export type { AssetsControllerState, AssetsControllerMessenger, AssetsControllerOptions, AssetsControllerGetStateAction, AssetsControllerActions, AssetsControllerStateChangeEvent, AssetsControllerBalanceChangedEvent,
|
|
7
|
+
export type { AssetsControllerState, AssetsControllerMessenger, AssetsControllerOptions, AssetsControllerGetStateAction, AssetsControllerActions, AssetsControllerStateChangeEvent, AssetsControllerBalanceChangedEvent, AssetsControllerEvents, } from './AssetsController.js';
|
|
8
8
|
export type { AssetsControllerGetAssetsAction, AssetsControllerGetAssetsBalanceAction, AssetsControllerGetAssetMetadataAction, AssetsControllerGetAccountAssetByIDAction, AssetsControllerGetAccountAssetsByIDsAction, AssetsControllerGetAccountAssetsByScopeAction, AssetsControllerGetAssetsPriceAction, AssetsControllerSyncAssetsPricesAction, AssetsControllerAddCustomAssetAction, AssetsControllerRemoveCustomAssetAction, AssetsControllerGetCustomAssetsAction, AssetsControllerHideAssetAction, AssetsControllerUnhideAssetAction, AssetsControllerGetExchangeRatesForBridgeAction, AssetsControllerGetStateForTransactionPayAction, AssetsControllerSetSelectedCurrencyAction, } from './AssetsController-method-action-types.js';
|
|
9
9
|
export type { Caip19AssetId, AccountId, ChainId, AssetType, TokenStandard, TokenFees, HoneypotStatus, StorageSlots, LocalizedDescription, BaseAssetMetadata, FungibleAssetMetadata, ERC721AssetMetadata, ERC1155AssetMetadata, AssetMetadata, BaseAssetPrice, FungibleAssetPrice, NFTAssetPrice, AssetPrice, FungibleAssetBalance, ERC721AssetBalance, ERC1155AssetBalance, AssetBalance, AccountWithSupportedChains, DataType, DataRequest, DataResponse, AssetsUpdateMode, AssetsLoadingStatus, Context, NextFunction, Middleware, AssetsDataSource, FetchContext, FetchNextFunction, FetchMiddleware, SubscriptionResponse, Asset, BalanceChangeEvent, PriceChangeEvent, MetadataChangeEvent, } from './types.js';
|
|
10
10
|
export { AbstractDataSource } from './data-sources/index.js';
|
|
@@ -16,9 +16,11 @@ export type { RpcDataSourceConfig, RpcDataSourceOptions, RpcDataSourceState, Cha
|
|
|
16
16
|
export { SnapDataSource, createSnapDataSource, SNAP_DATA_SOURCE_NAME, KEYRING_PERMISSION, getChainIdsCaveat, extractChainFromAssetId, } from './data-sources/index.js';
|
|
17
17
|
export type { SnapDataSourceState, SnapDataSourceOptions, } from './data-sources/index.js';
|
|
18
18
|
export { TokenDataSource, PriceDataSource } from './data-sources/index.js';
|
|
19
|
-
export type { TokenDataSourceOptions, PriceDataSourceConfig, PriceDataSourceOptions, } from './data-sources/index.js';
|
|
19
|
+
export type { TokenDataSourceOptions, PriceDataSourceConfig, PriceDataSourceOptions, MarketStatsPriceStreamMessenger, } from './data-sources/index.js';
|
|
20
20
|
export { RpcFallbackMiddleware } from './middlewares/index.js';
|
|
21
21
|
export type { RpcFallbackMiddlewareOptions } from './middlewares/index.js';
|
|
22
|
+
export { applyLiveTokenFiat, applyMarketStatsChainStatus, applyMarketStatsPrices, liveFiatDelta, liveGroupFiatAdjustments, liveHoldingFiat, marketStatsAssetKey, marketStatsQueryKey, quotesFor, readLiveQuotes, shareMarketStatsData, subscribeLiveQuotes, } from '@metamask/core-backend';
|
|
23
|
+
export type { LivePriceMap, LiveQuote, MarketStatsQuoteHandlers, MarketStatsQuotesQueryKey, SubscribeToMarketStats, UnsubscribeMarketStats, } from '@metamask/core-backend';
|
|
22
24
|
export { normalizeAssetId, formatExchangeRatesForBridge, formatStateForTransactionPay, } from './utils/index.js';
|
|
23
25
|
export type { AccountForLegacyFormat, BridgeExchangeRatesFormat, FormatExchangeRatesForBridgeParams, FormatStateForTransactionPayParams, LegacyToken, TransactionPayLegacyFormat, } from './utils/index.js';
|
|
24
26
|
export { calculateBalanceForAllWallets, calculateBalanceChangeForAccountGroup, getAggregatedBalanceForAccount, getGroupIdForAccount, getInternalAccountsForGroup, } from './selectors/balance.js';
|
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,
|
|
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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AAGhC,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,6 +20,8 @@ getChainIdsCaveat, extractChainFromAssetId, } from './data-sources/index.js';
|
|
|
20
20
|
export { TokenDataSource, PriceDataSource } from './data-sources/index.js';
|
|
21
21
|
// Middlewares
|
|
22
22
|
export { RpcFallbackMiddleware } from './middlewares/index.js';
|
|
23
|
+
// Market-stats quote helpers live in core-backend. Re-exported so existing imports keep working.
|
|
24
|
+
export { applyLiveTokenFiat, applyMarketStatsChainStatus, applyMarketStatsPrices, liveFiatDelta, liveGroupFiatAdjustments, liveHoldingFiat, marketStatsAssetKey, marketStatsQueryKey, quotesFor, readLiveQuotes, shareMarketStatsData, subscribeLiveQuotes, } from '@metamask/core-backend';
|
|
23
25
|
// Utilities
|
|
24
26
|
export { normalizeAssetId, formatExchangeRatesForBridge, formatStateForTransactionPay, } from './utils/index.js';
|
|
25
27
|
// Selectors
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,yBAAyB;AACzB,OAAO,EACL,gBAAgB,EAChB,+BAA+B,GAChC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,EAClC,sBAAsB,EACtB,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,GACxB,MAAM,eAAe,CAAC;AAGvB,4CAA4C;AAC5C,OAAO,EACL,gCAAgC,EAChC,iCAAiC,EACjC,yBAAyB,EACzB,gCAAgC,EAChC,sBAAsB,EACtB,+BAA+B,EAC/B,8BAA8B,GAC/B,MAAM,mCAAmC,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,yBAAyB;AACzB,OAAO,EACL,gBAAgB,EAChB,+BAA+B,GAChC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,EAClC,sBAAsB,EACtB,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,GACxB,MAAM,eAAe,CAAC;AAGvB,4CAA4C;AAC5C,OAAO,EACL,gCAAgC,EAChC,iCAAiC,EACjC,yBAAyB,EACzB,gCAAgC,EAChC,sBAAsB,EACtB,+BAA+B,EAC/B,8BAA8B,GAC/B,MAAM,mCAAmC,CAAC;AAuF3C,sCAAsC;AACtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAO7D,6BAA6B;AAC7B,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAQhE,qBAAqB;AACrB,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAS7E,gFAAgF;AAChF,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,qBAAqB;AACrB,YAAY;AACZ,kBAAkB;AAClB,oBAAoB;AACpB,iBAAiB,EACjB,uBAAuB,GACxB,MAAM,yBAAyB,CAAC;AAOjC,0BAA0B;AAC1B,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAS3E,cAAc;AACd,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAG/D,iGAAiG;AACjG,OAAO,EACL,kBAAkB,EAClB,2BAA2B,EAC3B,sBAAsB,EACtB,aAAa,EACb,wBAAwB,EACxB,eAAe,EACf,mBAAmB,EACnB,mBAAmB,EACnB,SAAS,EACT,cAAc,EACd,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,wBAAwB,CAAC;AAUhC,YAAY;AACZ,OAAO,EACL,gBAAgB,EAChB,4BAA4B,EAC5B,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC;AAU1B,YAAY;AACZ,OAAO,EACL,6BAA6B,EAC7B,qCAAqC,EACrC,8BAA8B,EAC9B,oBAAoB,EACpB,2BAA2B,GAC5B,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EACL,iCAAiC,EACjC,sCAAsC,EACtC,4BAA4B,EAC5B,uBAAuB,EACvB,mDAAmD,EACnD,yCAAyC,EACzC,0BAA0B,EAC1B,+BAA+B,EAC/B,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,wBAAwB,CAAC","sourcesContent":["// Main controller export\nexport {\n AssetsController,\n getDefaultAssetsControllerState,\n} from './AssetsController.js';\nexport { AssetsDataSourceError } from './errors.js';\nexport {\n DEFAULT_TRACKED_ASSETS_BY_CHAIN,\n CHAINS_WITH_DEFAULT_TRACKED_ASSETS,\n DEFAULT_ASSET_METADATA,\n buildDefaultAssetsInfo,\n getDefaultTrackedAssetsForChain,\n getDefaultAssetMetadata,\n} from './defaults.js';\nexport type { PendingTokenMetadata } from './AssetsController.js';\n\n// Snaps → AssetsController assets migration\nexport {\n SNAPS_ASSETS_MIGRATION_FLAG_KEYS,\n SNAPS_ASSETS_MIGRATION_NAMESPACES,\n SnapsAssetsMigrationStage,\n getSnapsAssetsMigrationNamespace,\n isMigrationStageActive,\n isSnapsAssetsMigrationNamespace,\n parseSnapsAssetsMigrationStage,\n} from './utils/snaps-assets-migration.js';\nexport type { SnapsAssetsMigrationNamespace } from './utils/snaps-assets-migration.js';\n\n// State and messenger types\nexport type {\n AssetsControllerState,\n AssetsControllerMessenger,\n AssetsControllerOptions,\n AssetsControllerGetStateAction,\n AssetsControllerActions,\n AssetsControllerStateChangeEvent,\n AssetsControllerBalanceChangedEvent,\n AssetsControllerEvents,\n} from './AssetsController.js';\nexport type {\n AssetsControllerGetAssetsAction,\n AssetsControllerGetAssetsBalanceAction,\n AssetsControllerGetAssetMetadataAction,\n AssetsControllerGetAccountAssetByIDAction,\n AssetsControllerGetAccountAssetsByIDsAction,\n AssetsControllerGetAccountAssetsByScopeAction,\n AssetsControllerGetAssetsPriceAction,\n AssetsControllerSyncAssetsPricesAction,\n AssetsControllerAddCustomAssetAction,\n AssetsControllerRemoveCustomAssetAction,\n AssetsControllerGetCustomAssetsAction,\n AssetsControllerHideAssetAction,\n AssetsControllerUnhideAssetAction,\n AssetsControllerGetExchangeRatesForBridgeAction,\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerSetSelectedCurrencyAction,\n} from './AssetsController-method-action-types.js';\n\n// Core types\nexport type {\n // CAIP types\n Caip19AssetId,\n AccountId,\n ChainId,\n // Asset types\n AssetType,\n TokenStandard,\n // Contract data types\n TokenFees,\n HoneypotStatus,\n StorageSlots,\n LocalizedDescription,\n // Metadata types\n BaseAssetMetadata,\n FungibleAssetMetadata,\n ERC721AssetMetadata,\n ERC1155AssetMetadata,\n AssetMetadata,\n // Price types\n BaseAssetPrice,\n FungibleAssetPrice,\n NFTAssetPrice,\n AssetPrice,\n // Balance types\n FungibleAssetBalance,\n ERC721AssetBalance,\n ERC1155AssetBalance,\n AssetBalance,\n // Data source types\n AccountWithSupportedChains,\n DataType,\n DataRequest,\n DataResponse,\n AssetsUpdateMode,\n AssetsLoadingStatus,\n // Middleware types\n Context,\n NextFunction,\n Middleware,\n AssetsDataSource,\n FetchContext,\n FetchNextFunction,\n FetchMiddleware,\n SubscriptionResponse,\n // Combined asset type\n Asset,\n // Event types\n BalanceChangeEvent,\n PriceChangeEvent,\n MetadataChangeEvent,\n} from './types.js';\n\n// Data sources - base class and types\nexport { AbstractDataSource } from './data-sources/index.js';\n\nexport type {\n DataSourceState,\n SubscriptionRequest,\n} from './data-sources/index.js';\n\n// Data sources - AccountsApi\nexport { AccountsApiDataSource } from './data-sources/index.js';\n\nexport type {\n AccountsApiDataSourceConfig,\n AccountsApiDataSourceOptions,\n AccountsApiDataSourceState,\n} from './data-sources/index.js';\n\n// Data sources - RPC\nexport { RpcDataSource, createRpcDataSource } from './data-sources/index.js';\n\nexport type {\n RpcDataSourceConfig,\n RpcDataSourceOptions,\n RpcDataSourceState,\n ChainStatus,\n} from './data-sources/index.js';\n\n// Data sources - Unified Snap Data Source (dynamically discovers keyring snaps)\nexport {\n SnapDataSource,\n createSnapDataSource,\n SNAP_DATA_SOURCE_NAME,\n // Constants\n KEYRING_PERMISSION,\n // Utility functions\n getChainIdsCaveat,\n extractChainFromAssetId,\n} from './data-sources/index.js';\n\nexport type {\n SnapDataSourceState,\n SnapDataSourceOptions,\n} from './data-sources/index.js';\n\n// Enrichment data sources\nexport { TokenDataSource, PriceDataSource } from './data-sources/index.js';\n\nexport type {\n TokenDataSourceOptions,\n PriceDataSourceConfig,\n PriceDataSourceOptions,\n MarketStatsPriceStreamMessenger,\n} from './data-sources/index.js';\n\n// Middlewares\nexport { RpcFallbackMiddleware } from './middlewares/index.js';\nexport type { RpcFallbackMiddlewareOptions } from './middlewares/index.js';\n\n// Market-stats quote helpers live in core-backend. Re-exported so existing imports keep working.\nexport {\n applyLiveTokenFiat,\n applyMarketStatsChainStatus,\n applyMarketStatsPrices,\n liveFiatDelta,\n liveGroupFiatAdjustments,\n liveHoldingFiat,\n marketStatsAssetKey,\n marketStatsQueryKey,\n quotesFor,\n readLiveQuotes,\n shareMarketStatsData,\n subscribeLiveQuotes,\n} from '@metamask/core-backend';\nexport type {\n LivePriceMap,\n LiveQuote,\n MarketStatsQuoteHandlers,\n MarketStatsQuotesQueryKey,\n SubscribeToMarketStats,\n UnsubscribeMarketStats,\n} from '@metamask/core-backend';\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,6 +200,11 @@ 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;
|
|
203
208
|
};
|
|
204
209
|
/**
|
|
205
210
|
* Price data for NFT collections
|