@metamask-previews/assets-controller 11.2.1-preview-6cd1bb2f5 → 11.3.0-preview-2296abeaf
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 +28 -1
- package/dist/AssetsController.cjs +238 -133
- package/dist/AssetsController.cjs.map +1 -1
- package/dist/AssetsController.d.cts.map +1 -1
- package/dist/AssetsController.d.mts.map +1 -1
- package/dist/AssetsController.mjs +238 -133
- package/dist/AssetsController.mjs.map +1 -1
- package/dist/data-sources/SnapDataSource.cjs +10 -49
- package/dist/data-sources/SnapDataSource.cjs.map +1 -1
- package/dist/data-sources/SnapDataSource.d.cts +8 -0
- package/dist/data-sources/SnapDataSource.d.cts.map +1 -1
- package/dist/data-sources/SnapDataSource.d.mts +8 -0
- package/dist/data-sources/SnapDataSource.d.mts.map +1 -1
- package/dist/data-sources/SnapDataSource.mjs +10 -49
- package/dist/data-sources/SnapDataSource.mjs.map +1 -1
- package/dist/selectors/balance.cjs +53 -35
- package/dist/selectors/balance.cjs.map +1 -1
- package/dist/selectors/balance.d.cts.map +1 -1
- package/dist/selectors/balance.d.mts.map +1 -1
- package/dist/selectors/balance.mjs +53 -35
- package/dist/selectors/balance.mjs.map +1 -1
- package/dist/utils/trace.cjs +120 -0
- package/dist/utils/trace.cjs.map +1 -0
- package/dist/utils/trace.d.cts +52 -0
- package/dist/utils/trace.d.cts.map +1 -0
- package/dist/utils/trace.d.mts +52 -0
- package/dist/utils/trace.d.mts.map +1 -0
- package/dist/utils/trace.mjs +115 -0
- package/dist/utils/trace.mjs.map +1 -0
- package/package.json +7 -7
|
@@ -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 _SnapDataSource_instances, _SnapDataSource_messenger, _SnapDataSource_onActiveChainsUpdated, _SnapDataSource_handleSnapBalancesUpdatedBound, _SnapDataSource_handlePermissionStateChangeBound, _SnapDataSource_keyringClientCache, _SnapDataSource_subscribeToEvents, _SnapDataSource_handleSnapBalancesUpdated, _SnapDataSource_isChainSupportedBySnap, _SnapDataSource_getRunnableSnaps, _SnapDataSource_getSnapPermissions, _SnapDataSource_discoverKeyringSnaps, _SnapDataSource_getKeyringClient;
|
|
13
|
+
var _SnapDataSource_instances, _SnapDataSource_messenger, _SnapDataSource_onActiveChainsUpdated, _SnapDataSource_onAssetsUpdate, _SnapDataSource_handleSnapBalancesUpdatedBound, _SnapDataSource_handlePermissionStateChangeBound, _SnapDataSource_keyringClientCache, _SnapDataSource_subscribeToEvents, _SnapDataSource_handleSnapBalancesUpdated, _SnapDataSource_isChainSupportedBySnap, _SnapDataSource_getRunnableSnaps, _SnapDataSource_getSnapPermissions, _SnapDataSource_discoverKeyringSnaps, _SnapDataSource_getKeyringClient;
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
exports.createSnapDataSource = exports.SnapDataSource = exports.extractChainFromAssetId = exports.getChainIdsCaveat = exports.ASSETS_PERMISSION = exports.KEYRING_PERMISSION = exports.SNAP_DATA_SOURCE_NAME = void 0;
|
|
16
16
|
const keyring_snap_client_1 = require("@metamask/keyring-snap-client");
|
|
@@ -95,6 +95,7 @@ class SnapDataSource extends AbstractDataSource_js_1.AbstractDataSource {
|
|
|
95
95
|
_SnapDataSource_instances.add(this);
|
|
96
96
|
_SnapDataSource_messenger.set(this, void 0);
|
|
97
97
|
_SnapDataSource_onActiveChainsUpdated.set(this, void 0);
|
|
98
|
+
_SnapDataSource_onAssetsUpdate.set(this, void 0);
|
|
98
99
|
/** Bound handler for snap keyring balance updates, stored for cleanup */
|
|
99
100
|
_SnapDataSource_handleSnapBalancesUpdatedBound.set(this, void 0);
|
|
100
101
|
_SnapDataSource_handlePermissionStateChangeBound.set(this, void 0);
|
|
@@ -102,6 +103,7 @@ class SnapDataSource extends AbstractDataSource_js_1.AbstractDataSource {
|
|
|
102
103
|
_SnapDataSource_keyringClientCache.set(this, new Map());
|
|
103
104
|
__classPrivateFieldSet(this, _SnapDataSource_messenger, options.messenger, "f");
|
|
104
105
|
__classPrivateFieldSet(this, _SnapDataSource_onActiveChainsUpdated, options.onActiveChainsUpdated, "f");
|
|
106
|
+
__classPrivateFieldSet(this, _SnapDataSource_onAssetsUpdate, options.onAssetsUpdate, "f");
|
|
105
107
|
// Bind handlers for cleanup in destroy()
|
|
106
108
|
__classPrivateFieldSet(this, _SnapDataSource_handleSnapBalancesUpdatedBound, __classPrivateFieldGet(this, _SnapDataSource_instances, "m", _SnapDataSource_handleSnapBalancesUpdated).bind(this), "f");
|
|
107
109
|
__classPrivateFieldSet(this, _SnapDataSource_handlePermissionStateChangeBound, __classPrivateFieldGet(this, _SnapDataSource_instances, "m", _SnapDataSource_discoverKeyringSnaps).bind(this), "f");
|
|
@@ -158,6 +160,7 @@ class SnapDataSource extends AbstractDataSource_js_1.AbstractDataSource {
|
|
|
158
160
|
if (accountBalances) {
|
|
159
161
|
accountBalances[assetId] = {
|
|
160
162
|
amount: balance.amount,
|
|
163
|
+
...(balance.metadata ? { metadata: balance.metadata } : {}),
|
|
161
164
|
};
|
|
162
165
|
}
|
|
163
166
|
}
|
|
@@ -250,7 +253,7 @@ class SnapDataSource extends AbstractDataSource_js_1.AbstractDataSource {
|
|
|
250
253
|
// SUBSCRIBE - Routes to appropriate snap(s)
|
|
251
254
|
// ============================================================================
|
|
252
255
|
async subscribe(subscriptionRequest) {
|
|
253
|
-
const { request, subscriptionId
|
|
256
|
+
const { request, subscriptionId } = subscriptionRequest;
|
|
254
257
|
// Guard against undefined request or chainIds
|
|
255
258
|
if (!request?.chainIds) {
|
|
256
259
|
return;
|
|
@@ -260,48 +263,13 @@ class SnapDataSource extends AbstractDataSource_js_1.AbstractDataSource {
|
|
|
260
263
|
if (supportedChains.length === 0) {
|
|
261
264
|
return;
|
|
262
265
|
}
|
|
263
|
-
if (isUpdate) {
|
|
264
|
-
const existing = this.activeSubscriptions.get(subscriptionId);
|
|
265
|
-
if (existing) {
|
|
266
|
-
existing.chains = supportedChains;
|
|
267
|
-
// Do a fetch to get latest data on subscription update
|
|
268
|
-
this.fetch({
|
|
269
|
-
...request,
|
|
270
|
-
chainIds: supportedChains,
|
|
271
|
-
})
|
|
272
|
-
.then(async (fetchResponse) => {
|
|
273
|
-
if (Object.keys(fetchResponse.assetsBalance ?? {}).length > 0) {
|
|
274
|
-
await existing.onAssetsUpdate(fetchResponse);
|
|
275
|
-
}
|
|
276
|
-
return fetchResponse;
|
|
277
|
-
})
|
|
278
|
-
.catch((error) => {
|
|
279
|
-
log('Subscription update fetch failed', { subscriptionId, error });
|
|
280
|
-
});
|
|
281
|
-
return;
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
await this.unsubscribe(subscriptionId);
|
|
285
|
-
// Snaps provide real-time updates via AccountsController:accountBalancesUpdated
|
|
286
|
-
// We only need to track the subscription and do an initial fetch
|
|
287
|
-
// No polling needed - updates come through #handleSnapBalancesUpdated
|
|
288
|
-
this.activeSubscriptions.set(subscriptionId, {
|
|
289
|
-
cleanup: () => {
|
|
290
|
-
// No timer to clear - we use event-based updates
|
|
291
|
-
},
|
|
292
|
-
chains: supportedChains,
|
|
293
|
-
onAssetsUpdate: subscriptionRequest.onAssetsUpdate,
|
|
294
|
-
});
|
|
295
|
-
// Initial fetch to get current balances
|
|
296
266
|
try {
|
|
297
267
|
const fetchResponse = await this.fetch({
|
|
298
268
|
...request,
|
|
299
269
|
chainIds: supportedChains,
|
|
300
270
|
});
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
subscription) {
|
|
304
|
-
await subscription.onAssetsUpdate(fetchResponse);
|
|
271
|
+
if (Object.keys(fetchResponse.assetsBalance ?? {}).length > 0) {
|
|
272
|
+
await __classPrivateFieldGet(this, _SnapDataSource_onAssetsUpdate, "f").call(this, fetchResponse);
|
|
305
273
|
}
|
|
306
274
|
}
|
|
307
275
|
catch (error) {
|
|
@@ -328,18 +296,12 @@ class SnapDataSource extends AbstractDataSource_js_1.AbstractDataSource {
|
|
|
328
296
|
catch (error) {
|
|
329
297
|
log('Failed to unsubscribe from permission changes', { error });
|
|
330
298
|
}
|
|
331
|
-
// Clean up active subscriptions
|
|
332
|
-
for (const [subscriptionId] of this.activeSubscriptions) {
|
|
333
|
-
this.unsubscribe(subscriptionId).catch(() => {
|
|
334
|
-
// Ignore cleanup errors
|
|
335
|
-
});
|
|
336
|
-
}
|
|
337
299
|
// Clear keyring client cache
|
|
338
300
|
__classPrivateFieldGet(this, _SnapDataSource_keyringClientCache, "f").clear();
|
|
339
301
|
}
|
|
340
302
|
}
|
|
341
303
|
exports.SnapDataSource = SnapDataSource;
|
|
342
|
-
_SnapDataSource_messenger = new WeakMap(), _SnapDataSource_onActiveChainsUpdated = new WeakMap(), _SnapDataSource_handleSnapBalancesUpdatedBound = new WeakMap(), _SnapDataSource_handlePermissionStateChangeBound = new WeakMap(), _SnapDataSource_keyringClientCache = new WeakMap(), _SnapDataSource_instances = new WeakSet(), _SnapDataSource_subscribeToEvents = function _SnapDataSource_subscribeToEvents() {
|
|
304
|
+
_SnapDataSource_messenger = new WeakMap(), _SnapDataSource_onActiveChainsUpdated = new WeakMap(), _SnapDataSource_onAssetsUpdate = new WeakMap(), _SnapDataSource_handleSnapBalancesUpdatedBound = new WeakMap(), _SnapDataSource_handlePermissionStateChangeBound = new WeakMap(), _SnapDataSource_keyringClientCache = new WeakMap(), _SnapDataSource_instances = new WeakSet(), _SnapDataSource_subscribeToEvents = function _SnapDataSource_subscribeToEvents() {
|
|
343
305
|
// Subscribe to snap keyring events and permission changes (not in AssetsControllerEvents).
|
|
344
306
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
345
307
|
const messenger = __classPrivateFieldGet(this, _SnapDataSource_messenger, "f");
|
|
@@ -370,6 +332,7 @@ _SnapDataSource_messenger = new WeakMap(), _SnapDataSource_onActiveChainsUpdated
|
|
|
370
332
|
accountAssets ?? (accountAssets = {});
|
|
371
333
|
accountAssets[assetId] = {
|
|
372
334
|
amount: balance.amount,
|
|
335
|
+
...(balance.metadata ? { metadata: balance.metadata } : {}),
|
|
373
336
|
};
|
|
374
337
|
}
|
|
375
338
|
}
|
|
@@ -381,9 +344,7 @@ _SnapDataSource_messenger = new WeakMap(), _SnapDataSource_onActiveChainsUpdated
|
|
|
381
344
|
// Only report if we have snap-related updates
|
|
382
345
|
if (assetsBalance) {
|
|
383
346
|
const response = { assetsBalance, updateMode: 'merge' };
|
|
384
|
-
|
|
385
|
-
subscription.onAssetsUpdate(response)?.catch(console.error);
|
|
386
|
-
}
|
|
347
|
+
Promise.resolve(__classPrivateFieldGet(this, _SnapDataSource_onAssetsUpdate, "f").call(this, response)).catch(console.error);
|
|
387
348
|
}
|
|
388
349
|
}, _SnapDataSource_isChainSupportedBySnap = function _SnapDataSource_isChainSupportedBySnap(chainId) {
|
|
389
350
|
return this.state.activeChains.includes(chainId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SnapDataSource.cjs","sourceRoot":"","sources":["../../src/data-sources/SnapDataSource.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,uEAA8D;AAc9D,uDAAoE;AACpE,2CAAqD;AAIrD,6CAAiE;AASjE,oEAA6D;AAiC7D,MAAM,GAAG,GAAG,IAAA,8BAAkB,EAAC,yBAAa,EAAE,gBAAgB,CAAC,CAAC;AAEhE,+EAA+E;AAC/E,YAAY;AACZ,+EAA+E;AAElE,QAAA,qBAAqB,GAAG,gBAAgB,CAAC;AAEtD,qDAAqD;AACxC,QAAA,kBAAkB,GAAG,mBAAmB,CAAC;AAEtD,wEAAwE;AAC3D,QAAA,iBAAiB,GAAG,kBAAkB,CAAC;AAEpD,+EAA+E;AAC/E,uBAAuB;AACvB,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AM,EAAE,MAAM,CAAC,CAAC;IAC7C,OAAO,MAAM,CAAC;AAChB,CAAC;AA0CH,+EAA+E;AAC/E,UAAU;AACV,+EAA+E;AAE/E,SAAgB,oBAAoB,CAClC,OAA8B;IAE9B,OAAO,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC;AACrC,CAAC;AAJD,oDAIC","sourcesContent":["import type { Balance, CaipAssetType } from '@metamask/keyring-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type {\n Caveat,\n GetPermissions,\n PermissionConstraint,\n PermissionControllerStateChange,\n SubjectPermissions,\n} from '@metamask/permission-controller';\nimport type {\n SnapControllerGetRunnableSnapsAction,\n SnapControllerHandleRequestAction,\n SnapControllerSnapInstalledEvent,\n} from '@metamask/snaps-controllers';\nimport type { Snap, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType, SnapCaveatType } from '@metamask/snaps-utils';\nimport { parseCaipAssetType } from '@metamask/utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\n\nimport type { AssetsControllerMessenger } from '../AssetsController.js';\nimport { projectLogger, createModuleLogger } from '../logger.js';\nimport type {\n AssetBalance,\n ChainId,\n Caip19AssetId,\n DataRequest,\n DataResponse,\n Middleware,\n} from '../types.js';\nimport { AbstractDataSource } from './AbstractDataSource.js';\nimport type {\n DataSourceState,\n SubscriptionRequest,\n} from './AbstractDataSource.js';\n\n// ============================================================================\n// SNAP KEYRING EVENT TYPES\n// ============================================================================\n\n/**\n * Payload for AccountsController:accountBalancesUpdated event.\n * Re-published from SnapKeyring:accountBalancesUpdated.\n */\nexport type AccountBalancesUpdatedEventPayload = {\n balances: {\n [accountId: string]: {\n [assetId: string]: {\n amount: string;\n unit: string;\n };\n };\n };\n};\n\n/**\n * Event from AccountsController when snap balances are updated.\n */\nexport type AccountsControllerAccountBalancesUpdatedEvent = {\n type: 'AccountsController:accountBalancesUpdated';\n payload: [AccountBalancesUpdatedEventPayload];\n};\n\nconst log = createModuleLogger(projectLogger, 'SnapDataSource');\n\n// ============================================================================\n// CONSTANTS\n// ============================================================================\n\nexport const SNAP_DATA_SOURCE_NAME = 'SnapDataSource';\n\n/** The permission name for snap keyring endowment */\nexport const KEYRING_PERMISSION = 'endowment:keyring';\n\n/** The permission name for snap assets endowment (contains chainIds) */\nexport const ASSETS_PERMISSION = 'endowment:assets';\n\n// ============================================================================\n// PERMISSION UTILITIES\n// ============================================================================\n\n/**\n * Getter function to get the chainIds caveat from a permission.\n *\n * This does basic validation of the caveat, but does not validate the type or\n * value of the namespaces object itself, as this is handled by the\n * `PermissionsController` when the permission is requested.\n *\n * @param permission - The permission to get the `chainIds` caveat from.\n * @returns An array of `chainIds` that the snap supports, or null if none.\n */\nexport function getChainIdsCaveat(\n permission?: PermissionConstraint,\n): ChainId[] | null {\n if (!permission?.caveats) {\n return null;\n }\n\n const caveat = permission.caveats.find(\n (permCaveat) => permCaveat.type === SnapCaveatType.ChainIds,\n ) as Caveat<string, string[]> | undefined;\n\n return caveat ? (caveat.value as ChainId[]) : null;\n}\n\n/**\n * Extracts the CAIP-2 chain ID from a CAIP-19 asset ID.\n * e.g., \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/slip44:501\" -> \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\"\n * Uses @metamask/utils parseCaipAssetType for CAIP parsing.\n *\n * @param assetId - The CAIP-19 asset ID to extract chain from.\n * @returns The CAIP-2 chain ID portion of the asset ID.\n */\nexport function extractChainFromAssetId(assetId: string): ChainId {\n const parsed = parseCaipAssetType(assetId as CaipAssetType);\n return parsed.chainId;\n}\n\n// ============================================================================\n// STATE\n// ============================================================================\n\n/**\n * State for the SnapDataSource.\n * Uses dynamic snap discovery - chains are populated from PermissionController.\n */\nexport type SnapDataSourceState = {\n /**\n * Mapping of chain IDs to snap IDs that support them.\n * Used to filter which accounts to process for a given chain request.\n */\n chainToSnap: Record<ChainId, string>;\n} & DataSourceState;\n\nconst defaultSnapState: SnapDataSourceState = {\n activeChains: [],\n chainToSnap: {},\n};\n\n// ============================================================================\n// MESSENGER TYPES\n// ============================================================================\n\n/**\n * Allowed events that SnapDataSource can subscribe to.\n */\nexport type SnapDataSourceAllowedEvents =\n | AccountsControllerAccountBalancesUpdatedEvent\n | PermissionControllerStateChange\n | SnapControllerSnapInstalledEvent;\n\nexport type SnapDataSourceAllowedActions =\n | SnapControllerGetRunnableSnapsAction\n | SnapControllerHandleRequestAction\n | GetPermissions;\n\n// ============================================================================\n// OPTIONS\n// ============================================================================\n\nexport type SnapDataSourceOptions = {\n /** The AssetsController messenger (shared by all data sources). */\n messenger: AssetsControllerMessenger;\n /** Called when this data source's active chains change. Pass dataSourceName so the controller knows the source. */\n onActiveChainsUpdated: (\n dataSourceName: string,\n chains: ChainId[],\n previousChains: ChainId[],\n ) => void;\n /** Configured networks to support (defaults to all snap networks) */\n configuredNetworks?: ChainId[];\n /** Default polling interval in ms for subscriptions */\n pollInterval?: number;\n /** Initial state */\n state?: Partial<SnapDataSourceState>;\n};\n\n// ============================================================================\n// SNAP DATA SOURCE\n// ============================================================================\n\n/**\n * Unified Snap data source that routes requests to the appropriate wallet snap\n * based on the chain ID prefix.\n *\n * @example\n * ```typescript\n * const snapDataSource = new SnapDataSource({\n * messenger,\n * onActiveChainsUpdated: (chains) => { /* ... *\\/ },\n * });\n *\n * // Fetch will automatically route to the correct snap\n * await snapDataSource.fetch({\n * chainIds: ['solana:mainnet', 'bip122:000000000019d6689c085ae165831e93'],\n * accountIds: ['account1'],\n * });\n * ```\n */\nexport class SnapDataSource extends AbstractDataSource<\n typeof SNAP_DATA_SOURCE_NAME,\n SnapDataSourceState\n> {\n readonly #messenger: AssetsControllerMessenger;\n\n readonly #onActiveChainsUpdated: (\n dataSourceName: string,\n chains: ChainId[],\n previousChains: ChainId[],\n ) => void;\n\n /** Bound handler for snap keyring balance updates, stored for cleanup */\n readonly #handleSnapBalancesUpdatedBound: (\n payload: AccountBalancesUpdatedEventPayload,\n ) => void;\n\n readonly #handlePermissionStateChangeBound: () => void;\n\n /** Cache of KeyringClient instances per snap ID to avoid re-instantiation */\n readonly #keyringClientCache: Map<string, KeyringClient> = new Map();\n\n constructor(options: SnapDataSourceOptions) {\n super(SNAP_DATA_SOURCE_NAME, {\n ...defaultSnapState,\n ...options.state,\n });\n\n this.#messenger = options.messenger;\n this.#onActiveChainsUpdated = options.onActiveChainsUpdated;\n\n // Bind handlers for cleanup in destroy()\n this.#handleSnapBalancesUpdatedBound = this.#handleSnapBalancesUpdated.bind(\n this,\n ) as (payload: AccountBalancesUpdatedEventPayload) => void;\n this.#handlePermissionStateChangeBound =\n this.#discoverKeyringSnaps.bind(this);\n\n this.#subscribeToEvents();\n\n // Discover keyring-capable snaps and populate activeChains dynamically\n this.#discoverKeyringSnaps();\n }\n\n /**\n * Subscribe to all events needed by SnapDataSource.\n * Groups snap keyring events and permission change events.\n */\n #subscribeToEvents(): void {\n // Subscribe to snap keyring events and permission changes (not in AssetsControllerEvents).\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const messenger = this.#messenger as any;\n messenger.subscribe(\n 'AccountsController:accountBalancesUpdated',\n this.#handleSnapBalancesUpdatedBound,\n );\n messenger.subscribe(\n 'PermissionController:stateChange',\n this.#handlePermissionStateChangeBound,\n );\n // Rediscover keyring snaps when any snap gets installed\n messenger.subscribe('SnapController:snapInstalled', () => {\n this.#discoverKeyringSnaps();\n });\n }\n\n /**\n * Handle snap balance updates from the keyring.\n * Transforms the payload and publishes to AssetsController.\n *\n * @param payload - The balance update payload from AccountsController.\n */\n #handleSnapBalancesUpdated(\n payload: AccountBalancesUpdatedEventPayload,\n ): void {\n // Transform the snap keyring payload to DataResponse format\n let assetsBalance: NonNullable<DataResponse['assetsBalance']> | undefined;\n\n for (const [accountId, assets] of Object.entries(payload.balances)) {\n let accountAssets: Record<Caip19AssetId, AssetBalance> | undefined;\n\n for (const [assetId, balance] of Object.entries(assets)) {\n let chainId: ChainId;\n try {\n chainId = extractChainFromAssetId(assetId);\n } catch (error) {\n log('Skipping snap balance for malformed asset ID', {\n assetId,\n error,\n });\n continue;\n }\n if (this.#isChainSupportedBySnap(chainId)) {\n accountAssets ??= {};\n accountAssets[assetId as Caip19AssetId] = {\n amount: balance.amount,\n };\n }\n }\n\n if (accountAssets) {\n assetsBalance ??= {};\n assetsBalance[accountId] = accountAssets;\n }\n }\n\n // Only report if we have snap-related updates\n if (assetsBalance) {\n const response: DataResponse = { assetsBalance, updateMode: 'merge' };\n for (const subscription of this.activeSubscriptions.values()) {\n subscription.onAssetsUpdate(response)?.catch(console.error);\n }\n }\n }\n\n /**\n * Check if a chain ID is supported by any discovered snap.\n *\n * @param chainId - The CAIP-2 chain ID to check.\n * @returns True if we have a snap that supports this chain.\n */\n #isChainSupportedBySnap(chainId: ChainId): boolean {\n return this.state.activeChains.includes(chainId);\n }\n\n // ============================================================================\n // SNAP DISCOVERY (Dynamic via PermissionController)\n // ============================================================================\n\n /**\n * Get all runnable snaps from SnapController.\n * Runnable snaps are enabled and not blocked.\n *\n * @returns Array of runnable snaps.\n */\n #getRunnableSnaps(): Snap[] {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (this.#messenger as any).call(\n 'SnapController:getRunnableSnaps',\n ) as Snap[];\n } catch (error) {\n log('Failed to get runnable snaps', error);\n return [];\n }\n }\n\n /**\n * Get permissions for a snap from PermissionController.\n *\n * @param snapId - The snap ID to get permissions for.\n * @returns The snap's permissions, or undefined if none.\n */\n #getSnapPermissions(\n snapId: string,\n ): SubjectPermissions<PermissionConstraint> | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (this.#messenger as any).call(\n 'PermissionController:getPermissions',\n snapId,\n ) as SubjectPermissions<PermissionConstraint>;\n } catch (error) {\n log('Failed to get permissions for snap', { snapId, error });\n return undefined;\n }\n }\n\n /**\n * Discover all snaps with keyring capabilities and their supported chains.\n * Uses PermissionController to find snaps with endowment:keyring permission.\n * Updates chainToSnap mapping and activeChains.\n *\n * Called on initialization and whenever PermissionController state changes\n * (e.g., new snaps installed, permissions granted/revoked).\n *\n * @remarks\n * **Known limitation:** If discovery fails (e.g., SnapController not ready),\n * the data source continues with empty chainToSnap. This means no snap\n * chains will be supported until a re-discovery is triggered by a permission\n * change. Callers should be aware that initialization may complete with no\n * active chains.\n */\n #discoverKeyringSnaps(): void {\n try {\n const runnableSnaps = this.#getRunnableSnaps();\n const chainToSnap: Record<ChainId, string> = {};\n const supportedChains: ChainId[] = [];\n\n for (const snap of runnableSnaps) {\n const permissions = this.#getSnapPermissions(snap.id);\n // Must have endowment:keyring permission to be a keyring snap\n if (!permissions?.[KEYRING_PERMISSION]) {\n continue;\n }\n\n // Get chainIds caveat from the assets permission (not keyring permission)\n // The chainIds are stored in endowment:assets\n const assetsPermission = permissions[ASSETS_PERMISSION];\n const chainIds = getChainIdsCaveat(assetsPermission);\n\n // Map each chain to this snap (first snap wins if multiple support same chain)\n if (chainIds) {\n for (const chainId of chainIds) {\n if (!(chainId in chainToSnap)) {\n chainToSnap[chainId] = snap.id;\n supportedChains.push(chainId);\n }\n }\n }\n }\n\n // Update chainToSnap mapping\n this.state.chainToSnap = chainToSnap;\n\n // Notify if chains changed\n try {\n const previous = [...this.state.activeChains];\n this.updateActiveChains(supportedChains, (updatedChains) => {\n this.#onActiveChainsUpdated(this.getName(), updatedChains, previous);\n });\n } catch {\n // AssetsController not ready yet - expected during initialization\n }\n } catch (error) {\n log('Keyring snap discovery failed', { error });\n this.state.chainToSnap = {};\n try {\n const previous = [...this.state.activeChains];\n this.updateActiveChains([], (updatedChains) => {\n this.#onActiveChainsUpdated(this.getName(), updatedChains, previous);\n });\n } catch {\n // AssetsController not ready yet - expected during initialization\n }\n }\n }\n\n // ============================================================================\n // FETCH\n // ============================================================================\n\n async fetch(request: DataRequest): Promise<DataResponse> {\n // Guard against undefined request\n // Note: chainIds filtering is done by middleware/subscribe before calling fetch\n if (!request?.chainIds?.length) {\n return {};\n }\n if (!request?.accountsWithSupportedChains?.length) {\n return { assetsBalance: {}, assetsInfo: {}, updateMode: 'merge' };\n }\n\n const results: DataResponse = {\n assetsBalance: {},\n assetsInfo: {},\n updateMode: 'merge',\n };\n\n // Fetch balances for each account using its snap ID from metadata\n for (const { account } of request.accountsWithSupportedChains) {\n // Skip accounts without snap metadata (non-snap accounts)\n const snapId = account.metadata.snap?.id;\n if (!snapId) {\n continue;\n }\n\n // Skip accounts whose snap doesn't support any of the requested chains\n const snapSupportsRequestedChains = request.chainIds.some(\n (chainId) => this.state.chainToSnap[chainId] === snapId,\n );\n if (!snapSupportsRequestedChains) {\n continue;\n }\n\n const accountId = account.id;\n try {\n const client = this.#getKeyringClient(snapId);\n\n // Step 1: Get the list of assets for this account\n const accountAssets = await client.listAccountAssets(accountId);\n\n // If no assets, skip to next account\n if (!accountAssets || accountAssets.length === 0) {\n continue;\n }\n\n // Step 2: Get balances for those specific assets\n const balances: Record<CaipAssetType, Balance> =\n await client.getAccountBalances(\n accountId,\n accountAssets as CaipAssetType[],\n );\n\n // Transform keyring response to DataResponse format\n if (balances && typeof balances === 'object' && results.assetsBalance) {\n for (const [assetId, balance] of Object.entries(balances)) {\n results.assetsBalance[accountId] ??= {};\n const accountBalances = results.assetsBalance[accountId];\n if (accountBalances) {\n (accountBalances as Record<string, unknown>)[assetId] = {\n amount: balance.amount,\n };\n }\n }\n }\n } catch {\n // Expected when account doesn't belong to this snap\n }\n }\n\n return results;\n }\n\n // ============================================================================\n // MIDDLEWARE\n // ============================================================================\n\n /**\n * Get the middleware for fetching balances via Snaps.\n * This middleware:\n * - Supports multiple accounts in a single request\n * - Filters request to only chains this data source supports\n * - Fetches balances for those chains for all accounts\n * - Merges response into context\n * - Removes handled chains from request for next middleware\n *\n * @returns The middleware function for the assets pipeline.\n */\n get assetsMiddleware(): Middleware {\n return async (context, next) => {\n const { request } = context;\n\n // Filter to chains this data source supports\n const supportedChains = request.chainIds.filter((chainId) =>\n this.state.activeChains.includes(chainId),\n );\n\n // If no supported chains, skip and pass to next middleware\n if (supportedChains.length === 0) {\n return next(context);\n }\n\n let successfullyHandledChains: ChainId[] = [];\n\n try {\n // Fetch for supported chains\n const response = await this.fetch({\n ...request,\n chainIds: supportedChains,\n });\n\n // Merge response into context\n if (response.assetsBalance) {\n context.response.assetsBalance ??= {};\n for (const [accountId, accountBalances] of Object.entries(\n response.assetsBalance,\n )) {\n context.response.assetsBalance[accountId] = {\n ...context.response.assetsBalance[accountId],\n ...accountBalances,\n };\n }\n }\n if (response.assetsInfo) {\n context.response.assetsInfo = {\n ...context.response.assetsInfo,\n ...response.assetsInfo,\n };\n }\n if (response.assetsPrice) {\n context.response.assetsPrice = {\n ...context.response.assetsPrice,\n ...response.assetsPrice,\n };\n }\n\n // Determine successfully handled chains (exclude errors)\n const failedChains = new Set(Object.keys(response.errors ?? {}));\n successfullyHandledChains = supportedChains.filter(\n (chainId) => !failedChains.has(chainId),\n );\n } catch (error) {\n log('Middleware fetch failed', { error });\n successfullyHandledChains = [];\n }\n\n // Prepare context for next middleware\n let nextContext = context;\n if (successfullyHandledChains.length > 0) {\n const remainingChains = request.chainIds.filter(\n (chainId) => !successfullyHandledChains.includes(chainId),\n );\n nextContext = {\n ...context,\n request: {\n ...request,\n chainIds: remainingChains,\n },\n };\n }\n\n // Call next middleware\n return next(nextContext);\n };\n }\n\n // ============================================================================\n // SUBSCRIBE - Routes to appropriate snap(s)\n // ============================================================================\n\n async subscribe(subscriptionRequest: SubscriptionRequest): Promise<void> {\n const { request, subscriptionId, isUpdate } = subscriptionRequest;\n\n // Guard against undefined request or chainIds\n if (!request?.chainIds) {\n return;\n }\n\n // Filter to chains we have a snap for\n const supportedChains = request.chainIds.filter((chainId) =>\n this.#isChainSupportedBySnap(chainId),\n );\n\n if (supportedChains.length === 0) {\n return;\n }\n\n if (isUpdate) {\n const existing = this.activeSubscriptions.get(subscriptionId);\n if (existing) {\n existing.chains = supportedChains;\n // Do a fetch to get latest data on subscription update\n this.fetch({\n ...request,\n chainIds: supportedChains,\n })\n .then(async (fetchResponse) => {\n if (Object.keys(fetchResponse.assetsBalance ?? {}).length > 0) {\n await existing.onAssetsUpdate(fetchResponse);\n }\n return fetchResponse;\n })\n .catch((error) => {\n log('Subscription update fetch failed', { subscriptionId, error });\n });\n return;\n }\n }\n\n await this.unsubscribe(subscriptionId);\n\n // Snaps provide real-time updates via AccountsController:accountBalancesUpdated\n // We only need to track the subscription and do an initial fetch\n // No polling needed - updates come through #handleSnapBalancesUpdated\n\n this.activeSubscriptions.set(subscriptionId, {\n cleanup: () => {\n // No timer to clear - we use event-based updates\n },\n chains: supportedChains,\n onAssetsUpdate: subscriptionRequest.onAssetsUpdate,\n });\n\n // Initial fetch to get current balances\n try {\n const fetchResponse = await this.fetch({\n ...request,\n chainIds: supportedChains,\n });\n\n const subscription = this.activeSubscriptions.get(subscriptionId);\n if (\n Object.keys(fetchResponse.assetsBalance ?? {}).length > 0 &&\n subscription\n ) {\n await subscription.onAssetsUpdate(fetchResponse);\n }\n } catch (error) {\n log('Initial fetch failed', { subscriptionId, error });\n }\n }\n\n // ============================================================================\n // KEYRING CLIENT\n // ============================================================================\n\n /**\n * Gets a `KeyringClient` for a Snap.\n * Caches clients per snap ID to avoid re-instantiation across multiple calls.\n *\n * @param snapId - ID of the Snap to get the client for.\n * @returns A `KeyringClient` for the Snap.\n */\n #getKeyringClient(snapId: string): KeyringClient {\n const cachedClient = this.#keyringClientCache.get(snapId);\n if (cachedClient) {\n return cachedClient;\n }\n\n const client = new KeyringClient({\n send: async (request: JsonRpcRequest): Promise<Json> =>\n await (\n this.#messenger as unknown as {\n call: (action: string, ...args: unknown[]) => Promise<Json> | Json;\n }\n ).call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n }),\n });\n\n this.#keyringClientCache.set(snapId, client);\n return client;\n }\n\n // ============================================================================\n // CLEANUP\n // ============================================================================\n\n destroy(): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const messenger = this.#messenger as any;\n\n // Unsubscribe from snap keyring events\n try {\n messenger.unsubscribe(\n 'AccountsController:accountBalancesUpdated',\n this.#handleSnapBalancesUpdatedBound,\n );\n } catch (error) {\n log('Failed to unsubscribe from snap keyring events', { error });\n }\n\n // Unsubscribe from permission changes\n try {\n messenger.unsubscribe(\n 'PermissionController:stateChange',\n this.#handlePermissionStateChangeBound,\n );\n } catch (error) {\n log('Failed to unsubscribe from permission changes', { error });\n }\n\n // Clean up active subscriptions\n for (const [subscriptionId] of this.activeSubscriptions) {\n this.unsubscribe(subscriptionId).catch(() => {\n // Ignore cleanup errors\n });\n }\n\n // Clear keyring client cache\n this.#keyringClientCache.clear();\n }\n}\n\n// ============================================================================\n// FACTORY\n// ============================================================================\n\nexport function createSnapDataSource(\n options: SnapDataSourceOptions,\n): SnapDataSource {\n return new SnapDataSource(options);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SnapDataSource.cjs","sourceRoot":"","sources":["../../src/data-sources/SnapDataSource.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,uEAA8D;AAc9D,uDAAoE;AACpE,2CAAqD;AAIrD,6CAAiE;AASjE,oEAA6D;AAkC7D,MAAM,GAAG,GAAG,IAAA,8BAAkB,EAAC,yBAAa,EAAE,gBAAgB,CAAC,CAAC;AAEhE,+EAA+E;AAC/E,YAAY;AACZ,+EAA+E;AAElE,QAAA,qBAAqB,GAAG,gBAAgB,CAAC;AAEtD,qDAAqD;AACxC,QAAA,kBAAkB,GAAG,mBAAmB,CAAC;AAEtD,wEAAwE;AAC3D,QAAA,iBAAiB,GAAG,kBAAkB,CAAC;AAEpD,+EAA+E;AAC/E,uBAAuB;AACvB,+EAA+E;AAE/E;;;;;;;;;GASG;AACH,SAAgB,iBAAiB,CAC/B,UAAiC;IAEjC,IAAI,CAAC,UAAU,EAAE,OAAO,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,MAAM,GAAG,UAAU,CAAC,OAAO,CAA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CAAC;IAC7C,OAAO,MAAM,CAAC;AAChB,CAAC;AAmCH,+EAA+E;AAC/E,UAAU;AACV,+EAA+E;AAE/E,SAAgB,oBAAoB,CAClC,OAA8B;IAE9B,OAAO,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC;AACrC,CAAC;AAJD,oDAIC","sourcesContent":["import type { Balance, CaipAssetType } from '@metamask/keyring-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type {\n Caveat,\n GetPermissions,\n PermissionConstraint,\n PermissionControllerStateChange,\n SubjectPermissions,\n} from '@metamask/permission-controller';\nimport type {\n SnapControllerGetRunnableSnapsAction,\n SnapControllerHandleRequestAction,\n SnapControllerSnapInstalledEvent,\n} from '@metamask/snaps-controllers';\nimport type { Snap, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType, SnapCaveatType } from '@metamask/snaps-utils';\nimport { parseCaipAssetType } from '@metamask/utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\n\nimport type { AssetsControllerMessenger } from '../AssetsController.js';\nimport { projectLogger, createModuleLogger } from '../logger.js';\nimport type {\n AssetBalance,\n ChainId,\n Caip19AssetId,\n DataRequest,\n DataResponse,\n Middleware,\n} from '../types.js';\nimport { AbstractDataSource } from './AbstractDataSource.js';\nimport type {\n DataSourceState,\n SubscriptionRequest,\n} from './AbstractDataSource.js';\n\n// ============================================================================\n// SNAP KEYRING EVENT TYPES\n// ============================================================================\n\n/**\n * Payload for AccountsController:accountBalancesUpdated event.\n * Re-published from SnapKeyring:accountBalancesUpdated.\n */\nexport type AccountBalancesUpdatedEventPayload = {\n balances: {\n [accountId: string]: {\n [assetId: string]: {\n amount: string;\n unit: string;\n metadata?: Record<string, Json>;\n };\n };\n };\n};\n\n/**\n * Event from AccountsController when snap balances are updated.\n */\nexport type AccountsControllerAccountBalancesUpdatedEvent = {\n type: 'AccountsController:accountBalancesUpdated';\n payload: [AccountBalancesUpdatedEventPayload];\n};\n\nconst log = createModuleLogger(projectLogger, 'SnapDataSource');\n\n// ============================================================================\n// CONSTANTS\n// ============================================================================\n\nexport const SNAP_DATA_SOURCE_NAME = 'SnapDataSource';\n\n/** The permission name for snap keyring endowment */\nexport const KEYRING_PERMISSION = 'endowment:keyring';\n\n/** The permission name for snap assets endowment (contains chainIds) */\nexport const ASSETS_PERMISSION = 'endowment:assets';\n\n// ============================================================================\n// PERMISSION UTILITIES\n// ============================================================================\n\n/**\n * Getter function to get the chainIds caveat from a permission.\n *\n * This does basic validation of the caveat, but does not validate the type or\n * value of the namespaces object itself, as this is handled by the\n * `PermissionsController` when the permission is requested.\n *\n * @param permission - The permission to get the `chainIds` caveat from.\n * @returns An array of `chainIds` that the snap supports, or null if none.\n */\nexport function getChainIdsCaveat(\n permission?: PermissionConstraint,\n): ChainId[] | null {\n if (!permission?.caveats) {\n return null;\n }\n\n const caveat = permission.caveats.find(\n (permCaveat) => permCaveat.type === SnapCaveatType.ChainIds,\n ) as Caveat<string, string[]> | undefined;\n\n return caveat ? (caveat.value as ChainId[]) : null;\n}\n\n/**\n * Extracts the CAIP-2 chain ID from a CAIP-19 asset ID.\n * e.g., \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/slip44:501\" -> \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\"\n * Uses @metamask/utils parseCaipAssetType for CAIP parsing.\n *\n * @param assetId - The CAIP-19 asset ID to extract chain from.\n * @returns The CAIP-2 chain ID portion of the asset ID.\n */\nexport function extractChainFromAssetId(assetId: string): ChainId {\n const parsed = parseCaipAssetType(assetId as CaipAssetType);\n return parsed.chainId;\n}\n\n// ============================================================================\n// STATE\n// ============================================================================\n\n/**\n * State for the SnapDataSource.\n * Uses dynamic snap discovery - chains are populated from PermissionController.\n */\nexport type SnapDataSourceState = {\n /**\n * Mapping of chain IDs to snap IDs that support them.\n * Used to filter which accounts to process for a given chain request.\n */\n chainToSnap: Record<ChainId, string>;\n} & DataSourceState;\n\nconst defaultSnapState: SnapDataSourceState = {\n activeChains: [],\n chainToSnap: {},\n};\n\n// ============================================================================\n// MESSENGER TYPES\n// ============================================================================\n\n/**\n * Allowed events that SnapDataSource can subscribe to.\n */\nexport type SnapDataSourceAllowedEvents =\n | AccountsControllerAccountBalancesUpdatedEvent\n | PermissionControllerStateChange\n | SnapControllerSnapInstalledEvent;\n\nexport type SnapDataSourceAllowedActions =\n | SnapControllerGetRunnableSnapsAction\n | SnapControllerHandleRequestAction\n | GetPermissions;\n\n// ============================================================================\n// OPTIONS\n// ============================================================================\n\nexport type SnapDataSourceOptions = {\n /** The AssetsController messenger (shared by all data sources). */\n messenger: AssetsControllerMessenger;\n /** Called when this data source's active chains change. Pass dataSourceName so the controller knows the source. */\n onActiveChainsUpdated: (\n dataSourceName: string,\n chains: ChainId[],\n previousChains: ChainId[],\n ) => void;\n /**\n * Called directly with snap-sourced balance updates (from\n * AccountsController:accountBalancesUpdated), independent of whether the\n * controller currently has an active subscription for the chain.\n */\n onAssetsUpdate: (response: DataResponse) => void | Promise<void>;\n /** Configured networks to support (defaults to all snap networks) */\n configuredNetworks?: ChainId[];\n /** Default polling interval in ms for subscriptions */\n pollInterval?: number;\n /** Initial state */\n state?: Partial<SnapDataSourceState>;\n};\n\n// ============================================================================\n// SNAP DATA SOURCE\n// ============================================================================\n\n/**\n * Unified Snap data source that routes requests to the appropriate wallet snap\n * based on the chain ID prefix.\n *\n * @example\n * ```typescript\n * const snapDataSource = new SnapDataSource({\n * messenger,\n * onActiveChainsUpdated: (chains) => { /* ... *\\/ },\n * });\n *\n * // Fetch will automatically route to the correct snap\n * await snapDataSource.fetch({\n * chainIds: ['solana:mainnet', 'bip122:000000000019d6689c085ae165831e93'],\n * accountIds: ['account1'],\n * });\n * ```\n */\nexport class SnapDataSource extends AbstractDataSource<\n typeof SNAP_DATA_SOURCE_NAME,\n SnapDataSourceState\n> {\n readonly #messenger: AssetsControllerMessenger;\n\n readonly #onActiveChainsUpdated: (\n dataSourceName: string,\n chains: ChainId[],\n previousChains: ChainId[],\n ) => void;\n\n readonly #onAssetsUpdate: (response: DataResponse) => void | Promise<void>;\n\n /** Bound handler for snap keyring balance updates, stored for cleanup */\n readonly #handleSnapBalancesUpdatedBound: (\n payload: AccountBalancesUpdatedEventPayload,\n ) => void;\n\n readonly #handlePermissionStateChangeBound: () => void;\n\n /** Cache of KeyringClient instances per snap ID to avoid re-instantiation */\n readonly #keyringClientCache: Map<string, KeyringClient> = new Map();\n\n constructor(options: SnapDataSourceOptions) {\n super(SNAP_DATA_SOURCE_NAME, {\n ...defaultSnapState,\n ...options.state,\n });\n\n this.#messenger = options.messenger;\n this.#onActiveChainsUpdated = options.onActiveChainsUpdated;\n this.#onAssetsUpdate = options.onAssetsUpdate;\n\n // Bind handlers for cleanup in destroy()\n this.#handleSnapBalancesUpdatedBound = this.#handleSnapBalancesUpdated.bind(\n this,\n ) as (payload: AccountBalancesUpdatedEventPayload) => void;\n this.#handlePermissionStateChangeBound =\n this.#discoverKeyringSnaps.bind(this);\n\n this.#subscribeToEvents();\n\n // Discover keyring-capable snaps and populate activeChains dynamically\n this.#discoverKeyringSnaps();\n }\n\n /**\n * Subscribe to all events needed by SnapDataSource.\n * Groups snap keyring events and permission change events.\n */\n #subscribeToEvents(): void {\n // Subscribe to snap keyring events and permission changes (not in AssetsControllerEvents).\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const messenger = this.#messenger as any;\n messenger.subscribe(\n 'AccountsController:accountBalancesUpdated',\n this.#handleSnapBalancesUpdatedBound,\n );\n messenger.subscribe(\n 'PermissionController:stateChange',\n this.#handlePermissionStateChangeBound,\n );\n // Rediscover keyring snaps when any snap gets installed\n messenger.subscribe('SnapController:snapInstalled', () => {\n this.#discoverKeyringSnaps();\n });\n }\n\n /**\n * Handle snap balance updates from the keyring.\n * Transforms the payload and publishes to AssetsController.\n *\n * @param payload - The balance update payload from AccountsController.\n */\n #handleSnapBalancesUpdated(\n payload: AccountBalancesUpdatedEventPayload,\n ): void {\n // Transform the snap keyring payload to DataResponse format\n let assetsBalance: NonNullable<DataResponse['assetsBalance']> | undefined;\n\n for (const [accountId, assets] of Object.entries(payload.balances)) {\n let accountAssets: Record<Caip19AssetId, AssetBalance> | undefined;\n\n for (const [assetId, balance] of Object.entries(assets)) {\n let chainId: ChainId;\n try {\n chainId = extractChainFromAssetId(assetId);\n } catch (error) {\n log('Skipping snap balance for malformed asset ID', {\n assetId,\n error,\n });\n continue;\n }\n if (this.#isChainSupportedBySnap(chainId)) {\n accountAssets ??= {};\n accountAssets[assetId as Caip19AssetId] = {\n amount: balance.amount,\n ...(balance.metadata ? { metadata: balance.metadata } : {}),\n };\n }\n }\n\n if (accountAssets) {\n assetsBalance ??= {};\n assetsBalance[accountId] = accountAssets;\n }\n }\n\n // Only report if we have snap-related updates\n if (assetsBalance) {\n const response: DataResponse = { assetsBalance, updateMode: 'merge' };\n Promise.resolve(this.#onAssetsUpdate(response)).catch(console.error);\n }\n }\n\n /**\n * Check if a chain ID is supported by any discovered snap.\n *\n * @param chainId - The CAIP-2 chain ID to check.\n * @returns True if we have a snap that supports this chain.\n */\n #isChainSupportedBySnap(chainId: ChainId): boolean {\n return this.state.activeChains.includes(chainId);\n }\n\n // ============================================================================\n // SNAP DISCOVERY (Dynamic via PermissionController)\n // ============================================================================\n\n /**\n * Get all runnable snaps from SnapController.\n * Runnable snaps are enabled and not blocked.\n *\n * @returns Array of runnable snaps.\n */\n #getRunnableSnaps(): Snap[] {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (this.#messenger as any).call(\n 'SnapController:getRunnableSnaps',\n ) as Snap[];\n } catch (error) {\n log('Failed to get runnable snaps', error);\n return [];\n }\n }\n\n /**\n * Get permissions for a snap from PermissionController.\n *\n * @param snapId - The snap ID to get permissions for.\n * @returns The snap's permissions, or undefined if none.\n */\n #getSnapPermissions(\n snapId: string,\n ): SubjectPermissions<PermissionConstraint> | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (this.#messenger as any).call(\n 'PermissionController:getPermissions',\n snapId,\n ) as SubjectPermissions<PermissionConstraint>;\n } catch (error) {\n log('Failed to get permissions for snap', { snapId, error });\n return undefined;\n }\n }\n\n /**\n * Discover all snaps with keyring capabilities and their supported chains.\n * Uses PermissionController to find snaps with endowment:keyring permission.\n * Updates chainToSnap mapping and activeChains.\n *\n * Called on initialization and whenever PermissionController state changes\n * (e.g., new snaps installed, permissions granted/revoked).\n *\n * @remarks\n * **Known limitation:** If discovery fails (e.g., SnapController not ready),\n * the data source continues with empty chainToSnap. This means no snap\n * chains will be supported until a re-discovery is triggered by a permission\n * change. Callers should be aware that initialization may complete with no\n * active chains.\n */\n #discoverKeyringSnaps(): void {\n try {\n const runnableSnaps = this.#getRunnableSnaps();\n const chainToSnap: Record<ChainId, string> = {};\n const supportedChains: ChainId[] = [];\n\n for (const snap of runnableSnaps) {\n const permissions = this.#getSnapPermissions(snap.id);\n // Must have endowment:keyring permission to be a keyring snap\n if (!permissions?.[KEYRING_PERMISSION]) {\n continue;\n }\n\n // Get chainIds caveat from the assets permission (not keyring permission)\n // The chainIds are stored in endowment:assets\n const assetsPermission = permissions[ASSETS_PERMISSION];\n const chainIds = getChainIdsCaveat(assetsPermission);\n\n // Map each chain to this snap (first snap wins if multiple support same chain)\n if (chainIds) {\n for (const chainId of chainIds) {\n if (!(chainId in chainToSnap)) {\n chainToSnap[chainId] = snap.id;\n supportedChains.push(chainId);\n }\n }\n }\n }\n\n // Update chainToSnap mapping\n this.state.chainToSnap = chainToSnap;\n\n // Notify if chains changed\n try {\n const previous = [...this.state.activeChains];\n this.updateActiveChains(supportedChains, (updatedChains) => {\n this.#onActiveChainsUpdated(this.getName(), updatedChains, previous);\n });\n } catch {\n // AssetsController not ready yet - expected during initialization\n }\n } catch (error) {\n log('Keyring snap discovery failed', { error });\n this.state.chainToSnap = {};\n try {\n const previous = [...this.state.activeChains];\n this.updateActiveChains([], (updatedChains) => {\n this.#onActiveChainsUpdated(this.getName(), updatedChains, previous);\n });\n } catch {\n // AssetsController not ready yet - expected during initialization\n }\n }\n }\n\n // ============================================================================\n // FETCH\n // ============================================================================\n\n async fetch(request: DataRequest): Promise<DataResponse> {\n // Guard against undefined request\n // Note: chainIds filtering is done by middleware/subscribe before calling fetch\n if (!request?.chainIds?.length) {\n return {};\n }\n if (!request?.accountsWithSupportedChains?.length) {\n return { assetsBalance: {}, assetsInfo: {}, updateMode: 'merge' };\n }\n\n const results: DataResponse = {\n assetsBalance: {},\n assetsInfo: {},\n updateMode: 'merge',\n };\n\n // Fetch balances for each account using its snap ID from metadata\n for (const { account } of request.accountsWithSupportedChains) {\n // Skip accounts without snap metadata (non-snap accounts)\n const snapId = account.metadata.snap?.id;\n if (!snapId) {\n continue;\n }\n\n // Skip accounts whose snap doesn't support any of the requested chains\n const snapSupportsRequestedChains = request.chainIds.some(\n (chainId) => this.state.chainToSnap[chainId] === snapId,\n );\n if (!snapSupportsRequestedChains) {\n continue;\n }\n\n const accountId = account.id;\n try {\n const client = this.#getKeyringClient(snapId);\n\n // Step 1: Get the list of assets for this account\n const accountAssets = await client.listAccountAssets(accountId);\n\n // If no assets, skip to next account\n if (!accountAssets || accountAssets.length === 0) {\n continue;\n }\n\n // Step 2: Get balances for those specific assets\n const balances: Record<CaipAssetType, Balance> =\n await client.getAccountBalances(\n accountId,\n accountAssets as CaipAssetType[],\n );\n\n // Transform keyring response to DataResponse format\n if (balances && typeof balances === 'object' && results.assetsBalance) {\n for (const [assetId, balance] of Object.entries(balances)) {\n results.assetsBalance[accountId] ??= {};\n const accountBalances = results.assetsBalance[accountId];\n if (accountBalances) {\n (accountBalances as Record<string, unknown>)[assetId] = {\n amount: balance.amount,\n ...(balance.metadata ? { metadata: balance.metadata } : {}),\n };\n }\n }\n }\n } catch {\n // Expected when account doesn't belong to this snap\n }\n }\n\n return results;\n }\n\n // ============================================================================\n // MIDDLEWARE\n // ============================================================================\n\n /**\n * Get the middleware for fetching balances via Snaps.\n * This middleware:\n * - Supports multiple accounts in a single request\n * - Filters request to only chains this data source supports\n * - Fetches balances for those chains for all accounts\n * - Merges response into context\n * - Removes handled chains from request for next middleware\n *\n * @returns The middleware function for the assets pipeline.\n */\n get assetsMiddleware(): Middleware {\n return async (context, next) => {\n const { request } = context;\n\n // Filter to chains this data source supports\n const supportedChains = request.chainIds.filter((chainId) =>\n this.state.activeChains.includes(chainId),\n );\n\n // If no supported chains, skip and pass to next middleware\n if (supportedChains.length === 0) {\n return next(context);\n }\n\n let successfullyHandledChains: ChainId[] = [];\n\n try {\n // Fetch for supported chains\n const response = await this.fetch({\n ...request,\n chainIds: supportedChains,\n });\n\n // Merge response into context\n if (response.assetsBalance) {\n context.response.assetsBalance ??= {};\n for (const [accountId, accountBalances] of Object.entries(\n response.assetsBalance,\n )) {\n context.response.assetsBalance[accountId] = {\n ...context.response.assetsBalance[accountId],\n ...accountBalances,\n };\n }\n }\n if (response.assetsInfo) {\n context.response.assetsInfo = {\n ...context.response.assetsInfo,\n ...response.assetsInfo,\n };\n }\n if (response.assetsPrice) {\n context.response.assetsPrice = {\n ...context.response.assetsPrice,\n ...response.assetsPrice,\n };\n }\n\n // Determine successfully handled chains (exclude errors)\n const failedChains = new Set(Object.keys(response.errors ?? {}));\n successfullyHandledChains = supportedChains.filter(\n (chainId) => !failedChains.has(chainId),\n );\n } catch (error) {\n log('Middleware fetch failed', { error });\n successfullyHandledChains = [];\n }\n\n // Prepare context for next middleware\n let nextContext = context;\n if (successfullyHandledChains.length > 0) {\n const remainingChains = request.chainIds.filter(\n (chainId) => !successfullyHandledChains.includes(chainId),\n );\n nextContext = {\n ...context,\n request: {\n ...request,\n chainIds: remainingChains,\n },\n };\n }\n\n // Call next middleware\n return next(nextContext);\n };\n }\n\n // ============================================================================\n // SUBSCRIBE - Routes to appropriate snap(s)\n // ============================================================================\n\n async subscribe(subscriptionRequest: SubscriptionRequest): Promise<void> {\n const { request, subscriptionId } = subscriptionRequest;\n\n // Guard against undefined request or chainIds\n if (!request?.chainIds) {\n return;\n }\n\n // Filter to chains we have a snap for\n const supportedChains = request.chainIds.filter((chainId) =>\n this.#isChainSupportedBySnap(chainId),\n );\n\n if (supportedChains.length === 0) {\n return;\n }\n\n try {\n const fetchResponse = await this.fetch({\n ...request,\n chainIds: supportedChains,\n });\n\n if (Object.keys(fetchResponse.assetsBalance ?? {}).length > 0) {\n await this.#onAssetsUpdate(fetchResponse);\n }\n } catch (error) {\n log('Initial fetch failed', { subscriptionId, error });\n }\n }\n\n // ============================================================================\n // KEYRING CLIENT\n // ============================================================================\n\n /**\n * Gets a `KeyringClient` for a Snap.\n * Caches clients per snap ID to avoid re-instantiation across multiple calls.\n *\n * @param snapId - ID of the Snap to get the client for.\n * @returns A `KeyringClient` for the Snap.\n */\n #getKeyringClient(snapId: string): KeyringClient {\n const cachedClient = this.#keyringClientCache.get(snapId);\n if (cachedClient) {\n return cachedClient;\n }\n\n const client = new KeyringClient({\n send: async (request: JsonRpcRequest): Promise<Json> =>\n await (\n this.#messenger as unknown as {\n call: (action: string, ...args: unknown[]) => Promise<Json> | Json;\n }\n ).call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n }),\n });\n\n this.#keyringClientCache.set(snapId, client);\n return client;\n }\n\n // ============================================================================\n // CLEANUP\n // ============================================================================\n\n destroy(): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const messenger = this.#messenger as any;\n\n // Unsubscribe from snap keyring events\n try {\n messenger.unsubscribe(\n 'AccountsController:accountBalancesUpdated',\n this.#handleSnapBalancesUpdatedBound,\n );\n } catch (error) {\n log('Failed to unsubscribe from snap keyring events', { error });\n }\n\n // Unsubscribe from permission changes\n try {\n messenger.unsubscribe(\n 'PermissionController:stateChange',\n this.#handlePermissionStateChangeBound,\n );\n } catch (error) {\n log('Failed to unsubscribe from permission changes', { error });\n }\n\n // Clear keyring client cache\n this.#keyringClientCache.clear();\n }\n}\n\n// ============================================================================\n// FACTORY\n// ============================================================================\n\nexport function createSnapDataSource(\n options: SnapDataSourceOptions,\n): SnapDataSource {\n return new SnapDataSource(options);\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { GetPermissions, PermissionConstraint, PermissionControllerStateChange } from "@metamask/permission-controller";
|
|
2
2
|
import type { SnapControllerGetRunnableSnapsAction, SnapControllerHandleRequestAction, SnapControllerSnapInstalledEvent } from "@metamask/snaps-controllers";
|
|
3
|
+
import type { Json } from "@metamask/utils";
|
|
3
4
|
import type { AssetsControllerMessenger } from "../AssetsController.cjs";
|
|
4
5
|
import type { ChainId, DataRequest, DataResponse, Middleware } from "../types.cjs";
|
|
5
6
|
import { AbstractDataSource } from "./AbstractDataSource.cjs";
|
|
@@ -14,6 +15,7 @@ export type AccountBalancesUpdatedEventPayload = {
|
|
|
14
15
|
[assetId: string]: {
|
|
15
16
|
amount: string;
|
|
16
17
|
unit: string;
|
|
18
|
+
metadata?: Record<string, Json>;
|
|
17
19
|
};
|
|
18
20
|
};
|
|
19
21
|
};
|
|
@@ -71,6 +73,12 @@ export type SnapDataSourceOptions = {
|
|
|
71
73
|
messenger: AssetsControllerMessenger;
|
|
72
74
|
/** Called when this data source's active chains change. Pass dataSourceName so the controller knows the source. */
|
|
73
75
|
onActiveChainsUpdated: (dataSourceName: string, chains: ChainId[], previousChains: ChainId[]) => void;
|
|
76
|
+
/**
|
|
77
|
+
* Called directly with snap-sourced balance updates (from
|
|
78
|
+
* AccountsController:accountBalancesUpdated), independent of whether the
|
|
79
|
+
* controller currently has an active subscription for the chain.
|
|
80
|
+
*/
|
|
81
|
+
onAssetsUpdate: (response: DataResponse) => void | Promise<void>;
|
|
74
82
|
/** Configured networks to support (defaults to all snap networks) */
|
|
75
83
|
configuredNetworks?: ChainId[];
|
|
76
84
|
/** Default polling interval in ms for subscriptions */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SnapDataSource.d.cts","sourceRoot":"","sources":["../../src/data-sources/SnapDataSource.ts"],"names":[],"mappings":"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AAG,OAAO,CAAC,YAAY,CAAC;IA4ExD;;;;;;;;;;OAUG;IACH,IAAI,gBAAgB,IAAI,UAAU,CA4EjC;IAMK,SAAS,CAAC,mBAAmB,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IAsExE,OAAO,IAAI,IAAI;CA2BhB;AAMD,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,qBAAqB,GAC7B,cAAc,CAEhB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { GetPermissions, PermissionConstraint, PermissionControllerStateChange } from "@metamask/permission-controller";
|
|
2
2
|
import type { SnapControllerGetRunnableSnapsAction, SnapControllerHandleRequestAction, SnapControllerSnapInstalledEvent } from "@metamask/snaps-controllers";
|
|
3
|
+
import type { Json } from "@metamask/utils";
|
|
3
4
|
import type { AssetsControllerMessenger } from "../AssetsController.mjs";
|
|
4
5
|
import type { ChainId, DataRequest, DataResponse, Middleware } from "../types.mjs";
|
|
5
6
|
import { AbstractDataSource } from "./AbstractDataSource.mjs";
|
|
@@ -14,6 +15,7 @@ export type AccountBalancesUpdatedEventPayload = {
|
|
|
14
15
|
[assetId: string]: {
|
|
15
16
|
amount: string;
|
|
16
17
|
unit: string;
|
|
18
|
+
metadata?: Record<string, Json>;
|
|
17
19
|
};
|
|
18
20
|
};
|
|
19
21
|
};
|
|
@@ -71,6 +73,12 @@ export type SnapDataSourceOptions = {
|
|
|
71
73
|
messenger: AssetsControllerMessenger;
|
|
72
74
|
/** Called when this data source's active chains change. Pass dataSourceName so the controller knows the source. */
|
|
73
75
|
onActiveChainsUpdated: (dataSourceName: string, chains: ChainId[], previousChains: ChainId[]) => void;
|
|
76
|
+
/**
|
|
77
|
+
* Called directly with snap-sourced balance updates (from
|
|
78
|
+
* AccountsController:accountBalancesUpdated), independent of whether the
|
|
79
|
+
* controller currently has an active subscription for the chain.
|
|
80
|
+
*/
|
|
81
|
+
onAssetsUpdate: (response: DataResponse) => void | Promise<void>;
|
|
74
82
|
/** Configured networks to support (defaults to all snap networks) */
|
|
75
83
|
configuredNetworks?: ChainId[];
|
|
76
84
|
/** Default polling interval in ms for subscriptions */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SnapDataSource.d.mts","sourceRoot":"","sources":["../../src/data-sources/SnapDataSource.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,cAAc,EACd,oBAAoB,EACpB,+BAA+B,EAEhC,wCAAwC;AACzC,OAAO,KAAK,EACV,oCAAoC,EACpC,iCAAiC,EACjC,gCAAgC,EACjC,oCAAoC;
|
|
1
|
+
{"version":3,"file":"SnapDataSource.d.mts","sourceRoot":"","sources":["../../src/data-sources/SnapDataSource.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,cAAc,EACd,oBAAoB,EACpB,+BAA+B,EAEhC,wCAAwC;AACzC,OAAO,KAAK,EACV,oCAAoC,EACpC,iCAAiC,EACjC,gCAAgC,EACjC,oCAAoC;AAIrC,OAAO,KAAK,EAAE,IAAI,EAAkB,wBAAwB;AAE5D,OAAO,KAAK,EAAE,yBAAyB,EAAE,gCAA+B;AAExE,OAAO,KAAK,EAEV,OAAO,EAEP,WAAW,EACX,YAAY,EACZ,UAAU,EACX,qBAAoB;AACrB,OAAO,EAAE,kBAAkB,EAAE,iCAAgC;AAC7D,OAAO,KAAK,EACV,eAAe,EACf,mBAAmB,EACpB,iCAAgC;AAMjC;;;GAGG;AACH,MAAM,MAAM,kCAAkC,GAAG;IAC/C,QAAQ,EAAE;QACR,CAAC,SAAS,EAAE,MAAM,GAAG;YACnB,CAAC,OAAO,EAAE,MAAM,GAAG;gBACjB,MAAM,EAAE,MAAM,CAAC;gBACf,IAAI,EAAE,MAAM,CAAC;gBACb,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;aACjC,CAAC;SACH,CAAC;KACH,CAAC;CACH,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,6CAA6C,GAAG;IAC1D,I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B,CAAC,CAAC;CACtC,CAAC;AAMF;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,cAAe,SAAQ,kBAAkB,CACpD,OAAO,qBAAqB,EAC5B,mBAAmB,CACpB;;gBAqBa,OAAO,EAAE,qBAAqB;IA4NpC,KAAK,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,YAAY,CAAC;IA4ExD;;;;;;;;;;OAUG;IACH,IAAI,gBAAgB,IAAI,UAAU,CA4EjC;IAMK,SAAS,CAAC,mBAAmB,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IAsExE,OAAO,IAAI,IAAI;CA2BhB;AAMD,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,qBAAqB,GAC7B,cAAc,CAEhB"}
|
|
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
9
9
|
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");
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
|
-
var _SnapDataSource_instances, _SnapDataSource_messenger, _SnapDataSource_onActiveChainsUpdated, _SnapDataSource_handleSnapBalancesUpdatedBound, _SnapDataSource_handlePermissionStateChangeBound, _SnapDataSource_keyringClientCache, _SnapDataSource_subscribeToEvents, _SnapDataSource_handleSnapBalancesUpdated, _SnapDataSource_isChainSupportedBySnap, _SnapDataSource_getRunnableSnaps, _SnapDataSource_getSnapPermissions, _SnapDataSource_discoverKeyringSnaps, _SnapDataSource_getKeyringClient;
|
|
12
|
+
var _SnapDataSource_instances, _SnapDataSource_messenger, _SnapDataSource_onActiveChainsUpdated, _SnapDataSource_onAssetsUpdate, _SnapDataSource_handleSnapBalancesUpdatedBound, _SnapDataSource_handlePermissionStateChangeBound, _SnapDataSource_keyringClientCache, _SnapDataSource_subscribeToEvents, _SnapDataSource_handleSnapBalancesUpdated, _SnapDataSource_isChainSupportedBySnap, _SnapDataSource_getRunnableSnaps, _SnapDataSource_getSnapPermissions, _SnapDataSource_discoverKeyringSnaps, _SnapDataSource_getKeyringClient;
|
|
13
13
|
import { KeyringClient } from "@metamask/keyring-snap-client";
|
|
14
14
|
import { HandlerType, SnapCaveatType } from "@metamask/snaps-utils";
|
|
15
15
|
import { parseCaipAssetType } from "@metamask/utils";
|
|
@@ -90,6 +90,7 @@ export class SnapDataSource extends AbstractDataSource {
|
|
|
90
90
|
_SnapDataSource_instances.add(this);
|
|
91
91
|
_SnapDataSource_messenger.set(this, void 0);
|
|
92
92
|
_SnapDataSource_onActiveChainsUpdated.set(this, void 0);
|
|
93
|
+
_SnapDataSource_onAssetsUpdate.set(this, void 0);
|
|
93
94
|
/** Bound handler for snap keyring balance updates, stored for cleanup */
|
|
94
95
|
_SnapDataSource_handleSnapBalancesUpdatedBound.set(this, void 0);
|
|
95
96
|
_SnapDataSource_handlePermissionStateChangeBound.set(this, void 0);
|
|
@@ -97,6 +98,7 @@ export class SnapDataSource extends AbstractDataSource {
|
|
|
97
98
|
_SnapDataSource_keyringClientCache.set(this, new Map());
|
|
98
99
|
__classPrivateFieldSet(this, _SnapDataSource_messenger, options.messenger, "f");
|
|
99
100
|
__classPrivateFieldSet(this, _SnapDataSource_onActiveChainsUpdated, options.onActiveChainsUpdated, "f");
|
|
101
|
+
__classPrivateFieldSet(this, _SnapDataSource_onAssetsUpdate, options.onAssetsUpdate, "f");
|
|
100
102
|
// Bind handlers for cleanup in destroy()
|
|
101
103
|
__classPrivateFieldSet(this, _SnapDataSource_handleSnapBalancesUpdatedBound, __classPrivateFieldGet(this, _SnapDataSource_instances, "m", _SnapDataSource_handleSnapBalancesUpdated).bind(this), "f");
|
|
102
104
|
__classPrivateFieldSet(this, _SnapDataSource_handlePermissionStateChangeBound, __classPrivateFieldGet(this, _SnapDataSource_instances, "m", _SnapDataSource_discoverKeyringSnaps).bind(this), "f");
|
|
@@ -153,6 +155,7 @@ export class SnapDataSource extends AbstractDataSource {
|
|
|
153
155
|
if (accountBalances) {
|
|
154
156
|
accountBalances[assetId] = {
|
|
155
157
|
amount: balance.amount,
|
|
158
|
+
...(balance.metadata ? { metadata: balance.metadata } : {}),
|
|
156
159
|
};
|
|
157
160
|
}
|
|
158
161
|
}
|
|
@@ -245,7 +248,7 @@ export class SnapDataSource extends AbstractDataSource {
|
|
|
245
248
|
// SUBSCRIBE - Routes to appropriate snap(s)
|
|
246
249
|
// ============================================================================
|
|
247
250
|
async subscribe(subscriptionRequest) {
|
|
248
|
-
const { request, subscriptionId
|
|
251
|
+
const { request, subscriptionId } = subscriptionRequest;
|
|
249
252
|
// Guard against undefined request or chainIds
|
|
250
253
|
if (!request?.chainIds) {
|
|
251
254
|
return;
|
|
@@ -255,48 +258,13 @@ export class SnapDataSource extends AbstractDataSource {
|
|
|
255
258
|
if (supportedChains.length === 0) {
|
|
256
259
|
return;
|
|
257
260
|
}
|
|
258
|
-
if (isUpdate) {
|
|
259
|
-
const existing = this.activeSubscriptions.get(subscriptionId);
|
|
260
|
-
if (existing) {
|
|
261
|
-
existing.chains = supportedChains;
|
|
262
|
-
// Do a fetch to get latest data on subscription update
|
|
263
|
-
this.fetch({
|
|
264
|
-
...request,
|
|
265
|
-
chainIds: supportedChains,
|
|
266
|
-
})
|
|
267
|
-
.then(async (fetchResponse) => {
|
|
268
|
-
if (Object.keys(fetchResponse.assetsBalance ?? {}).length > 0) {
|
|
269
|
-
await existing.onAssetsUpdate(fetchResponse);
|
|
270
|
-
}
|
|
271
|
-
return fetchResponse;
|
|
272
|
-
})
|
|
273
|
-
.catch((error) => {
|
|
274
|
-
log('Subscription update fetch failed', { subscriptionId, error });
|
|
275
|
-
});
|
|
276
|
-
return;
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
await this.unsubscribe(subscriptionId);
|
|
280
|
-
// Snaps provide real-time updates via AccountsController:accountBalancesUpdated
|
|
281
|
-
// We only need to track the subscription and do an initial fetch
|
|
282
|
-
// No polling needed - updates come through #handleSnapBalancesUpdated
|
|
283
|
-
this.activeSubscriptions.set(subscriptionId, {
|
|
284
|
-
cleanup: () => {
|
|
285
|
-
// No timer to clear - we use event-based updates
|
|
286
|
-
},
|
|
287
|
-
chains: supportedChains,
|
|
288
|
-
onAssetsUpdate: subscriptionRequest.onAssetsUpdate,
|
|
289
|
-
});
|
|
290
|
-
// Initial fetch to get current balances
|
|
291
261
|
try {
|
|
292
262
|
const fetchResponse = await this.fetch({
|
|
293
263
|
...request,
|
|
294
264
|
chainIds: supportedChains,
|
|
295
265
|
});
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
subscription) {
|
|
299
|
-
await subscription.onAssetsUpdate(fetchResponse);
|
|
266
|
+
if (Object.keys(fetchResponse.assetsBalance ?? {}).length > 0) {
|
|
267
|
+
await __classPrivateFieldGet(this, _SnapDataSource_onAssetsUpdate, "f").call(this, fetchResponse);
|
|
300
268
|
}
|
|
301
269
|
}
|
|
302
270
|
catch (error) {
|
|
@@ -323,17 +291,11 @@ export class SnapDataSource extends AbstractDataSource {
|
|
|
323
291
|
catch (error) {
|
|
324
292
|
log('Failed to unsubscribe from permission changes', { error });
|
|
325
293
|
}
|
|
326
|
-
// Clean up active subscriptions
|
|
327
|
-
for (const [subscriptionId] of this.activeSubscriptions) {
|
|
328
|
-
this.unsubscribe(subscriptionId).catch(() => {
|
|
329
|
-
// Ignore cleanup errors
|
|
330
|
-
});
|
|
331
|
-
}
|
|
332
294
|
// Clear keyring client cache
|
|
333
295
|
__classPrivateFieldGet(this, _SnapDataSource_keyringClientCache, "f").clear();
|
|
334
296
|
}
|
|
335
297
|
}
|
|
336
|
-
_SnapDataSource_messenger = new WeakMap(), _SnapDataSource_onActiveChainsUpdated = new WeakMap(), _SnapDataSource_handleSnapBalancesUpdatedBound = new WeakMap(), _SnapDataSource_handlePermissionStateChangeBound = new WeakMap(), _SnapDataSource_keyringClientCache = new WeakMap(), _SnapDataSource_instances = new WeakSet(), _SnapDataSource_subscribeToEvents = function _SnapDataSource_subscribeToEvents() {
|
|
298
|
+
_SnapDataSource_messenger = new WeakMap(), _SnapDataSource_onActiveChainsUpdated = new WeakMap(), _SnapDataSource_onAssetsUpdate = new WeakMap(), _SnapDataSource_handleSnapBalancesUpdatedBound = new WeakMap(), _SnapDataSource_handlePermissionStateChangeBound = new WeakMap(), _SnapDataSource_keyringClientCache = new WeakMap(), _SnapDataSource_instances = new WeakSet(), _SnapDataSource_subscribeToEvents = function _SnapDataSource_subscribeToEvents() {
|
|
337
299
|
// Subscribe to snap keyring events and permission changes (not in AssetsControllerEvents).
|
|
338
300
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
339
301
|
const messenger = __classPrivateFieldGet(this, _SnapDataSource_messenger, "f");
|
|
@@ -364,6 +326,7 @@ _SnapDataSource_messenger = new WeakMap(), _SnapDataSource_onActiveChainsUpdated
|
|
|
364
326
|
accountAssets ?? (accountAssets = {});
|
|
365
327
|
accountAssets[assetId] = {
|
|
366
328
|
amount: balance.amount,
|
|
329
|
+
...(balance.metadata ? { metadata: balance.metadata } : {}),
|
|
367
330
|
};
|
|
368
331
|
}
|
|
369
332
|
}
|
|
@@ -375,9 +338,7 @@ _SnapDataSource_messenger = new WeakMap(), _SnapDataSource_onActiveChainsUpdated
|
|
|
375
338
|
// Only report if we have snap-related updates
|
|
376
339
|
if (assetsBalance) {
|
|
377
340
|
const response = { assetsBalance, updateMode: 'merge' };
|
|
378
|
-
|
|
379
|
-
subscription.onAssetsUpdate(response)?.catch(console.error);
|
|
380
|
-
}
|
|
341
|
+
Promise.resolve(__classPrivateFieldGet(this, _SnapDataSource_onAssetsUpdate, "f").call(this, response)).catch(console.error);
|
|
381
342
|
}
|
|
382
343
|
}, _SnapDataSource_isChainSupportedBySnap = function _SnapDataSource_isChainSupportedBySnap(chainId) {
|
|
383
344
|
return this.state.activeChains.includes(chainId);
|