@metamask-previews/assets-controller 0.2.0-preview-c3cd77f → 0.2.0-preview-d01b2f93d
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 +4 -0
- package/dist/AssetsController-method-action-types.cjs +7 -0
- package/dist/AssetsController-method-action-types.cjs.map +1 -0
- package/dist/AssetsController-method-action-types.d.cts +78 -0
- package/dist/AssetsController-method-action-types.d.cts.map +1 -0
- package/dist/AssetsController-method-action-types.d.mts +78 -0
- package/dist/AssetsController-method-action-types.d.mts.map +1 -0
- package/dist/AssetsController-method-action-types.mjs +6 -0
- package/dist/AssetsController-method-action-types.mjs.map +1 -0
- package/dist/AssetsController.cjs +161 -116
- package/dist/AssetsController.cjs.map +1 -1
- package/dist/AssetsController.d.cts +23 -80
- package/dist/AssetsController.d.cts.map +1 -1
- package/dist/AssetsController.d.mts +23 -80
- package/dist/AssetsController.d.mts.map +1 -1
- package/dist/AssetsController.mjs +161 -116
- package/dist/AssetsController.mjs.map +1 -1
- package/dist/data-sources/AbstractDataSource.cjs.map +1 -1
- package/dist/data-sources/AbstractDataSource.d.cts +10 -1
- package/dist/data-sources/AbstractDataSource.d.cts.map +1 -1
- package/dist/data-sources/AbstractDataSource.d.mts +10 -1
- package/dist/data-sources/AbstractDataSource.d.mts.map +1 -1
- package/dist/data-sources/AbstractDataSource.mjs.map +1 -1
- package/dist/data-sources/AccountsApiDataSource.cjs +23 -99
- package/dist/data-sources/AccountsApiDataSource.cjs.map +1 -1
- package/dist/data-sources/AccountsApiDataSource.d.cts +5 -67
- package/dist/data-sources/AccountsApiDataSource.d.cts.map +1 -1
- package/dist/data-sources/AccountsApiDataSource.d.mts +5 -67
- package/dist/data-sources/AccountsApiDataSource.d.mts.map +1 -1
- package/dist/data-sources/AccountsApiDataSource.mjs +22 -97
- package/dist/data-sources/AccountsApiDataSource.mjs.map +1 -1
- package/dist/data-sources/BackendWebsocketDataSource.cjs +135 -45
- package/dist/data-sources/BackendWebsocketDataSource.cjs.map +1 -1
- package/dist/data-sources/BackendWebsocketDataSource.d.cts +19 -66
- package/dist/data-sources/BackendWebsocketDataSource.d.cts.map +1 -1
- package/dist/data-sources/BackendWebsocketDataSource.d.mts +19 -66
- package/dist/data-sources/BackendWebsocketDataSource.d.mts.map +1 -1
- package/dist/data-sources/BackendWebsocketDataSource.mjs +135 -45
- package/dist/data-sources/BackendWebsocketDataSource.mjs.map +1 -1
- package/dist/data-sources/PriceDataSource.cjs +22 -44
- package/dist/data-sources/PriceDataSource.cjs.map +1 -1
- package/dist/data-sources/PriceDataSource.d.cts +6 -89
- package/dist/data-sources/PriceDataSource.d.cts.map +1 -1
- package/dist/data-sources/PriceDataSource.d.mts +6 -89
- package/dist/data-sources/PriceDataSource.d.mts.map +1 -1
- package/dist/data-sources/PriceDataSource.mjs +22 -44
- package/dist/data-sources/PriceDataSource.mjs.map +1 -1
- package/dist/data-sources/RpcDataSource.cjs +57 -98
- package/dist/data-sources/RpcDataSource.cjs.map +1 -1
- package/dist/data-sources/RpcDataSource.d.cts +16 -55
- package/dist/data-sources/RpcDataSource.d.cts.map +1 -1
- package/dist/data-sources/RpcDataSource.d.mts +16 -55
- package/dist/data-sources/RpcDataSource.d.mts.map +1 -1
- package/dist/data-sources/RpcDataSource.mjs +57 -98
- package/dist/data-sources/RpcDataSource.mjs.map +1 -1
- package/dist/data-sources/SnapDataSource.cjs +30 -30
- package/dist/data-sources/SnapDataSource.cjs.map +1 -1
- package/dist/data-sources/SnapDataSource.d.cts +7 -44
- package/dist/data-sources/SnapDataSource.d.cts.map +1 -1
- package/dist/data-sources/SnapDataSource.d.mts +7 -44
- package/dist/data-sources/SnapDataSource.d.mts.map +1 -1
- package/dist/data-sources/SnapDataSource.mjs +30 -30
- package/dist/data-sources/SnapDataSource.mjs.map +1 -1
- package/dist/data-sources/TokenDataSource.cjs +3 -16
- package/dist/data-sources/TokenDataSource.cjs.map +1 -1
- package/dist/data-sources/TokenDataSource.d.cts +2 -25
- package/dist/data-sources/TokenDataSource.d.cts.map +1 -1
- package/dist/data-sources/TokenDataSource.d.mts +2 -25
- package/dist/data-sources/TokenDataSource.d.mts.map +1 -1
- package/dist/data-sources/TokenDataSource.mjs +3 -16
- package/dist/data-sources/TokenDataSource.mjs.map +1 -1
- package/dist/data-sources/index.cjs +1 -6
- package/dist/data-sources/index.cjs.map +1 -1
- package/dist/data-sources/index.d.cts +6 -7
- package/dist/data-sources/index.d.cts.map +1 -1
- package/dist/data-sources/index.d.mts +6 -7
- package/dist/data-sources/index.d.mts.map +1 -1
- package/dist/data-sources/index.mjs +1 -3
- package/dist/data-sources/index.mjs.map +1 -1
- package/dist/index.cjs +1 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -11
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +9 -11
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -3
- package/dist/index.mjs.map +1 -1
- package/dist/middlewares/DetectionMiddleware.cjs +4 -27
- package/dist/middlewares/DetectionMiddleware.cjs.map +1 -1
- package/dist/middlewares/DetectionMiddleware.d.cts +3 -26
- package/dist/middlewares/DetectionMiddleware.d.cts.map +1 -1
- package/dist/middlewares/DetectionMiddleware.d.mts +3 -26
- package/dist/middlewares/DetectionMiddleware.d.mts.map +1 -1
- package/dist/middlewares/DetectionMiddleware.mjs +4 -27
- package/dist/middlewares/DetectionMiddleware.mjs.map +1 -1
- package/dist/middlewares/index.cjs.map +1 -1
- package/dist/middlewares/index.d.cts +1 -1
- package/dist/middlewares/index.d.cts.map +1 -1
- package/dist/middlewares/index.d.mts +1 -1
- package/dist/middlewares/index.d.mts.map +1 -1
- package/dist/middlewares/index.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +52 -3
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +52 -3
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/data-sources/initDataSources.cjs +0 -215
- package/dist/data-sources/initDataSources.cjs.map +0 -1
- package/dist/data-sources/initDataSources.d.cts +0 -140
- package/dist/data-sources/initDataSources.d.cts.map +0 -1
- package/dist/data-sources/initDataSources.d.mts +0 -140
- package/dist/data-sources/initDataSources.d.mts.map +0 -1
- package/dist/data-sources/initDataSources.mjs +0 -210
- package/dist/data-sources/initDataSources.mjs.map +0 -1
|
@@ -10,7 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
10
10
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
11
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
12
|
};
|
|
13
|
-
var _PriceDataSource_instances,
|
|
13
|
+
var _PriceDataSource_instances, _PriceDataSource_currency, _PriceDataSource_pollInterval, _PriceDataSource_apiClient, _PriceDataSource_activeSubscriptions, _PriceDataSource_fetchSpotPrices, _PriceDataSource_getAssetIdsFromBalanceState;
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
exports.PriceDataSource = void 0;
|
|
16
16
|
const core_backend_1 = require("@metamask/core-backend");
|
|
@@ -68,44 +68,23 @@ function isValidMarketData(data) {
|
|
|
68
68
|
* This data source:
|
|
69
69
|
* - Fetches prices from Price API v3 spot-prices endpoint
|
|
70
70
|
* - Supports one-time fetch and subscription-based polling
|
|
71
|
-
* - In subscribe mode,
|
|
72
|
-
* - Publishes price updates via messenger events
|
|
71
|
+
* - In subscribe mode, uses getAssetsState from SubscriptionRequest to read assetsBalance and fetch prices
|
|
73
72
|
*
|
|
74
|
-
* Usage:
|
|
75
|
-
* ```typescript
|
|
76
|
-
* // Create and initialize (registers messenger actions)
|
|
77
|
-
* const priceDataSource = new PriceDataSource({ messenger });
|
|
78
|
-
*
|
|
79
|
-
* // One-time fetch for specific assets
|
|
80
|
-
* const response = await messenger.call('PriceDataSource:fetch', {
|
|
81
|
-
* customAssets: ['eip155:1/erc20:0x...'],
|
|
82
|
-
* });
|
|
83
|
-
*
|
|
84
|
-
* // Subscribe to price updates (polls all assets in balance state)
|
|
85
|
-
* await messenger.call('PriceDataSource:subscribe', { request, subscriptionId });
|
|
86
|
-
*
|
|
87
|
-
* // Listen for updates
|
|
88
|
-
* messenger.subscribe('PriceDataSource:assetsUpdated', (response) => {
|
|
89
|
-
* // Handle price updates
|
|
90
|
-
* });
|
|
91
|
-
* ```
|
|
73
|
+
* Usage: Create with queryApiClient; subscribe() requires getAssetsState in the request for balance-based pricing.
|
|
92
74
|
*/
|
|
93
75
|
class PriceDataSource {
|
|
94
76
|
constructor(options) {
|
|
95
77
|
_PriceDataSource_instances.add(this);
|
|
96
78
|
this.name = CONTROLLER_NAME;
|
|
97
|
-
_PriceDataSource_messenger.set(this, void 0);
|
|
98
79
|
_PriceDataSource_currency.set(this, void 0);
|
|
99
80
|
_PriceDataSource_pollInterval.set(this, void 0);
|
|
100
81
|
/** ApiPlatformClient for cached API calls */
|
|
101
82
|
_PriceDataSource_apiClient.set(this, void 0);
|
|
102
83
|
/** Active subscriptions by ID */
|
|
103
84
|
_PriceDataSource_activeSubscriptions.set(this, new Map());
|
|
104
|
-
__classPrivateFieldSet(this, _PriceDataSource_messenger, options.messenger, "f");
|
|
105
85
|
__classPrivateFieldSet(this, _PriceDataSource_currency, options.currency ?? 'usd', "f");
|
|
106
86
|
__classPrivateFieldSet(this, _PriceDataSource_pollInterval, options.pollInterval ?? DEFAULT_POLL_INTERVAL, "f");
|
|
107
87
|
__classPrivateFieldSet(this, _PriceDataSource_apiClient, options.queryApiClient, "f");
|
|
108
|
-
__classPrivateFieldGet(this, _PriceDataSource_instances, "m", _PriceDataSource_registerActionHandlers).call(this);
|
|
109
88
|
}
|
|
110
89
|
// ============================================================================
|
|
111
90
|
// MIDDLEWARE
|
|
@@ -174,15 +153,16 @@ class PriceDataSource {
|
|
|
174
153
|
// ============================================================================
|
|
175
154
|
/**
|
|
176
155
|
* Fetch prices for assets held by the accounts and chains in the request.
|
|
177
|
-
*
|
|
156
|
+
* When getAssetsState is provided, gets asset IDs from balance state; otherwise returns empty.
|
|
178
157
|
*
|
|
179
158
|
* @param request - The data request specifying accounts and chains.
|
|
159
|
+
* @param getAssetsState - Optional state access (e.g. from SubscriptionRequest).
|
|
180
160
|
* @returns DataResponse containing asset prices.
|
|
181
161
|
*/
|
|
182
|
-
async fetch(request) {
|
|
162
|
+
async fetch(request, getAssetsState) {
|
|
183
163
|
const response = {};
|
|
184
|
-
// Get asset IDs from balance state
|
|
185
|
-
const rawAssetIds = __classPrivateFieldGet(this, _PriceDataSource_instances, "m", _PriceDataSource_getAssetIdsFromBalanceState).call(this, request);
|
|
164
|
+
// Get asset IDs from balance state when state access is provided
|
|
165
|
+
const rawAssetIds = __classPrivateFieldGet(this, _PriceDataSource_instances, "m", _PriceDataSource_getAssetIdsFromBalanceState).call(this, request, getAssetsState);
|
|
186
166
|
// Filter out non-priceable assets (e.g., Tron bandwidth/energy resources)
|
|
187
167
|
const assetIds = rawAssetIds.filter(isPriceableAsset);
|
|
188
168
|
if (assetIds.length === 0) {
|
|
@@ -230,19 +210,19 @@ class PriceDataSource {
|
|
|
230
210
|
// Clean up existing subscription
|
|
231
211
|
await this.unsubscribe(subscriptionId);
|
|
232
212
|
const pollInterval = request.updateInterval ?? __classPrivateFieldGet(this, _PriceDataSource_pollInterval, "f");
|
|
233
|
-
// Create poll function - fetches prices
|
|
213
|
+
// Create poll function - fetches prices using getAssetsState from subscription
|
|
234
214
|
const pollFn = async () => {
|
|
235
215
|
try {
|
|
236
216
|
const subscription = __classPrivateFieldGet(this, _PriceDataSource_activeSubscriptions, "f").get(subscriptionId);
|
|
237
217
|
if (!subscription) {
|
|
238
218
|
return;
|
|
239
219
|
}
|
|
240
|
-
// Fetch prices for all assets
|
|
241
|
-
const fetchResponse = await this.fetch(subscription.request);
|
|
220
|
+
// Fetch prices for all assets in balance state (uses subscription's getAssetsState)
|
|
221
|
+
const fetchResponse = await this.fetch(subscription.request, subscription.getAssetsState);
|
|
242
222
|
// Only report if we got prices
|
|
243
223
|
if (fetchResponse.assetsPrice &&
|
|
244
224
|
Object.keys(fetchResponse.assetsPrice).length > 0) {
|
|
245
|
-
await
|
|
225
|
+
await subscription.onAssetsUpdate(fetchResponse);
|
|
246
226
|
}
|
|
247
227
|
}
|
|
248
228
|
catch (error) {
|
|
@@ -253,12 +233,14 @@ class PriceDataSource {
|
|
|
253
233
|
const timer = setInterval(() => {
|
|
254
234
|
pollFn().catch(console.error);
|
|
255
235
|
}, pollInterval);
|
|
256
|
-
// Store subscription
|
|
236
|
+
// Store subscription (getAssetsState from request for balance-based pricing)
|
|
257
237
|
__classPrivateFieldGet(this, _PriceDataSource_activeSubscriptions, "f").set(subscriptionId, {
|
|
258
238
|
cleanup: () => {
|
|
259
239
|
clearInterval(timer);
|
|
260
240
|
},
|
|
261
241
|
request,
|
|
242
|
+
onAssetsUpdate: subscriptionRequest.onAssetsUpdate,
|
|
243
|
+
getAssetsState: subscriptionRequest.getAssetsState,
|
|
262
244
|
});
|
|
263
245
|
// Initial fetch
|
|
264
246
|
await pollFn();
|
|
@@ -286,14 +268,7 @@ class PriceDataSource {
|
|
|
286
268
|
}
|
|
287
269
|
}
|
|
288
270
|
exports.PriceDataSource = PriceDataSource;
|
|
289
|
-
|
|
290
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
291
|
-
const messenger = __classPrivateFieldGet(this, _PriceDataSource_messenger, "f");
|
|
292
|
-
messenger.registerActionHandler('PriceDataSource:getAssetsMiddleware', () => this.assetsMiddleware);
|
|
293
|
-
messenger.registerActionHandler('PriceDataSource:fetch', (request) => this.fetch(request));
|
|
294
|
-
messenger.registerActionHandler('PriceDataSource:subscribe', (subscriptionRequest) => this.subscribe(subscriptionRequest));
|
|
295
|
-
messenger.registerActionHandler('PriceDataSource:unsubscribe', (subscriptionId) => this.unsubscribe(subscriptionId));
|
|
296
|
-
}, _PriceDataSource_fetchSpotPrices =
|
|
271
|
+
_PriceDataSource_currency = new WeakMap(), _PriceDataSource_pollInterval = new WeakMap(), _PriceDataSource_apiClient = new WeakMap(), _PriceDataSource_activeSubscriptions = new WeakMap(), _PriceDataSource_instances = new WeakSet(), _PriceDataSource_fetchSpotPrices =
|
|
297
272
|
// ============================================================================
|
|
298
273
|
// HELPERS
|
|
299
274
|
// ============================================================================
|
|
@@ -308,11 +283,14 @@ async function _PriceDataSource_fetchSpotPrices(assetIds) {
|
|
|
308
283
|
currency: __classPrivateFieldGet(this, _PriceDataSource_currency, "f"),
|
|
309
284
|
includeMarketData: true,
|
|
310
285
|
});
|
|
311
|
-
}, _PriceDataSource_getAssetIdsFromBalanceState = function _PriceDataSource_getAssetIdsFromBalanceState(request) {
|
|
286
|
+
}, _PriceDataSource_getAssetIdsFromBalanceState = function _PriceDataSource_getAssetIdsFromBalanceState(request, getAssetsState) {
|
|
287
|
+
if (!getAssetsState) {
|
|
288
|
+
return [];
|
|
289
|
+
}
|
|
312
290
|
try {
|
|
313
|
-
const state =
|
|
291
|
+
const state = getAssetsState();
|
|
314
292
|
const assetIds = new Set();
|
|
315
|
-
const accountIds = request.
|
|
293
|
+
const accountIds = request.accountsWithSupportedChains.map((a) => a.account.id);
|
|
316
294
|
const accountFilter = accountIds.length > 0 ? new Set(accountIds) : undefined;
|
|
317
295
|
const chainFilter = request.chainIds.length > 0 ? new Set(request.chainIds) : undefined;
|
|
318
296
|
if (state?.assetsBalance) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PriceDataSource.cjs","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAIA,yDAA2D;AAI3D,0CAA8D;AAC9D,wCAAwC;AAYxC,+EAA+E;AAC/E,YAAY;AACZ,+EAA+E;AAE/E,MAAM,eAAe,GAAG,iBAAiB,CAAC;AAC1C,MAAM,qBAAqB,G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,CAAC;AACH,CAAC","sourcesContent":["import type {\n SupportedCurrency,\n V3SpotPricesResponse,\n} from '@metamask/core-backend';\nimport { ApiPlatformClient } from '@metamask/core-backend';\nimport type { Messenger } from '@metamask/messenger';\n\nimport type { SubscriptionRequest } from './AbstractDataSource';\nimport { projectLogger, createModuleLogger } from '../logger';\nimport { forDataTypes } from '../types';\nimport type {\n Caip19AssetId,\n AssetBalance,\n AccountId,\n ChainId,\n DataRequest,\n DataResponse,\n FungibleAssetPrice,\n Middleware,\n} from '../types';\n\n// ============================================================================\n// CONSTANTS\n// ============================================================================\n\nconst CONTROLLER_NAME = 'PriceDataSource';\nconst DEFAULT_POLL_INTERVAL = 60_000; // 1 minute for price updates\n\nconst log = createModuleLogger(projectLogger, CONTROLLER_NAME);\n\n// ============================================================================\n// MESSENGER TYPES\n// ============================================================================\n\n/**\n * Action to get balance state (used to determine which assets need prices).\n */\ntype GetAssetsBalanceStateAction = {\n type: 'AssetsController:getState';\n handler: () => {\n assetsBalance: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;\n };\n};\n\n/**\n * Action to get the PriceDataSource middleware.\n */\nexport type PriceDataSourceGetAssetsMiddlewareAction = {\n type: `${typeof CONTROLLER_NAME}:getAssetsMiddleware`;\n handler: () => Middleware;\n};\n\n/**\n * Action to fetch prices for assets.\n */\nexport type PriceDataSourceFetchAction = {\n type: `${typeof CONTROLLER_NAME}:fetch`;\n handler: (request: DataRequest) => Promise<DataResponse>;\n};\n\n/**\n * Action to subscribe to price updates.\n */\nexport type PriceDataSourceSubscribeAction = {\n type: `${typeof CONTROLLER_NAME}:subscribe`;\n handler: (request: SubscriptionRequest) => Promise<void>;\n};\n\n/**\n * Action to unsubscribe from price updates.\n */\nexport type PriceDataSourceUnsubscribeAction = {\n type: `${typeof CONTROLLER_NAME}:unsubscribe`;\n handler: (subscriptionId: string) => Promise<void>;\n};\n\n/**\n * All actions exposed by PriceDataSource.\n */\nexport type PriceDataSourceActions =\n | PriceDataSourceGetAssetsMiddlewareAction\n | PriceDataSourceFetchAction\n | PriceDataSourceSubscribeAction\n | PriceDataSourceUnsubscribeAction;\n\n/**\n * Event emitted when prices are updated.\n */\nexport type PriceDataSourceAssetsUpdatedEvent = {\n type: `${typeof CONTROLLER_NAME}:assetsUpdated`;\n payload: [DataResponse, string];\n};\n\n/**\n * All events exposed by PriceDataSource.\n */\nexport type PriceDataSourceEvents = PriceDataSourceAssetsUpdatedEvent;\n\n// Action to report assets updated to AssetsController\ntype AssetsControllerAssetsUpdateAction = {\n type: 'AssetsController:assetsUpdate';\n handler: (response: DataResponse, sourceId: string) => Promise<void>;\n};\n\n/**\n * External actions that PriceDataSource needs to call.\n * Note: Uses ApiPlatformClient directly, so no BackendApiClient actions needed.\n */\nexport type PriceDataSourceAllowedActions =\n | GetAssetsBalanceStateAction\n | AssetsControllerAssetsUpdateAction;\n\nexport type PriceDataSourceMessenger = Messenger<\n typeof CONTROLLER_NAME,\n PriceDataSourceAllowedActions | PriceDataSourceActions,\n PriceDataSourceEvents\n>;\n\n// ============================================================================\n// OPTIONS\n// ============================================================================\n\nexport type PriceDataSourceOptions = {\n messenger: PriceDataSourceMessenger;\n /** ApiPlatformClient for API calls with caching */\n queryApiClient: ApiPlatformClient;\n /** Currency to fetch prices in (default: 'usd') */\n currency?: SupportedCurrency;\n /** Polling interval in ms (default: 60000) */\n pollInterval?: number;\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 */\nconst NON_PRICEABLE_ASSET_PATTERNS = [\n // Tron resource assets (bandwidth, energy, staking states)\n /\\/slip44:\\d+-staked-for-/u,\n /\\/slip44:bandwidth$/u,\n /\\/slip44:energy$/u,\n /\\/slip44:maximum-bandwidth$/u,\n /\\/slip44:maximum-energy$/u,\n];\n\n/**\n * Check if an asset ID represents a priceable asset.\n * Filters out internal resource tracking values that don't have market prices.\n *\n * @param assetId - The CAIP-19 asset ID to check.\n * @returns True if the asset has market price data.\n */\nfunction isPriceableAsset(assetId: Caip19AssetId): boolean {\n return !NON_PRICEABLE_ASSET_PATTERNS.some((pattern) => pattern.test(assetId));\n}\n\n/** Market data item from spot prices response (same as FungibleAssetPrice without lastUpdated) */\ntype SpotPriceMarketData = Omit<FungibleAssetPrice, 'lastUpdated'>;\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 'price' in data &&\n typeof (data as SpotPriceMarketData).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, automatically fetches prices for all assets in assetsBalance state\n * - Publishes price updates via messenger events\n *\n * Usage:\n * ```typescript\n * // Create and initialize (registers messenger actions)\n * const priceDataSource = new PriceDataSource({ messenger });\n *\n * // One-time fetch for specific assets\n * const response = await messenger.call('PriceDataSource:fetch', {\n * customAssets: ['eip155:1/erc20:0x...'],\n * });\n *\n * // Subscribe to price updates (polls all assets in balance state)\n * await messenger.call('PriceDataSource:subscribe', { request, subscriptionId });\n *\n * // Listen for updates\n * messenger.subscribe('PriceDataSource:assetsUpdated', (response) => {\n * // Handle price updates\n * });\n * ```\n */\nexport class PriceDataSource {\n readonly name = CONTROLLER_NAME;\n\n readonly #messenger: PriceDataSourceMessenger;\n\n readonly #currency: SupportedCurrency;\n\n readonly #pollInterval: number;\n\n /** ApiPlatformClient for cached API calls */\n readonly #apiClient: ApiPlatformClient;\n\n /** Active subscriptions by ID */\n readonly #activeSubscriptions: Map<\n string,\n { cleanup: () => void; request: DataRequest }\n > = new Map();\n\n constructor(options: PriceDataSourceOptions) {\n this.#messenger = options.messenger;\n this.#currency = options.currency ?? 'usd';\n this.#pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL;\n this.#apiClient = options.queryApiClient;\n\n this.#registerActionHandlers();\n }\n\n #registerActionHandlers(): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const messenger = this.#messenger as any;\n\n messenger.registerActionHandler(\n 'PriceDataSource:getAssetsMiddleware',\n () => this.assetsMiddleware,\n );\n\n messenger.registerActionHandler(\n 'PriceDataSource:fetch',\n (request: DataRequest) => this.fetch(request),\n );\n\n messenger.registerActionHandler(\n 'PriceDataSource:subscribe',\n (subscriptionRequest: SubscriptionRequest) =>\n this.subscribe(subscriptionRequest),\n );\n\n messenger.registerActionHandler(\n 'PriceDataSource:unsubscribe',\n (subscriptionId: string) => this.unsubscribe(subscriptionId),\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. Extracts the response from context\n * 2. Fetches prices for detected assets (assets without metadata)\n * 3. Enriches the response with fetched prices\n * 4. Calls next() at the end to continue the middleware chain\n *\n * Note: This middleware ONLY fetches prices for detected assets.\n * For fetching prices for all assets, use the subscription mechanism\n * which polls prices for all assets in the balance state.\n *\n * @returns The middleware function for the assets pipeline.\n */\n get assetsMiddleware(): Middleware {\n return forDataTypes(['price'], async (ctx, next) => {\n // Extract response from context\n const { response } = ctx;\n\n // Only fetch prices for detected assets (assets without metadata)\n // The subscription handles fetching prices for all existing assets\n if (!response.detectedAssets) {\n return next(ctx);\n }\n\n const detectedAssetIds = new Set<Caip19AssetId>();\n for (const detectedIds of Object.values(response.detectedAssets)) {\n for (const assetId of detectedIds) {\n detectedAssetIds.add(assetId);\n }\n }\n\n if (detectedAssetIds.size === 0) {\n return next(ctx);\n }\n\n // Filter to only priceable assets\n const priceableAssetIds = [...detectedAssetIds].filter(isPriceableAsset);\n\n if (priceableAssetIds.length === 0) {\n return next(ctx);\n }\n\n try {\n const priceResponse = await this.#fetchSpotPrices(priceableAssetIds);\n\n response.assetsPrice ??= {};\n\n for (const [assetId, marketData] of Object.entries(priceResponse)) {\n if (!isValidMarketData(marketData)) {\n continue;\n }\n\n const caipAssetId = assetId as Caip19AssetId;\n response.assetsPrice[caipAssetId] = {\n ...marketData,\n lastUpdated: Date.now(),\n };\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 // HELPERS\n // ============================================================================\n\n /**\n * Fetch spot prices with caching and deduplication via query service.\n *\n * @param assetIds - Array of CAIP-19 asset IDs\n * @returns Spot prices response\n */\n async #fetchSpotPrices(assetIds: string[]): Promise<V3SpotPricesResponse> {\n return this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: this.#currency,\n includeMarketData: true,\n });\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 const state = this.#messenger.call('AssetsController:getState');\n const assetIds = new Set<Caip19AssetId>();\n\n const accountIds = request.accounts.map((a) => a.id);\n const accountFilter =\n accountIds.length > 0 ? new Set(accountIds) : undefined;\n const chainFilter =\n request.chainIds.length > 0 ? new Set(request.chainIds) : undefined;\n\n if (state?.assetsBalance) {\n for (const [accountId, accountBalances] of Object.entries(\n state.assetsBalance,\n )) {\n // Filter by account if specified\n if (accountFilter && !accountFilter.has(accountId)) {\n continue;\n }\n\n for (const assetId of Object.keys(\n accountBalances as Record<string, unknown>,\n )) {\n // Filter by chain if specified\n if (chainFilter) {\n const chainId = assetId.split('/')[0] as ChainId;\n if (!chainFilter.has(chainId)) {\n continue;\n }\n }\n assetIds.add(assetId as Caip19AssetId);\n }\n }\n }\n\n return [...assetIds];\n } catch (error) {\n log('Failed to get asset IDs from balance state', { error });\n return [];\n }\n }\n\n // ============================================================================\n // FETCH\n // ============================================================================\n\n /**\n * Fetch prices for assets held by the accounts and chains in the request.\n * Gets asset IDs from balance state, filtered by request.accounts and request.chainIds.\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 // Get asset IDs from balance state, filtered by accounts and chains\n const rawAssetIds = this.#getAssetIdsFromBalanceState(request);\n\n // Filter out non-priceable assets (e.g., Tron bandwidth/energy resources)\n const assetIds = rawAssetIds.filter(isPriceableAsset);\n\n if (assetIds.length === 0) {\n return response;\n }\n\n try {\n const priceResponse = await this.#fetchSpotPrices([...assetIds]);\n\n response.assetsPrice = {};\n\n for (const [assetId, marketData] of Object.entries(priceResponse)) {\n // Skip assets with invalid market data (API doesn't have price for this asset)\n if (!isValidMarketData(marketData)) {\n continue;\n }\n\n const caipAssetId = assetId as Caip19AssetId;\n response.assetsPrice[caipAssetId] = {\n ...marketData,\n lastUpdated: Date.now(),\n };\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 - just update the request\n if (isUpdate) {\n const existing = this.#activeSubscriptions.get(subscriptionId);\n if (existing) {\n existing.request = request;\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 // Create poll function - fetches prices for all assets in balance state\n const pollFn = async (): Promise<void> => {\n try {\n const subscription = this.#activeSubscriptions.get(subscriptionId);\n if (!subscription) {\n return;\n }\n\n // Fetch prices for all assets currently in balance state\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 this.#messenger.call(\n 'AssetsController:assetsUpdate',\n fetchResponse,\n CONTROLLER_NAME,\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 });\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 * 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 }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"PriceDataSource.cjs","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAIA,yDAA2D;AAG3D,0CAA8D;AAC9D,wCAAwC;AAWxC,+EAA+E;AAC/E,YAAY;AACZ,+EAA+E;AAE/E,MAAM,eAAe,GAAG,iBAAiB,CAAC;AAC1C,MAAM,qBAAqB,GAAG,KAAM,CAAC,CAAC,6BAA6B;AAEnE,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,eAAe,CAAC,CAAC;AAe/D,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;GAGG;AACH,MAAM,4BAA4B,GAAG;IACnC,2DAA2D;IAC3D,2BAA2B;IAC3B,sBAAsB;IACtB,mBAAmB;IACnB,8BAA8B;IAC9B,2BAA2B;CAC5B,CAAC;AAEF;;;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GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;4BAC9B,SAAS;wBACX,CAAC;oBACH,CAAC;oBACD,QAAQ,CAAC,GAAG,CAAC,OAAwB,CAAC,CAAC;gBACzC,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC;IACvB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,4CAA4C,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC7D,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["import type {\n SupportedCurrency,\n V3SpotPricesResponse,\n} from '@metamask/core-backend';\nimport { ApiPlatformClient } from '@metamask/core-backend';\n\nimport type { SubscriptionRequest } from './AbstractDataSource';\nimport { projectLogger, createModuleLogger } from '../logger';\nimport { forDataTypes } from '../types';\nimport type {\n Caip19AssetId,\n ChainId,\n DataRequest,\n DataResponse,\n FungibleAssetPrice,\n Middleware,\n AssetsControllerStateInternal,\n} from '../types';\n\n// ============================================================================\n// CONSTANTS\n// ============================================================================\n\nconst CONTROLLER_NAME = 'PriceDataSource';\nconst DEFAULT_POLL_INTERVAL = 60_000; // 1 minute for price updates\n\nconst log = createModuleLogger(projectLogger, CONTROLLER_NAME);\n\n// ============================================================================\n// OPTIONS\n// ============================================================================\n\nexport type PriceDataSourceOptions = {\n /** ApiPlatformClient for API calls with caching */\n queryApiClient: ApiPlatformClient;\n /** Currency to fetch prices in (default: 'usd') */\n currency?: SupportedCurrency;\n /** Polling interval in ms (default: 60000) */\n pollInterval?: number;\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 */\nconst NON_PRICEABLE_ASSET_PATTERNS = [\n // Tron resource assets (bandwidth, energy, staking states)\n /\\/slip44:\\d+-staked-for-/u,\n /\\/slip44:bandwidth$/u,\n /\\/slip44:energy$/u,\n /\\/slip44:maximum-bandwidth$/u,\n /\\/slip44:maximum-energy$/u,\n];\n\n/**\n * Check if an asset ID represents a priceable asset.\n * Filters out internal resource tracking values that don't have market prices.\n *\n * @param assetId - The CAIP-19 asset ID to check.\n * @returns True if the asset has market price data.\n */\nfunction isPriceableAsset(assetId: Caip19AssetId): boolean {\n return !NON_PRICEABLE_ASSET_PATTERNS.some((pattern) => pattern.test(assetId));\n}\n\n/** Market data item from spot prices response (same as FungibleAssetPrice without lastUpdated) */\ntype SpotPriceMarketData = Omit<FungibleAssetPrice, 'lastUpdated'>;\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 'price' in data &&\n typeof (data as SpotPriceMarketData).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 getAssetsState from SubscriptionRequest to read assetsBalance and fetch prices\n *\n * Usage: Create with queryApiClient; subscribe() requires getAssetsState in the request for balance-based pricing.\n */\nexport class PriceDataSource {\n readonly name = CONTROLLER_NAME;\n\n readonly #currency: SupportedCurrency;\n\n readonly #pollInterval: number;\n\n /** ApiPlatformClient for cached API calls */\n readonly #apiClient: ApiPlatformClient;\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 getAssetsState?: () => AssetsControllerStateInternal;\n }\n > = new Map();\n\n constructor(options: PriceDataSourceOptions) {\n this.#currency = options.currency ?? 'usd';\n this.#pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL;\n this.#apiClient = options.queryApiClient;\n }\n\n // ============================================================================\n // MIDDLEWARE\n // ============================================================================\n\n /**\n * Get the middleware for enriching responses with price data.\n *\n * This middleware:\n * 1. Extracts the response from context\n * 2. Fetches prices for detected assets (assets without metadata)\n * 3. Enriches the response with fetched prices\n * 4. Calls next() at the end to continue the middleware chain\n *\n * Note: This middleware ONLY fetches prices for detected assets.\n * For fetching prices for all assets, use the subscription mechanism\n * which polls prices for all assets in the balance state.\n *\n * @returns The middleware function for the assets pipeline.\n */\n get assetsMiddleware(): Middleware {\n return forDataTypes(['price'], async (ctx, next) => {\n // Extract response from context\n const { response } = ctx;\n\n // Only fetch prices for detected assets (assets without metadata)\n // The subscription handles fetching prices for all existing assets\n if (!response.detectedAssets) {\n return next(ctx);\n }\n\n const detectedAssetIds = new Set<Caip19AssetId>();\n for (const detectedIds of Object.values(response.detectedAssets)) {\n for (const assetId of detectedIds) {\n detectedAssetIds.add(assetId);\n }\n }\n\n if (detectedAssetIds.size === 0) {\n return next(ctx);\n }\n\n // Filter to only priceable assets\n const priceableAssetIds = [...detectedAssetIds].filter(isPriceableAsset);\n\n if (priceableAssetIds.length === 0) {\n return next(ctx);\n }\n\n try {\n const priceResponse = await this.#fetchSpotPrices(priceableAssetIds);\n\n response.assetsPrice ??= {};\n\n for (const [assetId, marketData] of Object.entries(priceResponse)) {\n if (!isValidMarketData(marketData)) {\n continue;\n }\n\n const caipAssetId = assetId as Caip19AssetId;\n response.assetsPrice[caipAssetId] = {\n ...marketData,\n lastUpdated: Date.now(),\n };\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 // HELPERS\n // ============================================================================\n\n /**\n * Fetch spot prices with caching and deduplication via query service.\n *\n * @param assetIds - Array of CAIP-19 asset IDs\n * @returns Spot prices response\n */\n async #fetchSpotPrices(assetIds: string[]): Promise<V3SpotPricesResponse> {\n return this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: this.#currency,\n includeMarketData: true,\n });\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 * @param getAssetsState - State access; when omitted, returns [].\n * @returns Array of CAIP-19 asset IDs from balance state.\n */\n #getAssetIdsFromBalanceState(\n request: DataRequest,\n getAssetsState?: () => AssetsControllerStateInternal,\n ): Caip19AssetId[] {\n if (!getAssetsState) {\n return [];\n }\n try {\n const state = getAssetsState();\n const assetIds = new Set<Caip19AssetId>();\n\n const accountIds = request.accountsWithSupportedChains.map(\n (a) => a.account.id,\n );\n const accountFilter =\n accountIds.length > 0 ? new Set(accountIds) : undefined;\n const chainFilter =\n request.chainIds.length > 0 ? new Set(request.chainIds) : undefined;\n\n if (state?.assetsBalance) {\n for (const [accountId, accountBalances] of Object.entries(\n state.assetsBalance,\n )) {\n // Filter by account if specified\n if (accountFilter && !accountFilter.has(accountId)) {\n continue;\n }\n\n for (const assetId of Object.keys(\n accountBalances as Record<string, unknown>,\n )) {\n // Filter by chain if specified\n if (chainFilter) {\n const chainId = assetId.split('/')[0] as ChainId;\n if (!chainFilter.has(chainId)) {\n continue;\n }\n }\n assetIds.add(assetId as Caip19AssetId);\n }\n }\n }\n\n return [...assetIds];\n } catch (error) {\n log('Failed to get asset IDs from balance state', { error });\n return [];\n }\n }\n\n // ============================================================================\n // FETCH\n // ============================================================================\n\n /**\n * Fetch prices for assets held by the accounts and chains in the request.\n * When getAssetsState is provided, gets asset IDs from balance state; otherwise returns empty.\n *\n * @param request - The data request specifying accounts and chains.\n * @param getAssetsState - Optional state access (e.g. from SubscriptionRequest).\n * @returns DataResponse containing asset prices.\n */\n async fetch(\n request: DataRequest,\n getAssetsState?: () => AssetsControllerStateInternal,\n ): Promise<DataResponse> {\n const response: DataResponse = {};\n\n // Get asset IDs from balance state when state access is provided\n const rawAssetIds = this.#getAssetIdsFromBalanceState(\n request,\n getAssetsState,\n );\n\n // Filter out non-priceable assets (e.g., Tron bandwidth/energy resources)\n const assetIds = rawAssetIds.filter(isPriceableAsset);\n\n if (assetIds.length === 0) {\n return response;\n }\n\n try {\n const priceResponse = await this.#fetchSpotPrices([...assetIds]);\n\n response.assetsPrice = {};\n\n for (const [assetId, marketData] of Object.entries(priceResponse)) {\n // Skip assets with invalid market data (API doesn't have price for this asset)\n if (!isValidMarketData(marketData)) {\n continue;\n }\n\n const caipAssetId = assetId as Caip19AssetId;\n response.assetsPrice[caipAssetId] = {\n ...marketData,\n lastUpdated: Date.now(),\n };\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 - just update the request\n if (isUpdate) {\n const existing = this.#activeSubscriptions.get(subscriptionId);\n if (existing) {\n existing.request = request;\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 // Create poll function - fetches prices using getAssetsState from subscription\n const pollFn = async (): Promise<void> => {\n try {\n const subscription = this.#activeSubscriptions.get(subscriptionId);\n if (!subscription) {\n return;\n }\n\n // Fetch prices for all assets in balance state (uses subscription's getAssetsState)\n const fetchResponse = await this.fetch(\n subscription.request,\n subscription.getAssetsState,\n );\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(fetchResponse);\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 (getAssetsState from request for balance-based pricing)\n this.#activeSubscriptions.set(subscriptionId, {\n cleanup: () => {\n clearInterval(timer);\n },\n request,\n onAssetsUpdate: subscriptionRequest.onAssetsUpdate,\n getAssetsState: subscriptionRequest.getAssetsState,\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 * 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 }\n}\n"]}
|
|
@@ -1,73 +1,8 @@
|
|
|
1
1
|
import type { SupportedCurrency } from "@metamask/core-backend";
|
|
2
2
|
import { ApiPlatformClient } from "@metamask/core-backend";
|
|
3
|
-
import type { Messenger } from "@metamask/messenger";
|
|
4
3
|
import type { SubscriptionRequest } from "./AbstractDataSource.cjs";
|
|
5
|
-
import type {
|
|
6
|
-
declare const CONTROLLER_NAME = "PriceDataSource";
|
|
7
|
-
/**
|
|
8
|
-
* Action to get balance state (used to determine which assets need prices).
|
|
9
|
-
*/
|
|
10
|
-
type GetAssetsBalanceStateAction = {
|
|
11
|
-
type: 'AssetsController:getState';
|
|
12
|
-
handler: () => {
|
|
13
|
-
assetsBalance: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;
|
|
14
|
-
};
|
|
15
|
-
};
|
|
16
|
-
/**
|
|
17
|
-
* Action to get the PriceDataSource middleware.
|
|
18
|
-
*/
|
|
19
|
-
export type PriceDataSourceGetAssetsMiddlewareAction = {
|
|
20
|
-
type: `${typeof CONTROLLER_NAME}:getAssetsMiddleware`;
|
|
21
|
-
handler: () => Middleware;
|
|
22
|
-
};
|
|
23
|
-
/**
|
|
24
|
-
* Action to fetch prices for assets.
|
|
25
|
-
*/
|
|
26
|
-
export type PriceDataSourceFetchAction = {
|
|
27
|
-
type: `${typeof CONTROLLER_NAME}:fetch`;
|
|
28
|
-
handler: (request: DataRequest) => Promise<DataResponse>;
|
|
29
|
-
};
|
|
30
|
-
/**
|
|
31
|
-
* Action to subscribe to price updates.
|
|
32
|
-
*/
|
|
33
|
-
export type PriceDataSourceSubscribeAction = {
|
|
34
|
-
type: `${typeof CONTROLLER_NAME}:subscribe`;
|
|
35
|
-
handler: (request: SubscriptionRequest) => Promise<void>;
|
|
36
|
-
};
|
|
37
|
-
/**
|
|
38
|
-
* Action to unsubscribe from price updates.
|
|
39
|
-
*/
|
|
40
|
-
export type PriceDataSourceUnsubscribeAction = {
|
|
41
|
-
type: `${typeof CONTROLLER_NAME}:unsubscribe`;
|
|
42
|
-
handler: (subscriptionId: string) => Promise<void>;
|
|
43
|
-
};
|
|
44
|
-
/**
|
|
45
|
-
* All actions exposed by PriceDataSource.
|
|
46
|
-
*/
|
|
47
|
-
export type PriceDataSourceActions = PriceDataSourceGetAssetsMiddlewareAction | PriceDataSourceFetchAction | PriceDataSourceSubscribeAction | PriceDataSourceUnsubscribeAction;
|
|
48
|
-
/**
|
|
49
|
-
* Event emitted when prices are updated.
|
|
50
|
-
*/
|
|
51
|
-
export type PriceDataSourceAssetsUpdatedEvent = {
|
|
52
|
-
type: `${typeof CONTROLLER_NAME}:assetsUpdated`;
|
|
53
|
-
payload: [DataResponse, string];
|
|
54
|
-
};
|
|
55
|
-
/**
|
|
56
|
-
* All events exposed by PriceDataSource.
|
|
57
|
-
*/
|
|
58
|
-
export type PriceDataSourceEvents = PriceDataSourceAssetsUpdatedEvent;
|
|
59
|
-
type AssetsControllerAssetsUpdateAction = {
|
|
60
|
-
type: 'AssetsController:assetsUpdate';
|
|
61
|
-
handler: (response: DataResponse, sourceId: string) => Promise<void>;
|
|
62
|
-
};
|
|
63
|
-
/**
|
|
64
|
-
* External actions that PriceDataSource needs to call.
|
|
65
|
-
* Note: Uses ApiPlatformClient directly, so no BackendApiClient actions needed.
|
|
66
|
-
*/
|
|
67
|
-
export type PriceDataSourceAllowedActions = GetAssetsBalanceStateAction | AssetsControllerAssetsUpdateAction;
|
|
68
|
-
export type PriceDataSourceMessenger = Messenger<typeof CONTROLLER_NAME, PriceDataSourceAllowedActions | PriceDataSourceActions, PriceDataSourceEvents>;
|
|
4
|
+
import type { DataRequest, DataResponse, Middleware, AssetsControllerStateInternal } from "../types.cjs";
|
|
69
5
|
export type PriceDataSourceOptions = {
|
|
70
|
-
messenger: PriceDataSourceMessenger;
|
|
71
6
|
/** ApiPlatformClient for API calls with caching */
|
|
72
7
|
queryApiClient: ApiPlatformClient;
|
|
73
8
|
/** Currency to fetch prices in (default: 'usd') */
|
|
@@ -81,27 +16,9 @@ export type PriceDataSourceOptions = {
|
|
|
81
16
|
* This data source:
|
|
82
17
|
* - Fetches prices from Price API v3 spot-prices endpoint
|
|
83
18
|
* - Supports one-time fetch and subscription-based polling
|
|
84
|
-
* - In subscribe mode,
|
|
85
|
-
* - Publishes price updates via messenger events
|
|
86
|
-
*
|
|
87
|
-
* Usage:
|
|
88
|
-
* ```typescript
|
|
89
|
-
* // Create and initialize (registers messenger actions)
|
|
90
|
-
* const priceDataSource = new PriceDataSource({ messenger });
|
|
91
|
-
*
|
|
92
|
-
* // One-time fetch for specific assets
|
|
93
|
-
* const response = await messenger.call('PriceDataSource:fetch', {
|
|
94
|
-
* customAssets: ['eip155:1/erc20:0x...'],
|
|
95
|
-
* });
|
|
96
|
-
*
|
|
97
|
-
* // Subscribe to price updates (polls all assets in balance state)
|
|
98
|
-
* await messenger.call('PriceDataSource:subscribe', { request, subscriptionId });
|
|
19
|
+
* - In subscribe mode, uses getAssetsState from SubscriptionRequest to read assetsBalance and fetch prices
|
|
99
20
|
*
|
|
100
|
-
*
|
|
101
|
-
* messenger.subscribe('PriceDataSource:assetsUpdated', (response) => {
|
|
102
|
-
* // Handle price updates
|
|
103
|
-
* });
|
|
104
|
-
* ```
|
|
21
|
+
* Usage: Create with queryApiClient; subscribe() requires getAssetsState in the request for balance-based pricing.
|
|
105
22
|
*/
|
|
106
23
|
export declare class PriceDataSource {
|
|
107
24
|
#private;
|
|
@@ -125,12 +42,13 @@ export declare class PriceDataSource {
|
|
|
125
42
|
get assetsMiddleware(): Middleware;
|
|
126
43
|
/**
|
|
127
44
|
* Fetch prices for assets held by the accounts and chains in the request.
|
|
128
|
-
*
|
|
45
|
+
* When getAssetsState is provided, gets asset IDs from balance state; otherwise returns empty.
|
|
129
46
|
*
|
|
130
47
|
* @param request - The data request specifying accounts and chains.
|
|
48
|
+
* @param getAssetsState - Optional state access (e.g. from SubscriptionRequest).
|
|
131
49
|
* @returns DataResponse containing asset prices.
|
|
132
50
|
*/
|
|
133
|
-
fetch(request: DataRequest): Promise<DataResponse>;
|
|
51
|
+
fetch(request: DataRequest, getAssetsState?: () => AssetsControllerStateInternal): Promise<DataResponse>;
|
|
134
52
|
/**
|
|
135
53
|
* Subscribe to price updates.
|
|
136
54
|
* Sets up polling that fetches prices for all assets in assetsBalance state.
|
|
@@ -149,5 +67,4 @@ export declare class PriceDataSource {
|
|
|
149
67
|
*/
|
|
150
68
|
destroy(): void;
|
|
151
69
|
}
|
|
152
|
-
export {};
|
|
153
70
|
//# sourceMappingURL=PriceDataSource.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PriceDataSource.d.cts","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EAElB,+BAA+B;AAChC,OAAO,EAAE,iBAAiB,EAAE,+BAA+B;
|
|
1
|
+
{"version":3,"file":"PriceDataSource.d.cts","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EAElB,+BAA+B;AAChC,OAAO,EAAE,iBAAiB,EAAE,+BAA+B;AAE3D,OAAO,KAAK,EAAE,mBAAmB,EAAE,iCAA6B;AAGhE,OAAO,KAAK,EAGV,WAAW,EACX,YAAY,EAEZ,UAAU,EACV,6BAA6B,EAC9B,qBAAiB;AAelB,MAAM,MAAM,sBAAsB,GAAG;IACnC,mDAAmD;IACnD,cAAc,EAAE,iBAAiB,CAAC;IAClC,mDAAmD;IACnD,QAAQ,CAAC,EAAE,iBAAiB,CAAC;IAC7B,8CAA8C;IAC9C,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC;AAoDF;;;;;;;;;GASG;AACH,qBAAa,eAAe;;IAC1B,QAAQ,CAAC,IAAI,qBAAmB;gBAoBpB,OAAO,EAAE,sBAAsB;IAU3C;;;;;;;;;;;;;;OAcG;IACH,IAAI,gBAAgB,IAAI,UAAU,CAoDjC;IAiFD;;;;;;;OAOG;IACG,KAAK,CACT,OAAO,EAAE,WAAW,EACpB,cAAc,CAAC,EAAE,MAAM,6BAA6B,GACnD,OAAO,CAAC,YAAY,CAAC;IA4CxB;;;;;OAKG;IACG,SAAS,CAAC,mBAAmB,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IA8DxE;;;;OAIG;IACG,WAAW,CAAC,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQxD;;OAEG;IACH,OAAO,IAAI,IAAI;CAMhB"}
|
|
@@ -1,73 +1,8 @@
|
|
|
1
1
|
import type { SupportedCurrency } from "@metamask/core-backend";
|
|
2
2
|
import { ApiPlatformClient } from "@metamask/core-backend";
|
|
3
|
-
import type { Messenger } from "@metamask/messenger";
|
|
4
3
|
import type { SubscriptionRequest } from "./AbstractDataSource.mjs";
|
|
5
|
-
import type {
|
|
6
|
-
declare const CONTROLLER_NAME = "PriceDataSource";
|
|
7
|
-
/**
|
|
8
|
-
* Action to get balance state (used to determine which assets need prices).
|
|
9
|
-
*/
|
|
10
|
-
type GetAssetsBalanceStateAction = {
|
|
11
|
-
type: 'AssetsController:getState';
|
|
12
|
-
handler: () => {
|
|
13
|
-
assetsBalance: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;
|
|
14
|
-
};
|
|
15
|
-
};
|
|
16
|
-
/**
|
|
17
|
-
* Action to get the PriceDataSource middleware.
|
|
18
|
-
*/
|
|
19
|
-
export type PriceDataSourceGetAssetsMiddlewareAction = {
|
|
20
|
-
type: `${typeof CONTROLLER_NAME}:getAssetsMiddleware`;
|
|
21
|
-
handler: () => Middleware;
|
|
22
|
-
};
|
|
23
|
-
/**
|
|
24
|
-
* Action to fetch prices for assets.
|
|
25
|
-
*/
|
|
26
|
-
export type PriceDataSourceFetchAction = {
|
|
27
|
-
type: `${typeof CONTROLLER_NAME}:fetch`;
|
|
28
|
-
handler: (request: DataRequest) => Promise<DataResponse>;
|
|
29
|
-
};
|
|
30
|
-
/**
|
|
31
|
-
* Action to subscribe to price updates.
|
|
32
|
-
*/
|
|
33
|
-
export type PriceDataSourceSubscribeAction = {
|
|
34
|
-
type: `${typeof CONTROLLER_NAME}:subscribe`;
|
|
35
|
-
handler: (request: SubscriptionRequest) => Promise<void>;
|
|
36
|
-
};
|
|
37
|
-
/**
|
|
38
|
-
* Action to unsubscribe from price updates.
|
|
39
|
-
*/
|
|
40
|
-
export type PriceDataSourceUnsubscribeAction = {
|
|
41
|
-
type: `${typeof CONTROLLER_NAME}:unsubscribe`;
|
|
42
|
-
handler: (subscriptionId: string) => Promise<void>;
|
|
43
|
-
};
|
|
44
|
-
/**
|
|
45
|
-
* All actions exposed by PriceDataSource.
|
|
46
|
-
*/
|
|
47
|
-
export type PriceDataSourceActions = PriceDataSourceGetAssetsMiddlewareAction | PriceDataSourceFetchAction | PriceDataSourceSubscribeAction | PriceDataSourceUnsubscribeAction;
|
|
48
|
-
/**
|
|
49
|
-
* Event emitted when prices are updated.
|
|
50
|
-
*/
|
|
51
|
-
export type PriceDataSourceAssetsUpdatedEvent = {
|
|
52
|
-
type: `${typeof CONTROLLER_NAME}:assetsUpdated`;
|
|
53
|
-
payload: [DataResponse, string];
|
|
54
|
-
};
|
|
55
|
-
/**
|
|
56
|
-
* All events exposed by PriceDataSource.
|
|
57
|
-
*/
|
|
58
|
-
export type PriceDataSourceEvents = PriceDataSourceAssetsUpdatedEvent;
|
|
59
|
-
type AssetsControllerAssetsUpdateAction = {
|
|
60
|
-
type: 'AssetsController:assetsUpdate';
|
|
61
|
-
handler: (response: DataResponse, sourceId: string) => Promise<void>;
|
|
62
|
-
};
|
|
63
|
-
/**
|
|
64
|
-
* External actions that PriceDataSource needs to call.
|
|
65
|
-
* Note: Uses ApiPlatformClient directly, so no BackendApiClient actions needed.
|
|
66
|
-
*/
|
|
67
|
-
export type PriceDataSourceAllowedActions = GetAssetsBalanceStateAction | AssetsControllerAssetsUpdateAction;
|
|
68
|
-
export type PriceDataSourceMessenger = Messenger<typeof CONTROLLER_NAME, PriceDataSourceAllowedActions | PriceDataSourceActions, PriceDataSourceEvents>;
|
|
4
|
+
import type { DataRequest, DataResponse, Middleware, AssetsControllerStateInternal } from "../types.mjs";
|
|
69
5
|
export type PriceDataSourceOptions = {
|
|
70
|
-
messenger: PriceDataSourceMessenger;
|
|
71
6
|
/** ApiPlatformClient for API calls with caching */
|
|
72
7
|
queryApiClient: ApiPlatformClient;
|
|
73
8
|
/** Currency to fetch prices in (default: 'usd') */
|
|
@@ -81,27 +16,9 @@ export type PriceDataSourceOptions = {
|
|
|
81
16
|
* This data source:
|
|
82
17
|
* - Fetches prices from Price API v3 spot-prices endpoint
|
|
83
18
|
* - Supports one-time fetch and subscription-based polling
|
|
84
|
-
* - In subscribe mode,
|
|
85
|
-
* - Publishes price updates via messenger events
|
|
86
|
-
*
|
|
87
|
-
* Usage:
|
|
88
|
-
* ```typescript
|
|
89
|
-
* // Create and initialize (registers messenger actions)
|
|
90
|
-
* const priceDataSource = new PriceDataSource({ messenger });
|
|
91
|
-
*
|
|
92
|
-
* // One-time fetch for specific assets
|
|
93
|
-
* const response = await messenger.call('PriceDataSource:fetch', {
|
|
94
|
-
* customAssets: ['eip155:1/erc20:0x...'],
|
|
95
|
-
* });
|
|
96
|
-
*
|
|
97
|
-
* // Subscribe to price updates (polls all assets in balance state)
|
|
98
|
-
* await messenger.call('PriceDataSource:subscribe', { request, subscriptionId });
|
|
19
|
+
* - In subscribe mode, uses getAssetsState from SubscriptionRequest to read assetsBalance and fetch prices
|
|
99
20
|
*
|
|
100
|
-
*
|
|
101
|
-
* messenger.subscribe('PriceDataSource:assetsUpdated', (response) => {
|
|
102
|
-
* // Handle price updates
|
|
103
|
-
* });
|
|
104
|
-
* ```
|
|
21
|
+
* Usage: Create with queryApiClient; subscribe() requires getAssetsState in the request for balance-based pricing.
|
|
105
22
|
*/
|
|
106
23
|
export declare class PriceDataSource {
|
|
107
24
|
#private;
|
|
@@ -125,12 +42,13 @@ export declare class PriceDataSource {
|
|
|
125
42
|
get assetsMiddleware(): Middleware;
|
|
126
43
|
/**
|
|
127
44
|
* Fetch prices for assets held by the accounts and chains in the request.
|
|
128
|
-
*
|
|
45
|
+
* When getAssetsState is provided, gets asset IDs from balance state; otherwise returns empty.
|
|
129
46
|
*
|
|
130
47
|
* @param request - The data request specifying accounts and chains.
|
|
48
|
+
* @param getAssetsState - Optional state access (e.g. from SubscriptionRequest).
|
|
131
49
|
* @returns DataResponse containing asset prices.
|
|
132
50
|
*/
|
|
133
|
-
fetch(request: DataRequest): Promise<DataResponse>;
|
|
51
|
+
fetch(request: DataRequest, getAssetsState?: () => AssetsControllerStateInternal): Promise<DataResponse>;
|
|
134
52
|
/**
|
|
135
53
|
* Subscribe to price updates.
|
|
136
54
|
* Sets up polling that fetches prices for all assets in assetsBalance state.
|
|
@@ -149,5 +67,4 @@ export declare class PriceDataSource {
|
|
|
149
67
|
*/
|
|
150
68
|
destroy(): void;
|
|
151
69
|
}
|
|
152
|
-
export {};
|
|
153
70
|
//# sourceMappingURL=PriceDataSource.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PriceDataSource.d.mts","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EAElB,+BAA+B;AAChC,OAAO,EAAE,iBAAiB,EAAE,+BAA+B;
|
|
1
|
+
{"version":3,"file":"PriceDataSource.d.mts","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EAElB,+BAA+B;AAChC,OAAO,EAAE,iBAAiB,EAAE,+BAA+B;AAE3D,OAAO,KAAK,EAAE,mBAAmB,EAAE,iCAA6B;AAGhE,OAAO,KAAK,EAGV,WAAW,EACX,YAAY,EAEZ,UAAU,EACV,6BAA6B,EAC9B,qBAAiB;AAelB,MAAM,MAAM,sBAAsB,GAAG;IACnC,mDAAmD;IACnD,cAAc,EAAE,iBAAiB,CAAC;IAClC,mDAAmD;IACnD,QAAQ,CAAC,EAAE,iBAAiB,CAAC;IAC7B,8CAA8C;IAC9C,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC;AAoDF;;;;;;;;;GASG;AACH,qBAAa,eAAe;;IAC1B,QAAQ,CAAC,IAAI,qBAAmB;gBAoBpB,OAAO,EAAE,sBAAsB;IAU3C;;;;;;;;;;;;;;OAcG;IACH,IAAI,gBAAgB,IAAI,UAAU,CAoDjC;IAiFD;;;;;;;OAOG;IACG,KAAK,CACT,OAAO,EAAE,WAAW,EACpB,cAAc,CAAC,EAAE,MAAM,6BAA6B,GACnD,OAAO,CAAC,YAAY,CAAC;IA4CxB;;;;;OAKG;IACG,SAAS,CAAC,mBAAmB,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IA8DxE;;;;OAIG;IACG,WAAW,CAAC,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQxD;;OAEG;IACH,OAAO,IAAI,IAAI;CAMhB"}
|