@metamask-previews/assets-controller 20.4.1-preview-1ae799a5c → 20.4.1-preview-e80304db4
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 +11 -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 +11 -18
- 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 +108 -0
- package/dist/data-sources/MarketStatsPriceStream.d.ts.map +1 -0
- package/dist/data-sources/MarketStatsPriceStream.js +297 -0
- package/dist/data-sources/MarketStatsPriceStream.js.map +1 -0
- package/dist/data-sources/PriceDataSource.d.ts +32 -2
- package/dist/data-sources/PriceDataSource.d.ts.map +1 -1
- package/dist/data-sources/PriceDataSource.js +164 -37
- 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/store/MarketStatsStore.d.ts +72 -0
- package/dist/store/MarketStatsStore.d.ts.map +1 -0
- package/dist/store/MarketStatsStore.js +182 -0
- package/dist/store/MarketStatsStore.js.map +1 -0
- 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
|
@@ -2,6 +2,7 @@ import type { SupportedCurrency } from '@metamask/core-backend';
|
|
|
2
2
|
import { ApiPlatformClient } from '@metamask/core-backend';
|
|
3
3
|
import type { Caip19AssetId, DataRequest, DataResponse, FungibleAssetPrice, Middleware, AssetsControllerState } from '../types.js';
|
|
4
4
|
import type { SubscriptionRequest } from './AbstractDataSource.js';
|
|
5
|
+
import type { MarketStatsPriceStreamMessenger } from './MarketStatsPriceStream.js';
|
|
5
6
|
/** Optional configuration for PriceDataSource. */
|
|
6
7
|
export type PriceDataSourceConfig = {
|
|
7
8
|
/** Polling interval in ms (default: 60000) */
|
|
@@ -19,6 +20,7 @@ export type PriceDataSourceConfig = {
|
|
|
19
20
|
*/
|
|
20
21
|
priceFreshnessTtlMs?: number;
|
|
21
22
|
};
|
|
23
|
+
export type { MarketStatsPriceStreamMessenger } from './MarketStatsPriceStream.js';
|
|
22
24
|
export type PriceDataSourceOptions = PriceDataSourceConfig & {
|
|
23
25
|
/** ApiPlatformClient for API calls with caching */
|
|
24
26
|
queryApiClient: ApiPlatformClient;
|
|
@@ -26,6 +28,12 @@ export type PriceDataSourceOptions = PriceDataSourceConfig & {
|
|
|
26
28
|
getSelectedCurrency: () => SupportedCurrency;
|
|
27
29
|
/** Current AssetsController state. Used for balance-based pricing and freshness checks. */
|
|
28
30
|
getAssetsState: () => AssetsControllerState;
|
|
31
|
+
/**
|
|
32
|
+
* Messenger that can call MarketStatsService. When the service is registered,
|
|
33
|
+
* assets with `wssSupport` stream and the rest keep polling. When it is not
|
|
34
|
+
* registered, every asset stays on the poll.
|
|
35
|
+
*/
|
|
36
|
+
messenger: MarketStatsPriceStreamMessenger;
|
|
29
37
|
};
|
|
30
38
|
/**
|
|
31
39
|
* Asset reference patterns that should NOT be sent to the Price API.
|
|
@@ -39,8 +47,15 @@ export { isPriceableAsset } from '../utils/getAssetIdsForPriceFetch.js';
|
|
|
39
47
|
* - Fetches prices from Price API v3 spot-prices endpoint
|
|
40
48
|
* - Supports one-time fetch and subscription-based polling
|
|
41
49
|
* - In subscribe mode, uses constructor `getAssetsState` to read assetsBalance and fetch prices
|
|
50
|
+
* - Streams the same assets the price poll tracks, when the spot-price
|
|
51
|
+
* response marks them `wssSupport: true`, on market-stats.v1. Socket ticks
|
|
52
|
+
* are not written into controller state. The UI reads
|
|
53
|
+
* `MarketStatsService:pricesUpdated`. The poll still writes `assetsPrice`
|
|
54
|
+
* for tracked assets that are not streaming. A price for an asset this
|
|
55
|
+
* controller does not track is a `MarketStatsService` subscription, not a
|
|
56
|
+
* call into this data source.
|
|
42
57
|
*
|
|
43
|
-
* Usage: Create with queryApiClient and getAssetsState; subscribe() polls prices for held assets.
|
|
58
|
+
* Usage: Create with queryApiClient, messenger, and getAssetsState; subscribe() polls prices for held assets.
|
|
44
59
|
*/
|
|
45
60
|
export declare class PriceDataSource {
|
|
46
61
|
#private;
|
|
@@ -81,7 +96,7 @@ export declare class PriceDataSource {
|
|
|
81
96
|
fetch(request: DataRequest): Promise<DataResponse>;
|
|
82
97
|
/**
|
|
83
98
|
* Subscribe to price updates.
|
|
84
|
-
*
|
|
99
|
+
* Polls the Price API, and streams assets that support market-stats.v1.
|
|
85
100
|
*
|
|
86
101
|
* @param subscriptionRequest - The subscription request configuration.
|
|
87
102
|
*/
|
|
@@ -92,6 +107,21 @@ export declare class PriceDataSource {
|
|
|
92
107
|
* @param subscriptionId - The ID of the subscription to cancel.
|
|
93
108
|
*/
|
|
94
109
|
unsubscribe(subscriptionId: string): Promise<void>;
|
|
110
|
+
/**
|
|
111
|
+
* Drop market-stats channels and open them again for the current currency.
|
|
112
|
+
* Called when the selected currency changes so batches match `assetsPrice`.
|
|
113
|
+
*/
|
|
114
|
+
resubscribeForCurrencyChange(): Promise<void>;
|
|
115
|
+
/**
|
|
116
|
+
* Align market-stats channels with the price-fetch set and the `wssSupport`
|
|
117
|
+
* already stored in `assetsPrice`.
|
|
118
|
+
*
|
|
119
|
+
* The poll calls this after it writes the spot-price response. A balance
|
|
120
|
+
* update does not. Stored flags can be from an earlier response, and
|
|
121
|
+
* subscribing from them opens channels the latest response marks
|
|
122
|
+
* `wssSupport: false`. A new balance waits for the next poll.
|
|
123
|
+
*/
|
|
124
|
+
reconcileMarketStreams(): Promise<void>;
|
|
95
125
|
/**
|
|
96
126
|
* Invalidate the price freshness cache, forcing the next fetch to call the
|
|
97
127
|
* API regardless of TTL. Use when external state changes (e.g. selected
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PriceDataSource.d.ts","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,iBAAiB,EAElB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAI3D,OAAO,KAAK,EACV,aAAa,EACb,WAAW,EACX,YAAY,EACZ,kBAAkB,EAClB,UAAU,EACV,qBAAqB,EACtB,MAAM,aAAa,CAAC;AASrB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"PriceDataSource.d.ts","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,iBAAiB,EAElB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAI3D,OAAO,KAAK,EACV,aAAa,EACb,WAAW,EACX,YAAY,EACZ,kBAAkB,EAClB,UAAU,EACV,qBAAqB,EACtB,MAAM,aAAa,CAAC;AASrB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAEnE,OAAO,KAAK,EACV,+BAA+B,EAEhC,MAAM,6BAA6B,CAAC;AAgErC,kDAAkD;AAClD,MAAM,MAAM,qBAAqB,GAAG;IAClC,8CAA8C;IAC9C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;;;OAKG;IACH,mBAAmB,CAAC,EAAE,MAAM,CA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AED;;OAEG;IACH,OAAO,IAAI,IAAI,CAQd;CAmGF"}
|
|
@@ -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, chainIdFromAssetId, readSpotPriceStreamEligibility, } from './MarketStatsPriceStream.js';
|
|
7
8
|
// ============================================================================
|
|
8
9
|
// CONSTANTS
|
|
9
10
|
// ============================================================================
|
|
@@ -74,8 +75,15 @@ 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. Socket ticks
|
|
80
|
+
* are not written into controller state. The UI reads
|
|
81
|
+
* `MarketStatsService:pricesUpdated`. The poll still writes `assetsPrice`
|
|
82
|
+
* for tracked assets that are not streaming. A price for an asset this
|
|
83
|
+
* controller does not track is a `MarketStatsService` subscription, not a
|
|
84
|
+
* call into this data source.
|
|
77
85
|
*
|
|
78
|
-
* Usage: Create with queryApiClient and getAssetsState; subscribe() polls prices for held assets.
|
|
86
|
+
* Usage: Create with queryApiClient, messenger, and getAssetsState; subscribe() polls prices for held assets.
|
|
79
87
|
*/
|
|
80
88
|
export class PriceDataSource {
|
|
81
89
|
static controllerName = CONTROLLER_NAME;
|
|
@@ -95,6 +103,11 @@ export class PriceDataSource {
|
|
|
95
103
|
*/
|
|
96
104
|
#deduper;
|
|
97
105
|
#getAssetsState;
|
|
106
|
+
#marketStats;
|
|
107
|
+
/** Poll interval of the active subscription, used to size chain-down jitter. */
|
|
108
|
+
#effectivePollInterval;
|
|
109
|
+
/** Delays the next poll after a chain goes down or comes back. */
|
|
110
|
+
#fallbackTimer;
|
|
98
111
|
/** Active subscriptions by ID */
|
|
99
112
|
#activeSubscriptions = new Map();
|
|
100
113
|
constructor(options) {
|
|
@@ -103,6 +116,18 @@ export class PriceDataSource {
|
|
|
103
116
|
this.#apiClient = options.queryApiClient;
|
|
104
117
|
this.#fetchTimeoutMs = options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
|
|
105
118
|
this.#getAssetsState = options.getAssetsState;
|
|
119
|
+
this.#effectivePollInterval = this.#pollInterval;
|
|
120
|
+
this.#marketStats = new MarketStatsPriceStream({
|
|
121
|
+
messenger: options.messenger,
|
|
122
|
+
getSelectedCurrency: () => this.#getSelectedCurrency(),
|
|
123
|
+
getPollIntervalMs: () => this.#effectivePollInterval,
|
|
124
|
+
requestPoll: (delayMs, details) => {
|
|
125
|
+
if (details.status === 'down') {
|
|
126
|
+
this.#invalidateChains(details.chainIds);
|
|
127
|
+
}
|
|
128
|
+
this.#scheduleStreamPoll(delayMs);
|
|
129
|
+
},
|
|
130
|
+
});
|
|
106
131
|
this.#deduper = new DedupingBatchFetcher({
|
|
107
132
|
fetchBatch: (assetIds) => this.#executeBatchFetch(assetIds),
|
|
108
133
|
freshnessTtlMs: options.priceFreshnessTtlMs ?? this.#pollInterval,
|
|
@@ -182,6 +207,7 @@ export class PriceDataSource {
|
|
|
182
207
|
const selectedCurrencyPrices = await fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
|
|
183
208
|
currency: selectedCurrency,
|
|
184
209
|
includeMarketData: true,
|
|
210
|
+
includeWssSupportField: true,
|
|
185
211
|
}), this.#fetchTimeoutMs);
|
|
186
212
|
return { selectedCurrencyPrices, usdPrices: selectedCurrencyPrices };
|
|
187
213
|
}
|
|
@@ -189,10 +215,12 @@ export class PriceDataSource {
|
|
|
189
215
|
fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
|
|
190
216
|
currency: selectedCurrency,
|
|
191
217
|
includeMarketData: true,
|
|
218
|
+
includeWssSupportField: true,
|
|
192
219
|
}), this.#fetchTimeoutMs),
|
|
193
220
|
fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
|
|
194
221
|
currency: 'usd',
|
|
195
222
|
includeMarketData: true,
|
|
223
|
+
includeWssSupportField: true,
|
|
196
224
|
}), this.#fetchTimeoutMs),
|
|
197
225
|
]);
|
|
198
226
|
return { selectedCurrencyPrices, usdPrices };
|
|
@@ -322,8 +350,18 @@ export class PriceDataSource {
|
|
|
322
350
|
* @returns DataResponse containing asset prices.
|
|
323
351
|
*/
|
|
324
352
|
async fetch(request) {
|
|
325
|
-
const response = {};
|
|
326
353
|
const assetIds = await this.#filterToSupportedPriceableAssets(this.#getAssetIdsFromBalanceState(request));
|
|
354
|
+
return this.#fetchAssetIdList(assetIds);
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Fetch spot prices for an explicit id list. Empty when there is nothing to
|
|
358
|
+
* price or the Price API call fails.
|
|
359
|
+
*
|
|
360
|
+
* @param assetIds - CAIP-19 asset IDs already filtered to priceable assets.
|
|
361
|
+
* @returns DataResponse containing asset prices.
|
|
362
|
+
*/
|
|
363
|
+
async #fetchAssetIdList(assetIds) {
|
|
364
|
+
const response = {};
|
|
327
365
|
if (assetIds.length === 0) {
|
|
328
366
|
return response;
|
|
329
367
|
}
|
|
@@ -344,7 +382,7 @@ export class PriceDataSource {
|
|
|
344
382
|
// ============================================================================
|
|
345
383
|
/**
|
|
346
384
|
* Subscribe to price updates.
|
|
347
|
-
*
|
|
385
|
+
* Polls the Price API, and streams assets that support market-stats.v1.
|
|
348
386
|
*
|
|
349
387
|
* @param subscriptionRequest - The subscription request configuration.
|
|
350
388
|
*/
|
|
@@ -367,6 +405,7 @@ export class PriceDataSource {
|
|
|
367
405
|
updateMode: 'merge',
|
|
368
406
|
});
|
|
369
407
|
}
|
|
408
|
+
await this.#reconcileMarketStats();
|
|
370
409
|
}
|
|
371
410
|
catch (error) {
|
|
372
411
|
log('Subscription update fetch failed', { subscriptionId, error });
|
|
@@ -377,43 +416,18 @@ export class PriceDataSource {
|
|
|
377
416
|
// Clean up existing subscription
|
|
378
417
|
await this.unsubscribe(subscriptionId);
|
|
379
418
|
const pollInterval = request.updateInterval ?? this.#pollInterval;
|
|
419
|
+
this.#effectivePollInterval = pollInterval;
|
|
380
420
|
// Cap the freshness TTL strictly below the effective poll interval.
|
|
381
421
|
// `fetchedAt` is stamped when a fetch completes (slightly after the tick
|
|
382
422
|
// that triggered it), so a TTL equal to the poll interval would leave the
|
|
383
423
|
// asset still "fresh" at the next tick, making the subscription re-fetch
|
|
384
424
|
// only every other poll. The margin also absorbs network latency / jitter.
|
|
385
425
|
this.#deduper.freshnessTtlMs = Math.min(this.#deduper.freshnessTtlMs, Math.floor(pollInterval * FRESHNESS_TTL_POLL_RATIO));
|
|
386
|
-
//
|
|
387
|
-
// The freshness TTL naturally gates re-fetches: assets fetched less than
|
|
388
|
-
// `priceFreshnessTtlMs` ago are skipped, preventing duplicates when middleware
|
|
389
|
-
// or other triggers already fetched the same assets between polls.
|
|
390
|
-
// Concurrent middleware calls will join the inflight promise rather than
|
|
391
|
-
// issuing duplicate requests.
|
|
392
|
-
const pollFn = async () => {
|
|
393
|
-
try {
|
|
394
|
-
const subscription = this.#activeSubscriptions.get(subscriptionId);
|
|
395
|
-
if (!subscription) {
|
|
396
|
-
return;
|
|
397
|
-
}
|
|
398
|
-
const fetchResponse = await this.fetch(subscription.request);
|
|
399
|
-
// Only report if we got prices
|
|
400
|
-
if (fetchResponse.assetsPrice &&
|
|
401
|
-
Object.keys(fetchResponse.assetsPrice).length > 0) {
|
|
402
|
-
await subscription.onAssetsUpdate({
|
|
403
|
-
...fetchResponse,
|
|
404
|
-
// merge overwrites existing spot prices on each poll; update would
|
|
405
|
-
// seed-only and leave the first price forever.
|
|
406
|
-
updateMode: 'merge',
|
|
407
|
-
});
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
catch (error) {
|
|
411
|
-
log('Subscription poll failed', { subscriptionId, error });
|
|
412
|
-
}
|
|
413
|
-
};
|
|
414
|
-
// Set up polling
|
|
426
|
+
// Each tick skips assets `getSubscriptions` already has open on a healthy chain.
|
|
415
427
|
const timer = setInterval(() => {
|
|
416
|
-
|
|
428
|
+
this.#runPoll(subscriptionId).catch((error) => {
|
|
429
|
+
log('Subscription poll failed', { subscriptionId, error });
|
|
430
|
+
});
|
|
417
431
|
}, pollInterval);
|
|
418
432
|
// Store subscription
|
|
419
433
|
this.#activeSubscriptions.set(subscriptionId, {
|
|
@@ -424,7 +438,7 @@ export class PriceDataSource {
|
|
|
424
438
|
onAssetsUpdate: subscriptionRequest.onAssetsUpdate,
|
|
425
439
|
});
|
|
426
440
|
// Initial fetch
|
|
427
|
-
await
|
|
441
|
+
await this.#runPoll(subscriptionId);
|
|
428
442
|
}
|
|
429
443
|
/**
|
|
430
444
|
* Unsubscribe from price updates.
|
|
@@ -433,10 +447,43 @@ export class PriceDataSource {
|
|
|
433
447
|
*/
|
|
434
448
|
async unsubscribe(subscriptionId) {
|
|
435
449
|
const subscription = this.#activeSubscriptions.get(subscriptionId);
|
|
436
|
-
if (subscription) {
|
|
437
|
-
|
|
438
|
-
|
|
450
|
+
if (!subscription) {
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
subscription.cleanup();
|
|
454
|
+
this.#activeSubscriptions.delete(subscriptionId);
|
|
455
|
+
if (this.#activeSubscriptions.size === 0) {
|
|
456
|
+
this.#clearFallbackTimer();
|
|
457
|
+
await this.#marketStats.releaseSubscriptions();
|
|
458
|
+
return;
|
|
439
459
|
}
|
|
460
|
+
await this.#reconcileMarketStats();
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Drop market-stats channels and open them again for the current currency.
|
|
464
|
+
* Called when the selected currency changes so batches match `assetsPrice`.
|
|
465
|
+
*/
|
|
466
|
+
async resubscribeForCurrencyChange() {
|
|
467
|
+
if (this.#activeSubscriptions.size === 0) {
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
await this.#marketStats.releaseSubscriptions();
|
|
471
|
+
await this.#reconcileMarketStats();
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Align market-stats channels with the price-fetch set and the `wssSupport`
|
|
475
|
+
* already stored in `assetsPrice`.
|
|
476
|
+
*
|
|
477
|
+
* The poll calls this after it writes the spot-price response. A balance
|
|
478
|
+
* update does not. Stored flags can be from an earlier response, and
|
|
479
|
+
* subscribing from them opens channels the latest response marks
|
|
480
|
+
* `wssSupport: false`. A new balance waits for the next poll.
|
|
481
|
+
*/
|
|
482
|
+
async reconcileMarketStreams() {
|
|
483
|
+
if (this.#activeSubscriptions.size === 0) {
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
await this.#reconcileMarketStats();
|
|
440
487
|
}
|
|
441
488
|
/**
|
|
442
489
|
* Invalidate the price freshness cache, forcing the next fetch to call the
|
|
@@ -454,7 +501,87 @@ export class PriceDataSource {
|
|
|
454
501
|
subscription.cleanup();
|
|
455
502
|
}
|
|
456
503
|
this.#activeSubscriptions.clear();
|
|
504
|
+
this.#clearFallbackTimer();
|
|
505
|
+
this.#marketStats.destroy();
|
|
457
506
|
this.#deduper.destroy();
|
|
458
507
|
}
|
|
508
|
+
/**
|
|
509
|
+
* One poll tick: REST-fetch assets that are not streaming, then align the
|
|
510
|
+
* market-stats subscription with what the latest spot response can stream.
|
|
511
|
+
*
|
|
512
|
+
* @param subscriptionId - Active subscription to poll.
|
|
513
|
+
*/
|
|
514
|
+
async #runPoll(subscriptionId) {
|
|
515
|
+
const subscription = this.#activeSubscriptions.get(subscriptionId);
|
|
516
|
+
if (!subscription) {
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
try {
|
|
520
|
+
const assetIds = await this.#filterToSupportedPriceableAssets(this.#getAssetIdsFromBalanceState(subscription.request));
|
|
521
|
+
const now = Date.now();
|
|
522
|
+
const [subscribed, downChains] = await Promise.all([
|
|
523
|
+
this.#marketStats.subscribedAssetIds(),
|
|
524
|
+
this.#marketStats.downChainIds(),
|
|
525
|
+
]);
|
|
526
|
+
const idsToFetch = assetIds.filter((assetId) => this.#marketStats.shouldPoll(assetId, now, subscribed, downChains));
|
|
527
|
+
const fetchResponse = await this.#fetchAssetIdList(idsToFetch);
|
|
528
|
+
if (fetchResponse.assetsPrice &&
|
|
529
|
+
Object.keys(fetchResponse.assetsPrice).length > 0) {
|
|
530
|
+
await subscription.onAssetsUpdate({
|
|
531
|
+
...fetchResponse,
|
|
532
|
+
updateMode: 'merge',
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
await this.#reconcileMarketStats();
|
|
536
|
+
}
|
|
537
|
+
catch (error) {
|
|
538
|
+
log('Subscription poll failed', { subscriptionId, error });
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
async #reconcileMarketStats() {
|
|
542
|
+
const assetIds = new Set();
|
|
543
|
+
for (const subscription of this.#activeSubscriptions.values()) {
|
|
544
|
+
const ids = await this.#filterToSupportedPriceableAssets(this.#getAssetIdsFromBalanceState(subscription.request));
|
|
545
|
+
for (const assetId of ids) {
|
|
546
|
+
assetIds.add(assetId);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
await this.#marketStats.reconcile(this.#candidatesFor([...assetIds]));
|
|
550
|
+
}
|
|
551
|
+
#candidatesFor(assetIds) {
|
|
552
|
+
const prices = this.#getAssetsState().assetsPrice ?? {};
|
|
553
|
+
return assetIds.map((assetId) => ({
|
|
554
|
+
assetId,
|
|
555
|
+
wssSupport: prices[assetId] !== undefined &&
|
|
556
|
+
readSpotPriceStreamEligibility(prices[assetId]),
|
|
557
|
+
}));
|
|
558
|
+
}
|
|
559
|
+
#invalidateChains(chainIds) {
|
|
560
|
+
const chains = new Set(chainIds);
|
|
561
|
+
const assetIds = Object.keys(this.#getAssetsState().assetsPrice ?? {}).filter((assetId) => {
|
|
562
|
+
const chainId = chainIdFromAssetId(assetId);
|
|
563
|
+
return chainId !== undefined && chains.has(chainId);
|
|
564
|
+
});
|
|
565
|
+
if (assetIds.length > 0) {
|
|
566
|
+
this.#deduper.invalidateKeys(assetIds);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
#scheduleStreamPoll(delayMs) {
|
|
570
|
+
this.#clearFallbackTimer();
|
|
571
|
+
this.#fallbackTimer = setTimeout(() => {
|
|
572
|
+
this.#fallbackTimer = undefined;
|
|
573
|
+
for (const subscriptionId of this.#activeSubscriptions.keys()) {
|
|
574
|
+
this.#runPoll(subscriptionId).catch((error) => {
|
|
575
|
+
log('Market stats fallback poll failed', { subscriptionId, error });
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
}, delayMs);
|
|
579
|
+
}
|
|
580
|
+
#clearFallbackTimer() {
|
|
581
|
+
if (this.#fallbackTimer) {
|
|
582
|
+
clearTimeout(this.#fallbackTimer);
|
|
583
|
+
this.#fallbackTimer = undefined;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
459
586
|
}
|
|
460
587
|
//# 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;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edCurrency,\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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CAAC;IAED,mBAAmB,CAAC,OAAe;QACjC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC3B,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC,GAAG,EAAE;YACpC,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;YAChC,KAAK,MAAM,cAAc,IAAI,IAAI,CAAC,oBAAoB,CAAC,IAAI,EAAE,EAAE,CAAC;gBAC9D,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;oBACrD,GAAG,CAAC,mCAAmC,EAAE,EAAE,cAAc,EAAE,KAAK,EAAE,CAAC,CAAC;gBACtE,CAAC,CAAC,CAAC;YACL,CAAC;QACH,CAAC,EAAE,OAAO,CAAC,CAAC;IACd,CAAC;IAED,mBAAmB;QACjB,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACxB,YAAY,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;YAClC,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAClC,CAAC;IACH,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 chainIdFromAssetId,\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 and the rest keep 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. Socket ticks\n * are not written into controller state. The UI reads\n * `MarketStatsService:pricesUpdated`. The poll still writes `assetsPrice`\n * for tracked assets that are not streaming. A price for an asset this\n * controller does not track is a `MarketStatsService` subscription, not a\n * call into this data source.\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 /** Poll interval of the active subscription, used to size chain-down jitter. */\n #effectivePollInterval: number;\n\n /** Delays the next poll after a chain goes down or comes back. */\n #fallbackTimer?: ReturnType<typeof setTimeout>;\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.#effectivePollInterval = this.#pollInterval;\n this.#marketStats = new MarketStatsPriceStream({\n messenger: options.messenger,\n getSelectedCurrency: (): SupportedCurrency => this.#getSelectedCurrency(),\n getPollIntervalMs: (): number => this.#effectivePollInterval,\n requestPoll: (\n delayMs: number,\n details: { chainIds: string[]; status: 'up' | 'down' },\n ): void => {\n if (details.status === 'down') {\n this.#invalidateChains(details.chainIds);\n }\n this.#scheduleStreamPoll(delayMs);\n },\n });\n this.#deduper = new DedupingBatchFetcher({\n fetchBatch: (\n assetIds,\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> =>\n this.#executeBatchFetch(assetIds),\n freshnessTtlMs: options.priceFreshnessTtlMs ?? this.#pollInterval,\n });\n }\n\n // ============================================================================\n // MIDDLEWARE\n // ============================================================================\n\n /**\n * Get the middleware for enriching responses with price data.\n *\n * This middleware:\n * 1. Selects response balances that still need a price.\n * {@link getUnpricedResponseAssetIds} skips hidden, non-priceable, and\n * already-priced assets, and assets on chains the Price API does not support\n * 2. Fetches those prices. A price asked for within the freshness window is\n * skipped, unless the request forces an update\n * 3. Merges fetched prices into the response and continues the chain. A\n * failed fetch leaves the response balances unchanged\n *\n * @returns The middleware function for the assets pipeline.\n */\n get assetsMiddleware(): Middleware {\n return forDataTypes(['price'], async (ctx, next) => {\n const { response, request } = ctx;\n const unpricedAssetIds = await getUnpricedResponseAssetIds({\n state: this.#getAssetsState(),\n response,\n getSupportedNetworks: () => this.#getSupportedNetworks(),\n });\n if (unpricedAssetIds.length === 0) {\n return next(ctx);\n }\n\n if (request.forceUpdate) {\n this.#deduper.invalidateKeys(unpricedAssetIds);\n }\n\n try {\n const spotPrices = await this.#fetchSpotPrices(unpricedAssetIds);\n response.assetsPrice = {\n ...(response.assetsPrice ?? {}),\n ...spotPrices,\n };\n } catch (error) {\n log('Failed to fetch prices via middleware', { error });\n }\n\n // Call next() at the end to continue the middleware chain\n return next(ctx);\n });\n }\n\n /**\n * Fetch spot prices for an explicit asset list, bypassing the freshness cache.\n *\n * @param assetIds - CAIP-19 asset IDs to price.\n * @returns Prices keyed by asset ID. Empty when none are priceable or supported.\n */\n async fetchAssetPrices(\n assetIds: Caip19AssetId[],\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> {\n const supportedAssetIds =\n await this.#filterToSupportedPriceableAssets(assetIds);\n if (supportedAssetIds.length === 0) {\n return {};\n }\n\n this.#deduper.invalidateKeys(supportedAssetIds);\n return this.#fetchSpotPrices(supportedAssetIds);\n }\n\n // ============================================================================\n // HELPERS\n // ============================================================================\n\n /**\n * Fetch spot prices for a single batch of asset IDs (must be ≤ PRICE_API_BATCH_SIZE).\n *\n * @param assetIds - Array of CAIP-19 asset IDs (already within batch size limit).\n * @param selectedCurrency - The user's selected display currency.\n * @returns Raw spot-prices responses for the selected currency and USD.\n */\n async #fetchSpotPricesBatch(\n assetIds: string[],\n selectedCurrency: SupportedCurrency,\n ): Promise<{\n selectedCurrencyPrices: V3SpotPricesResponse;\n usdPrices: V3SpotPricesResponse;\n }> {\n if (selectedCurrency === 'usd') {\n const selectedCurrencyPrices = await fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: selectedCurrency,\n includeMarketData: true,\n includeWssSupportField: true,\n }),\n this.#fetchTimeoutMs,\n );\n return { selectedCurrencyPrices, usdPrices: selectedCurrencyPrices };\n }\n\n const [selectedCurrencyPrices, usdPrices] = await Promise.all([\n fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: selectedCurrency,\n includeMarketData: true,\n includeWssSupportField: true,\n }),\n this.#fetchTimeoutMs,\n ),\n fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: 'usd',\n includeMarketData: true,\n includeWssSupportField: true,\n }),\n this.#fetchTimeoutMs,\n ),\n ]);\n\n return { selectedCurrencyPrices, usdPrices };\n }\n\n /**\n * Execute the actual batched API call for a set of asset IDs and return\n * parsed price results. Used as the `fetchBatch` callback for the deduper,\n * so it does NOT check freshness or inflight state — that is handled by\n * {@link DedupingBatchFetcher}.\n *\n * @param assetIds - Asset IDs to fetch (already filtered/deduplicated).\n * @returns Parsed prices keyed by CAIP-19 asset ID.\n */\n async #executeBatchFetch(\n assetIds: Caip19AssetId[],\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> {\n const selectedCurrency = this.#getSelectedCurrency();\n\n type BatchResult = {\n selectedCurrencyPrices: V3SpotPricesResponse;\n usdPrices: V3SpotPricesResponse;\n };\n\n const batchResults = await reduceInBatchesSerially<string, BatchResult[]>({\n values: assetIds,\n batchSize: PRICE_API_BATCH_SIZE,\n eachBatch: async (workingResult, batch) => {\n const result = await this.#fetchSpotPricesBatch(\n batch,\n selectedCurrency,\n );\n return [...(workingResult as BatchResult[]), result];\n },\n initialResult: [],\n });\n\n const fetchedAt = Date.now();\n const prices: Record<Caip19AssetId, FungibleAssetPrice> = {};\n\n for (const { selectedCurrencyPrices, usdPrices } of batchResults) {\n for (const [assetId, marketData] of Object.entries(\n selectedCurrencyPrices,\n )) {\n const usdMarketData = usdPrices[assetId];\n\n if (\n !isValidMarketData(marketData) ||\n !isValidMarketData(usdMarketData)\n ) {\n continue;\n }\n\n prices[assetId as Caip19AssetId] = {\n ...marketData,\n assetPriceType: 'fungible',\n usdPrice: usdMarketData.price,\n lastUpdated: fetchedAt,\n };\n }\n }\n\n return prices;\n }\n\n /**\n * Fetch spot prices for all provided asset IDs, deduplicating via the\n * deduper (freshness TTL + per-asset inflight coalescing).\n *\n * @param assetIds - Array of CAIP-19 asset IDs.\n * @returns Spot prices response (only contains entries for assets that were\n * actually fetched or joined from inflight).\n */\n async #fetchSpotPrices(\n assetIds: Caip19AssetId[],\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> {\n return this.#deduper.fetch(assetIds);\n }\n\n /**\n * Get unique asset IDs from the assetsBalance state.\n * Filters by accounts and chains from the request.\n *\n * @param request - Data request with accounts and chainIds filters.\n * @returns Array of CAIP-19 asset IDs from balance state.\n */\n #getAssetIdsFromBalanceState(request: DataRequest): Caip19AssetId[] {\n try {\n return [\n ...getAssetIdsForPriceFetch({\n state: this.#getAssetsState(),\n request,\n }),\n ];\n } catch (error) {\n log('Failed to get asset IDs from balance state', { error });\n return [];\n }\n }\n\n /**\n * Drop non-priceable assets, then assets on chains the price API does not\n * support. An empty supported-network set keeps every priceable asset.\n *\n * @param assetIds - Candidate CAIP-19 asset IDs.\n * @returns Priceable IDs on a supported chain.\n */\n async #filterToSupportedPriceableAssets(\n assetIds: Caip19AssetId[],\n ): Promise<Caip19AssetId[]> {\n const priceableAssetIds = assetIds.filter(isPriceableAsset);\n if (priceableAssetIds.length === 0) {\n return [];\n }\n\n const supportedNetworks = await this.#getSupportedNetworks();\n return this.#filterAssetsByNetwork(priceableAssetIds, supportedNetworks);\n }\n\n /**\n * Price API networks supported by the v3 spot-prices endpoint\n * (`fullSupport` plus `partialSupport.spotPricesV3`).\n *\n * @returns CAIP-2 chain IDs; empty on error.\n */\n async #getSupportedNetworks(): Promise<Set<string>> {\n try {\n const response = await fetchWithTimeout(\n (): Promise<PriceV2SupportedNetworksResponse> =>\n this.#apiClient.prices.fetchPriceV2SupportedNetworks(),\n this.#fetchTimeoutMs,\n );\n\n return getV3SpotPriceSupportedChainIds(response);\n } catch (error) {\n log('Failed to fetch price supported networks', { error });\n return new Set();\n }\n }\n\n /**\n * Keeps asset IDs whose chain is in `supportedNetworks`.\n *\n * @param assetIds - CAIP-19 asset IDs.\n * @param supportedNetworks - Supported CAIP-2 chain IDs.\n * @returns Matching IDs, or all IDs if the set is empty.\n */\n #filterAssetsByNetwork(\n assetIds: Caip19AssetId[],\n supportedNetworks: Set<string>,\n ): Caip19AssetId[] {\n return filterAssetsBySupportedNetworks(assetIds, supportedNetworks);\n }\n\n // ============================================================================\n // FETCH\n // ============================================================================\n\n /**\n * Fetch prices for visible assets on the accounts and chains in the request:\n * saved balances and custom assets. Metadata with no balance is skipped.\n * Unlike the middleware, this includes assets that already have a stored\n * price so the poll can refresh them. The freshness cache skips recent ones.\n *\n * @param request - The data request specifying accounts and chains.\n * @returns DataResponse containing asset prices.\n */\n async fetch(request: DataRequest): Promise<DataResponse> {\n const assetIds = await this.#filterToSupportedPriceableAssets(\n this.#getAssetIdsFromBalanceState(request),\n );\n return this.#fetchAssetIdList(assetIds);\n }\n\n /**\n * Fetch spot prices for an explicit id list. Empty when there is nothing to\n * price or the Price API call fails.\n *\n * @param assetIds - CAIP-19 asset IDs already filtered to priceable assets.\n * @returns DataResponse containing asset prices.\n */\n async #fetchAssetIdList(assetIds: Caip19AssetId[]): Promise<DataResponse> {\n const response: DataResponse = {};\n if (assetIds.length === 0) {\n return response;\n }\n\n try {\n const spotPrices = await this.#fetchSpotPrices(assetIds);\n response.assetsPrice = {\n ...(response.assetsPrice ?? {}),\n ...spotPrices,\n };\n } catch (error) {\n log('Failed to fetch prices', { error });\n }\n\n return response;\n }\n\n // ============================================================================\n // SUBSCRIBE\n // ============================================================================\n\n /**\n * Subscribe to price updates.\n * Polls the Price API, and streams assets that support market-stats.v1.\n *\n * @param subscriptionRequest - The subscription request configuration.\n */\n async subscribe(subscriptionRequest: SubscriptionRequest): Promise<void> {\n const { request, subscriptionId, isUpdate } = subscriptionRequest;\n\n // Handle subscription update: refresh request and fetch immediately so\n // newly held / still-unpriced assets (e.g. seeded natives) do not wait\n // for the next poll tick. Deduper freshness TTL skips recently priced IDs.\n if (isUpdate) {\n const existing = this.#activeSubscriptions.get(subscriptionId);\n if (existing) {\n existing.request = request;\n existing.onAssetsUpdate = subscriptionRequest.onAssetsUpdate;\n\n try {\n const fetchResponse = await this.fetch(request);\n if (\n fetchResponse.assetsPrice &&\n Object.keys(fetchResponse.assetsPrice).length > 0\n ) {\n await existing.onAssetsUpdate({\n ...fetchResponse,\n updateMode: 'merge',\n });\n }\n await this.#reconcileMarketStats();\n } catch (error) {\n log('Subscription update fetch failed', { subscriptionId, error });\n }\n return;\n }\n }\n\n // Clean up existing subscription\n await this.unsubscribe(subscriptionId);\n\n const pollInterval = request.updateInterval ?? this.#pollInterval;\n this.#effectivePollInterval = pollInterval;\n\n // Cap the freshness TTL strictly below the effective poll interval.\n // `fetchedAt` is stamped when a fetch completes (slightly after the tick\n // that triggered it), so a TTL equal to the poll interval would leave the\n // asset still \"fresh\" at the next tick, making the subscription re-fetch\n // only every other poll. The margin also absorbs network latency / jitter.\n this.#deduper.freshnessTtlMs = Math.min(\n this.#deduper.freshnessTtlMs,\n Math.floor(pollInterval * FRESHNESS_TTL_POLL_RATIO),\n );\n\n // Each tick skips assets `getSubscriptions` already has open on a healthy chain.\n const timer = setInterval(() => {\n this.#runPoll(subscriptionId).catch((error: unknown) => {\n log('Subscription poll failed', { subscriptionId, error });\n });\n }, pollInterval);\n\n // Store subscription\n this.#activeSubscriptions.set(subscriptionId, {\n cleanup: () => {\n clearInterval(timer);\n },\n request,\n onAssetsUpdate: subscriptionRequest.onAssetsUpdate,\n });\n\n // Initial fetch\n await this.#runPoll(subscriptionId);\n }\n\n /**\n * Unsubscribe from price updates.\n *\n * @param subscriptionId - The ID of the subscription to cancel.\n */\n async unsubscribe(subscriptionId: string): Promise<void> {\n const subscription = this.#activeSubscriptions.get(subscriptionId);\n if (!subscription) {\n return;\n }\n\n subscription.cleanup();\n this.#activeSubscriptions.delete(subscriptionId);\n\n if (this.#activeSubscriptions.size === 0) {\n this.#clearFallbackTimer();\n await this.#marketStats.releaseSubscriptions();\n return;\n }\n\n await this.#reconcileMarketStats();\n }\n\n /**\n * Drop market-stats channels and open them again for the current currency.\n * Called when the selected currency changes so batches match `assetsPrice`.\n */\n async resubscribeForCurrencyChange(): Promise<void> {\n if (this.#activeSubscriptions.size === 0) {\n return;\n }\n\n await this.#marketStats.releaseSubscriptions();\n await this.#reconcileMarketStats();\n }\n\n /**\n * Align market-stats channels with the price-fetch set and the `wssSupport`\n * already stored in `assetsPrice`.\n *\n * The poll calls this after it writes the spot-price response. A balance\n * update does not. Stored flags can be from an earlier response, and\n * subscribing from them opens channels the latest response marks\n * `wssSupport: false`. A new balance waits for the next poll.\n */\n async reconcileMarketStreams(): Promise<void> {\n if (this.#activeSubscriptions.size === 0) {\n return;\n }\n await this.#reconcileMarketStats();\n }\n\n /**\n * Invalidate the price freshness cache, forcing the next fetch to call the\n * API regardless of TTL. Use when external state changes (e.g. selected\n * currency) require a full refresh.\n */\n invalidatePriceCache(): void {\n this.#deduper.invalidate();\n }\n\n /**\n * Destroy the data source and clean up all subscriptions.\n */\n destroy(): void {\n for (const subscription of this.#activeSubscriptions.values()) {\n subscription.cleanup();\n }\n this.#activeSubscriptions.clear();\n this.#clearFallbackTimer();\n this.#marketStats.destroy();\n this.#deduper.destroy();\n }\n\n /**\n * One poll tick: REST-fetch assets that are not streaming, then align the\n * market-stats subscription with what the latest spot response can stream.\n *\n * @param subscriptionId - Active subscription to poll.\n */\n async #runPoll(subscriptionId: string): Promise<void> {\n const subscription = this.#activeSubscriptions.get(subscriptionId);\n if (!subscription) {\n return;\n }\n\n try {\n const assetIds = await this.#filterToSupportedPriceableAssets(\n this.#getAssetIdsFromBalanceState(subscription.request),\n );\n const now = Date.now();\n const [subscribed, downChains] = await Promise.all([\n this.#marketStats.subscribedAssetIds(),\n this.#marketStats.downChainIds(),\n ]);\n const idsToFetch = assetIds.filter((assetId) =>\n this.#marketStats.shouldPoll(assetId, now, subscribed, downChains),\n );\n\n const fetchResponse = await this.#fetchAssetIdList(idsToFetch);\n if (\n fetchResponse.assetsPrice &&\n Object.keys(fetchResponse.assetsPrice).length > 0\n ) {\n await subscription.onAssetsUpdate({\n ...fetchResponse,\n updateMode: 'merge',\n });\n }\n\n await this.#reconcileMarketStats();\n } catch (error) {\n log('Subscription poll failed', { subscriptionId, error });\n }\n }\n\n async #reconcileMarketStats(): Promise<void> {\n const assetIds = new Set<Caip19AssetId>();\n for (const subscription of this.#activeSubscriptions.values()) {\n const ids = await this.#filterToSupportedPriceableAssets(\n this.#getAssetIdsFromBalanceState(subscription.request),\n );\n for (const assetId of ids) {\n assetIds.add(assetId);\n }\n }\n\n await this.#marketStats.reconcile(this.#candidatesFor([...assetIds]));\n }\n\n #candidatesFor(assetIds: Caip19AssetId[]): StreamCandidate[] {\n const prices = this.#getAssetsState().assetsPrice ?? {};\n return assetIds.map((assetId) => ({\n assetId,\n wssSupport:\n prices[assetId] !== undefined &&\n readSpotPriceStreamEligibility(prices[assetId]),\n }));\n }\n\n #invalidateChains(chainIds: string[]): void {\n const chains = new Set(chainIds);\n const assetIds = Object.keys(\n this.#getAssetsState().assetsPrice ?? {},\n ).filter((assetId) => {\n const chainId = chainIdFromAssetId(assetId);\n return chainId !== undefined && chains.has(chainId);\n }) as Caip19AssetId[];\n if (assetIds.length > 0) {\n this.#deduper.invalidateKeys(assetIds);\n }\n }\n\n #scheduleStreamPoll(delayMs: number): void {\n this.#clearFallbackTimer();\n this.#fallbackTimer = setTimeout(() => {\n this.#fallbackTimer = undefined;\n for (const subscriptionId of this.#activeSubscriptions.keys()) {\n this.#runPoll(subscriptionId).catch((error: unknown) => {\n log('Market stats fallback poll failed', { subscriptionId, error });\n });\n }\n }, delayMs);\n }\n\n #clearFallbackTimer(): void {\n if (this.#fallbackTimer) {\n clearTimeout(this.#fallbackTimer);\n this.#fallbackTimer = undefined;\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 { CustomAssetGraduationMiddleware, RpcFallbackMiddleware, } from './middlewares/index.js';
|
|
21
21
|
export type { CustomAssetGraduationMiddlewareOptions, RpcFallbackMiddlewareOptions, } from './middlewares/index.js';
|
|
22
|
+
export { MarketStatsStore, marketStatsAssetKey, readLiveQuote, } from './store/MarketStatsStore.js';
|
|
23
|
+
export type { LiveQuote, LivePriceMap } from './store/MarketStatsStore.js';
|
|
22
24
|
export { normalizeAssetId, formatExchangeRatesForBridge, formatStateForTransactionPay, } from './utils/index.js';
|
|
23
25
|
export type { AccountForLegacyFormat, BridgeExchangeRatesFormat, FormatExchangeRatesForBridgeParams, FormatStateForTransactionPayParams, LegacyToken, TransactionPayLegacyFormat, } from './utils/index.js';
|
|
24
26
|
export { calculateBalanceForAllWallets, calculateBalanceChangeForAccountGroup, getAggregatedBalanceForAccount, getGroupIdForAccount, getInternalAccountsForGroup, } from './selectors/balance.js';
|