-
-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathPriceDataSource.ts
More file actions
509 lines (440 loc) · 15.7 KB
/
PriceDataSource.ts
File metadata and controls
509 lines (440 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
import type {
SupportedCurrency,
V3SpotPricesResponse,
} from '@metamask/core-backend';
import { ApiPlatformClient } from '@metamask/core-backend';
import { parseCaipAssetType } from '@metamask/utils';
import pLimit from 'p-limit';
import type { SubscriptionRequest } from './AbstractDataSource';
import { projectLogger, createModuleLogger } from '../logger';
import { forDataTypes } from '../types';
import type {
Caip19AssetId,
DataRequest,
DataResponse,
FungibleAssetPrice,
Middleware,
AssetsControllerStateInternal,
} from '../types';
// ============================================================================
// CONSTANTS
// ============================================================================
const CONTROLLER_NAME = 'PriceDataSource';
const DEFAULT_POLL_INTERVAL = 60_000; // 1 minute for price updates
/** Price API v3 spot-prices accepts at most this many `assetIds` per request (same cap as tokens `/v3/assets`). */
const V3_SPOT_PRICES_MAX_IDS_PER_REQUEST = 120;
/** Max concurrent spot-price chunk requests (aligned with TokenDataSource metadata fetches). */
const V3_SPOT_PRICES_FETCH_CONCURRENCY = 3;
const log = createModuleLogger(projectLogger, CONTROLLER_NAME);
// ============================================================================
// OPTIONS
// ============================================================================
/** Optional configuration for PriceDataSource. */
export type PriceDataSourceConfig = {
/** Polling interval in ms (default: 60000) */
pollInterval?: number;
};
export type PriceDataSourceOptions = PriceDataSourceConfig & {
/** ApiPlatformClient for API calls with caching */
queryApiClient: ApiPlatformClient;
/** Function returning the currently-active ISO 4217 currency code */
getSelectedCurrency: () => SupportedCurrency;
};
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
/**
* Asset reference patterns that should NOT be sent to the Price API.
* These are internal resource tracking values without market prices.
*/
const NON_PRICEABLE_ASSET_PATTERNS = [
// Tron resource assets (bandwidth, energy, staking states)
/\/slip44:\d+-staked-for-/u,
/\/slip44:bandwidth$/u,
/\/slip44:energy$/u,
/\/slip44:maximum-bandwidth$/u,
/\/slip44:maximum-energy$/u,
];
/**
* Check if an asset ID represents a priceable asset.
* Filters out internal resource tracking values that don't have market prices.
*
* @param assetId - The CAIP-19 asset ID to check.
* @returns True if the asset has market price data.
*/
function isPriceableAsset(assetId: Caip19AssetId): boolean {
return !NON_PRICEABLE_ASSET_PATTERNS.some((pattern) => pattern.test(assetId));
}
/** Market data item from spot prices response (same as FungibleAssetPrice without lastUpdated) */
type SpotPriceMarketData = Omit<
FungibleAssetPrice,
'lastUpdated' | 'assetPriceType'
>;
/**
* Type guard to check if market data has a valid price
*
* @param data - The data to check.
* @returns True if data is valid SpotPriceMarketData.
*/
function isValidMarketData(data: unknown): data is SpotPriceMarketData {
return (
typeof data === 'object' &&
data !== null &&
'price' in data &&
typeof data.price === 'number'
);
}
// ============================================================================
// PRICE DATA SOURCE
// ============================================================================
/**
* PriceDataSource fetches asset prices from the Price API.
*
* This data source:
* - Fetches prices from Price API v3 spot-prices endpoint
* - Supports one-time fetch and subscription-based polling
* - In subscribe mode, uses getAssetsState from SubscriptionRequest to read assetsBalance and fetch prices
*
* Usage: Create with queryApiClient; subscribe() requires getAssetsState in the request for balance-based pricing.
*/
export class PriceDataSource {
static readonly controllerName = CONTROLLER_NAME;
getName(): string {
return PriceDataSource.controllerName;
}
readonly #getSelectedCurrency: () => SupportedCurrency;
readonly #pollInterval: number;
/** ApiPlatformClient for cached API calls */
readonly #apiClient: ApiPlatformClient;
/** Active subscriptions by ID */
readonly #activeSubscriptions: Map<
string,
{
cleanup: () => void;
request: DataRequest;
onAssetsUpdate: (response: DataResponse) => void | Promise<void>;
getAssetsState?: () => AssetsControllerStateInternal;
}
> = new Map();
constructor(options: PriceDataSourceOptions) {
this.#getSelectedCurrency = options.getSelectedCurrency;
this.#pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL;
this.#apiClient = options.queryApiClient;
}
// ============================================================================
// MIDDLEWARE
// ============================================================================
/**
* Get the middleware for enriching responses with price data.
*
* This middleware:
* 1. Extracts the response from context
* 2. Fetches prices for detected assets (assets without metadata)
* 3. Enriches the response with fetched prices
* 4. Calls next() at the end to continue the middleware chain
*
* Note: This middleware ONLY fetches prices for detected assets.
* For fetching prices for all assets, use the subscription mechanism
* which polls prices for all assets in the balance state.
*
* @returns The middleware function for the assets pipeline.
*/
get assetsMiddleware(): Middleware {
return forDataTypes(['price'], async (ctx, next) => {
// Extract response from context
const { response, request } = ctx;
// Only fetch prices for detected assets (assets without metadata)
// The subscription handles fetching prices for all existing assets
if (!response.detectedAssets && !request.assetsForPriceUpdate?.length) {
return next(ctx);
}
const assetIds = new Set<Caip19AssetId>();
for (const detectedAccountAssets of Object.values(
response.detectedAssets ?? {},
)) {
for (const assetId of detectedAccountAssets) {
assetIds.add(assetId);
}
}
for (const assetId of request.assetsForPriceUpdate ?? []) {
assetIds.add(assetId);
}
if (assetIds.size === 0) {
return next(ctx);
}
// Filter to only priceable assets
const priceableAssetIds = [...assetIds].filter(isPriceableAsset);
if (priceableAssetIds.length === 0) {
return next(ctx);
}
try {
const spotPrices = await this.#fetchSpotPrices(priceableAssetIds);
response.assetsPrice = {
...(response.assetsPrice ?? {}),
...spotPrices,
};
} catch (error) {
log('Failed to fetch prices via middleware', { error });
}
// Call next() at the end to continue the middleware chain
return next(ctx);
});
}
// ============================================================================
// HELPERS
// ============================================================================
/**
* Fetch spot prices with caching and deduplication via query service.
*
* @param assetIds - Array of CAIP-19 asset IDs
* @returns Spot prices response
*/
async #fetchSpotPrices(
assetIds: string[],
): Promise<Record<Caip19AssetId, FungibleAssetPrice>> {
if (assetIds.length === 0) {
return {};
}
const selectedCurrency = this.#getSelectedCurrency();
const chunks: string[][] = [];
for (
let i = 0;
i < assetIds.length;
i += V3_SPOT_PRICES_MAX_IDS_PER_REQUEST
) {
chunks.push(assetIds.slice(i, i + V3_SPOT_PRICES_MAX_IDS_PER_REQUEST));
}
const limit = pLimit(V3_SPOT_PRICES_FETCH_CONCURRENCY);
const queryOpts = { includeMarketData: true as const };
const selectedChunkResults = await Promise.all(
chunks.map((chunk) =>
limit(() =>
this.#apiClient.prices.fetchV3SpotPrices(chunk, {
currency: selectedCurrency,
...queryOpts,
}),
),
),
);
const selectedCurrencyPrices = Object.assign({}, ...selectedChunkResults);
let usdPrices: V3SpotPricesResponse;
if (selectedCurrency === 'usd') {
usdPrices = selectedCurrencyPrices;
} else {
const usdChunkResults = await Promise.all(
chunks.map((chunk) =>
limit(() =>
this.#apiClient.prices.fetchV3SpotPrices(chunk, {
currency: 'usd',
...queryOpts,
}),
),
),
);
usdPrices = Object.assign({}, ...usdChunkResults);
}
const prices: Record<Caip19AssetId, FungibleAssetPrice> = {};
for (const [assetId, marketData] of Object.entries(
selectedCurrencyPrices,
)) {
const usdMarketData = usdPrices[assetId];
// Skip assets with invalid market data (API doesn't have price for this asset is selected currency or USD)
if (!isValidMarketData(marketData) || !isValidMarketData(usdMarketData)) {
continue;
}
const caipAssetId = assetId as Caip19AssetId;
prices[caipAssetId] = {
...marketData,
assetPriceType: 'fungible',
usdPrice: usdMarketData.price,
lastUpdated: Date.now(),
};
}
return prices;
}
/**
* Get unique asset IDs from the assetsBalance state.
* Filters by accounts and chains from the request.
*
* @param request - Data request with accounts and chainIds filters.
* @param getAssetsState - State access; when omitted, returns [].
* @returns Array of CAIP-19 asset IDs from balance state.
*/
#getAssetIdsFromBalanceState(
request: DataRequest,
getAssetsState?: () => AssetsControllerStateInternal,
): Caip19AssetId[] {
if (!getAssetsState) {
return [];
}
try {
const state = getAssetsState();
const assetIds = new Set<Caip19AssetId>();
const accountIds = request.accountsWithSupportedChains.map(
(a) => a.account.id,
);
const accountFilter =
accountIds.length > 0 ? new Set(accountIds) : undefined;
const chainFilter =
request.chainIds.length > 0 ? new Set(request.chainIds) : undefined;
if (state?.assetsBalance) {
for (const [accountId, accountBalances] of Object.entries(
state.assetsBalance,
)) {
// Filter by account if specified
if (accountFilter && !accountFilter.has(accountId)) {
continue;
}
for (const assetId of Object.keys(
accountBalances as Record<string, unknown>,
)) {
// Filter by chain if specified; skip malformed asset IDs for this entry only
if (chainFilter) {
try {
const { chainId } = parseCaipAssetType(
assetId as Caip19AssetId,
);
if (!chainFilter.has(chainId)) {
continue;
}
} catch (error) {
log('Skipping malformed asset ID in balance state', {
assetId,
error,
});
continue;
}
}
assetIds.add(assetId as Caip19AssetId);
}
}
}
return [...assetIds];
} catch (error) {
log('Failed to get asset IDs from balance state', { error });
return [];
}
}
// ============================================================================
// FETCH
// ============================================================================
/**
* Fetch prices for assets held by the accounts and chains in the request.
* When getAssetsState is provided, gets asset IDs from balance state; otherwise returns empty.
*
* @param request - The data request specifying accounts and chains.
* @param getAssetsState - Optional state access (e.g. from SubscriptionRequest).
* @returns DataResponse containing asset prices.
*/
async fetch(
request: DataRequest,
getAssetsState?: () => AssetsControllerStateInternal,
): Promise<DataResponse> {
const response: DataResponse = {};
// Get asset IDs from balance state when state access is provided
const rawAssetIds = this.#getAssetIdsFromBalanceState(
request,
getAssetsState,
);
// Filter out non-priceable assets (e.g., Tron bandwidth/energy resources)
const assetIds = rawAssetIds.filter(isPriceableAsset);
if (assetIds.length === 0) {
return response;
}
try {
const spotPrices = await this.#fetchSpotPrices([...assetIds]);
response.assetsPrice = {
...(response.assetsPrice ?? {}),
...spotPrices,
};
} catch (error) {
log('Failed to fetch prices', { error });
}
return response;
}
// ============================================================================
// SUBSCRIBE
// ============================================================================
/**
* Subscribe to price updates.
* Sets up polling that fetches prices for all assets in assetsBalance state.
*
* @param subscriptionRequest - The subscription request configuration.
*/
async subscribe(subscriptionRequest: SubscriptionRequest): Promise<void> {
const { request, subscriptionId, isUpdate } = subscriptionRequest;
// Handle subscription update - just update the request
if (isUpdate) {
const existing = this.#activeSubscriptions.get(subscriptionId);
if (existing) {
existing.request = request;
return;
}
}
// Clean up existing subscription
await this.unsubscribe(subscriptionId);
const pollInterval = request.updateInterval ?? this.#pollInterval;
// Create poll function - fetches prices using getAssetsState from subscription
const pollFn = async (): Promise<void> => {
try {
const subscription = this.#activeSubscriptions.get(subscriptionId);
if (!subscription) {
return;
}
// Fetch prices for all assets in balance state (uses subscription's getAssetsState)
const fetchResponse = await this.fetch(
subscription.request,
subscription.getAssetsState,
);
// Only report if we got prices
if (
fetchResponse.assetsPrice &&
Object.keys(fetchResponse.assetsPrice).length > 0
) {
await subscription.onAssetsUpdate({
...fetchResponse,
updateMode: 'merge',
});
}
} catch (error) {
log('Subscription poll failed', { subscriptionId, error });
}
};
// Set up polling
const timer = setInterval(() => {
pollFn().catch(console.error);
}, pollInterval);
// Store subscription (getAssetsState from request for balance-based pricing)
this.#activeSubscriptions.set(subscriptionId, {
cleanup: () => {
clearInterval(timer);
},
request,
onAssetsUpdate: subscriptionRequest.onAssetsUpdate,
getAssetsState: subscriptionRequest.getAssetsState,
});
// Initial fetch
await pollFn();
}
/**
* Unsubscribe from price updates.
*
* @param subscriptionId - The ID of the subscription to cancel.
*/
async unsubscribe(subscriptionId: string): Promise<void> {
const subscription = this.#activeSubscriptions.get(subscriptionId);
if (subscription) {
subscription.cleanup();
this.#activeSubscriptions.delete(subscriptionId);
}
}
/**
* Destroy the data source and clean up all subscriptions.
*/
destroy(): void {
for (const subscription of this.#activeSubscriptions.values()) {
subscription.cleanup();
}
this.#activeSubscriptions.clear();
}
}