@metamask-previews/assets-controller 20.4.1-preview-c552582c8 → 20.4.1-preview-2da314d6d
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 +0 -9
- package/README.md +0 -3
- package/dist/AssetsController-method-action-types.d.ts +2 -2
- package/dist/AssetsController-method-action-types.js.map +1 -1
- package/dist/AssetsController.d.ts +12 -6
- package/dist/AssetsController.d.ts.map +1 -1
- package/dist/AssetsController.js +16 -21
- package/dist/AssetsController.js.map +1 -1
- package/dist/data-sources/AccountActivityDataSource.d.ts +2 -4
- package/dist/data-sources/AccountActivityDataSource.d.ts.map +1 -1
- package/dist/data-sources/AccountActivityDataSource.js +1 -3
- package/dist/data-sources/AccountActivityDataSource.js.map +1 -1
- package/dist/data-sources/PriceDataSource.d.ts +5 -32
- package/dist/data-sources/PriceDataSource.d.ts.map +1 -1
- package/dist/data-sources/PriceDataSource.js +91 -133
- package/dist/data-sources/PriceDataSource.js.map +1 -1
- package/dist/data-sources/index.d.ts +1 -1
- package/dist/data-sources/index.d.ts.map +1 -1
- package/dist/data-sources/index.js.map +1 -1
- package/dist/index.d.ts +2 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -2
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +0 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
- package/dist/data-sources/MarketStatsPriceStream.d.ts +0 -67
- package/dist/data-sources/MarketStatsPriceStream.d.ts.map +0 -1
- package/dist/data-sources/MarketStatsPriceStream.js +0 -181
- package/dist/data-sources/MarketStatsPriceStream.js.map +0 -1
- package/dist/store/MarketStatsStore.d.ts +0 -72
- package/dist/store/MarketStatsStore.d.ts.map +0 -1
- package/dist/store/MarketStatsStore.js +0 -182
- package/dist/store/MarketStatsStore.js.map +0 -1
|
@@ -2,7 +2,7 @@ import type { AccountActivityServiceBalanceUpdatedEvent, AccountActivityServiceS
|
|
|
2
2
|
import type { AssetsControllerMessenger } from '../AssetsController.js';
|
|
3
3
|
import type { ChainId, DataRequest, DataResponse } from '../types.js';
|
|
4
4
|
import { AbstractDataSource } from './AbstractDataSource.js';
|
|
5
|
-
import type { DataSourceState
|
|
5
|
+
import type { DataSourceState } from './AbstractDataSource.js';
|
|
6
6
|
declare const CONTROLLER_NAME = "AccountActivityDataSource";
|
|
7
7
|
/** Allowed events that AccountActivityDataSource subscribes to. */
|
|
8
8
|
export type AccountActivityDataSourceAllowedEvents = AccountActivityServiceBalanceUpdatedEvent | AccountActivityServiceStatusChangedEvent;
|
|
@@ -63,10 +63,8 @@ export declare class AccountActivityDataSource extends AbstractDataSource<typeof
|
|
|
63
63
|
* (see `#onBalanceUpdated`), and updates are pushed through the injected
|
|
64
64
|
* `#onAssetsUpdate` callback. This override exists only to satisfy the
|
|
65
65
|
* abstract contract and is intentionally a no-op.
|
|
66
|
-
*
|
|
67
|
-
* @param _request - Ignored. Account activity does not subscribe per request.
|
|
68
66
|
*/
|
|
69
|
-
subscribe(
|
|
67
|
+
subscribe(): Promise<void>;
|
|
70
68
|
destroy(): void;
|
|
71
69
|
}
|
|
72
70
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AccountActivityDataSource.d.ts","sourceRoot":"","sources":["../../src/data-sources/AccountActivityDataSource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,yCAAyC,EACzC,wCAAwC,EAEzC,MAAM,wBAAwB,CAAC;AAKhC,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AAExE,OAAO,KAAK,EAEV,OAAO,EAEP,WAAW,EACX,YAAY,EACb,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"AccountActivityDataSource.d.ts","sourceRoot":"","sources":["../../src/data-sources/AccountActivityDataSource.ts"],"names":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AC7C,OAAO,EAAE,gCAAgC,GACxC,yBAAyB,CAE3B"}
|
|
@@ -123,10 +123,8 @@ export class AccountActivityDataSource extends AbstractDataSource {
|
|
|
123
123
|
* (see `#onBalanceUpdated`), and updates are pushed through the injected
|
|
124
124
|
* `#onAssetsUpdate` callback. This override exists only to satisfy the
|
|
125
125
|
* abstract contract and is intentionally a no-op.
|
|
126
|
-
*
|
|
127
|
-
* @param _request - Ignored. Account activity does not subscribe per request.
|
|
128
126
|
*/
|
|
129
|
-
async subscribe(
|
|
127
|
+
async subscribe() {
|
|
130
128
|
// Intentionally empty — see method doc.
|
|
131
129
|
}
|
|
132
130
|
// ============================================================================
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AccountActivityDataSource.js","sourceRoot":"","sources":["../../src/data-sources/AccountActivityDataSource.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,cAAc,CAAC;AAGxD,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAQjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAM7D,+EAA+E;AAC/E,YAAY;AACZ,+EAA+E;AAE/E,MAAM,eAAe,GAAG,2BAA2B,CAAC;AAEpD,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,eAAe,CAAC,CAAC;AAE/D,+EAA+E;AAC/E,4BAA4B;AAC5B,+EAA+E;AAE/E;;;;;;;GAOG;AACH,SAAS,oCAAoC,CAC3C,OAAwB,EACxB,SAAiB;IAEjB,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAGvC,CAAC;IACF,aAAa,CAAC,SAAS,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAG5C,CAAC;IAEF,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ChangedEvent,\n BalanceUpdate,\n} from '@metamask/core-backend';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { isCaipChainId } from '@metamask/utils';\nimport { BigNumber as BigNumberJS } from 'bignumber.js';\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} from '../types.js';\nimport { safeNormalizeAssetId } from '../utils/index.js';\nimport { AbstractDataSource } from './AbstractDataSource.js';\nimport type {\n DataSourceState,\n SubscriptionRequest,\n} from './AbstractDataSource.js';\n\n// ============================================================================\n// CONSTANTS\n// ============================================================================\n\nconst CONTROLLER_NAME = 'AccountActivityDataSource';\n\nconst log = createModuleLogger(projectLogger, CONTROLLER_NAME);\n\n// ============================================================================\n// BALANCE UPDATE PROCESSING\n// ============================================================================\n\n/**\n * Convert AccountActivityMessage balance updates into a {@link DataResponse}\n * for AssetsController.\n *\n * @param updates - Balance updates from account-activity websocket payload.\n * @param accountId - Internal account UUID.\n * @returns DataResponse with merge mode when balances are present.\n */\nfunction processAccountActivityBalanceUpdates(\n updates: BalanceUpdate[],\n accountId: string,\n): DataResponse {\n const assetsBalance = Object.create(null) as Record<\n string,\n Record<Caip19AssetId, AssetBalance>\n >;\n assetsBalance[accountId] = Object.create(null) as Record<\n Caip19AssetId,\n AssetBalance\n >;\n\n for (const update of updates) {\n const { asset, postBalance } = update;\n\n if (!asset || !postBalance) {\n continue;\n }\n\n // The websocket sends lower-case ERC-20 addresses, while state and the\n // rest of the pipeline key assets by their checksummed ID. Normalizing\n // here keeps middleware comparisons (detection, occurrence filtering)\n // from treating an existing holding as brand new.\n const assetId = safeNormalizeAssetId(asset.type as Caip19AssetId);\n\n if (asset.decimals === undefined) {\n continue;\n }\n\n const rawBalanceStr = postBalance.amount.startsWith('0x')\n ? BigInt(postBalance.amount).toString()\n : postBalance.amount;\n\n const humanReadableAmount = new BigNumberJS(rawBalanceStr)\n .dividedBy(new BigNumberJS(10).pow(asset.decimals))\n .toFixed();\n\n assetsBalance[accountId][assetId] = {\n amount: humanReadableAmount,\n ...(postBalance.metadata ? { metadata: postBalance.metadata } : {}),\n };\n }\n\n const response: DataResponse = { updateMode: 'merge' };\n if (Object.keys(assetsBalance[accountId]).length > 0) {\n response.assetsBalance = assetsBalance;\n }\n\n return response;\n}\n\n// ============================================================================\n// MESSENGER TYPES\n// ============================================================================\n\n/** Allowed events that AccountActivityDataSource subscribes to. */\nexport type AccountActivityDataSourceAllowedEvents =\n | AccountActivityServiceBalanceUpdatedEvent\n | AccountActivityServiceStatusChangedEvent;\n\n// ============================================================================\n// STATE\n// ============================================================================\n\nexport type AccountActivityDataSourceState = DataSourceState;\n\nconst defaultState: AccountActivityDataSourceState = {\n activeChains: [],\n};\n\n// ============================================================================\n// OPTIONS\n// ============================================================================\n\nexport type AccountActivityDataSourceOptions = {\n /** The AssetsController messenger (shared by all data sources). */\n messenger: AssetsControllerMessenger;\n /** Called when active chains are updated. Pass dataSourceName so the controller knows the source. */\n onActiveChainsUpdated: (\n dataSourceName: string,\n chains: ChainId[],\n previousChains: ChainId[],\n ) => void;\n /**\n * Pushes decoded balance updates to the controller (bound to\n * `AssetsController.handleAssetsUpdate`). AADS is event-driven and never\n * takes part in the controller's subscribe handoff, so it receives this\n * callback directly instead of via a `SubscriptionRequest`.\n */\n onAssetsUpdate: (\n response: DataResponse,\n request?: DataRequest,\n ) => void | Promise<void>;\n state?: Partial<AccountActivityDataSourceState>;\n};\n\n// ============================================================================\n// ACCOUNT ACTIVITY DATA SOURCE\n// ============================================================================\n\n/**\n * Data source that consumes real-time updates from `AccountActivityService`.\n *\n * `AccountActivityService` owns the WebSocket connection and channel\n * subscriptions; this data source is a thin consumer of the two high-level\n * events that it publishes:\n *\n * - `AccountActivityService:balanceUpdated` — post-transaction balances for the\n * subscribed account(s). The address is resolved against the wallet's\n * selected account group, transformed into a {@link DataResponse} (via\n * {@link processAccountActivityBalanceUpdates}), and pushed to the controller\n * through the injected `onAssetsUpdate` callback.\n * - `AccountActivityService:statusChanged` — per-chain \"up\"/\"down\" notifications.\n * A chain reported \"up\" is claimed as an active chain (WebSocket is providing\n * real-time data); a chain reported \"down\" is released so polling data sources\n * can take over. Each change is applied directly via `updateActiveChains`,\n * which notifies the controller through `onActiveChainsUpdated`.\n *\n * This data source does NOT debounce, jitter, or gate chain updates itself.\n * Coalescing (collapsing bursts) and jitter (staggering the WS-subscribe herd\n * across clients) live in `AssetsController`, where the expensive re-subscribe\n * happens and where updates from all data sources converge. `activeChains` are\n * never seeded from the accounts API; they only ever reflect live\n * `statusChanged` events (the service flushes all tracked chains as \"down\" when\n * the WebSocket disconnects, releasing them).\n *\n * It subscribes to these events in its constructor (the same way\n * `TokenBalancesController` does). Unlike the polling data sources it does not\n * take part in the controller's subscribe/unsubscribe handoff: `subscribe` is a\n * no-op, balance updates are routed by resolving the address against the\n * wallet, and updates are pushed through the injected `onAssetsUpdate` callback.\n */\nexport class AccountActivityDataSource extends AbstractDataSource<\n typeof CONTROLLER_NAME,\n AccountActivityDataSourceState\n> {\n readonly #messenger: AssetsControllerMessenger;\n\n readonly #onActiveChainsUpdated: (\n dataSourceName: string,\n chains: ChainId[],\n previousChains: ChainId[],\n ) => void;\n\n readonly #onAssetsUpdate: (\n response: DataResponse,\n request?: DataRequest,\n ) => void | Promise<void>;\n\n readonly #onBalanceUpdatedBound: (event: {\n address: string;\n chain: string;\n updates: BalanceUpdate[];\n }) => void;\n\n constructor(options: AccountActivityDataSourceOptions) {\n super(CONTROLLER_NAME, {\n ...defaultState,\n ...options.state,\n });\n\n this.#messenger = options.messenger;\n this.#onActiveChainsUpdated = options.onActiveChainsUpdated;\n this.#onAssetsUpdate = options.onAssetsUpdate;\n this.#onBalanceUpdatedBound = this.#onBalanceUpdated.bind(this);\n\n this.#subscribeToEvents();\n }\n\n // ============================================================================\n // EVENT SUBSCRIPTIONS\n // ============================================================================\n\n #subscribeToEvents(): void {\n this.#messenger.subscribe(\n 'AccountActivityService:balanceUpdated',\n this.#onBalanceUpdatedBound,\n );\n this.#messenger.subscribe(\n 'AccountActivityService:statusChanged',\n this.#onAccountActivityStatusChanged,\n );\n }\n\n // ============================================================================\n // SUBSCRIBE / UNSUBSCRIBE\n // ============================================================================\n\n /**\n * AADS is event-driven and chain-agnostic: it never participates in the\n * controller's subscribe/unsubscribe handoff. Incoming `balanceUpdated`\n * events are routed by resolving the address against the wallet's accounts\n * (see `#onBalanceUpdated`), and updates are pushed through the injected\n * `#onAssetsUpdate` callback. This override exists only to satisfy the\n * abstract contract and is intentionally a no-op.\n *\n * @param _request - Ignored. Account activity does not subscribe per request.\n */\n async subscribe(_request?: SubscriptionRequest): Promise<void> {\n // Intentionally empty — see method doc.\n }\n\n // ============================================================================\n // BALANCE UPDATES\n // ============================================================================\n\n #onBalanceUpdated({\n address,\n chain,\n updates,\n }: {\n address: string;\n chain: string;\n updates: BalanceUpdate[];\n }): void {\n try {\n if (!address || !chain || !updates || updates.length === 0) {\n return;\n }\n\n const account = this.#findAccountForAddress(address);\n if (!account) {\n return;\n }\n\n const chainId = chain as ChainId;\n\n const response = processAccountActivityBalanceUpdates(\n updates,\n account.id,\n );\n\n if (!response.assetsBalance) {\n return;\n }\n\n const request: DataRequest = {\n accountsWithSupportedChains: [{ account, supportedChains: [chainId] }],\n chainIds: [chainId],\n dataTypes: ['balance', 'metadata', 'price'],\n };\n\n Promise.resolve(this.#onAssetsUpdate(response, request)).catch(\n (error) => {\n log('Failed to report balance update', { error });\n },\n );\n } catch (error) {\n log('Error handling balance update', error);\n }\n }\n\n /**\n * Find the wallet account matching the given activity address. EVM addresses\n * are matched case-insensitively; other namespaces are matched exactly.\n *\n * The candidate set is the accounts of the selected account group, resolved\n * from the wallet at event time (rather than from a stored subscription), so\n * AADS does not need to be re-subscribed whenever the account set changes.\n *\n * @param address - The account address from the activity message.\n * @returns The matching account, or null.\n */\n #findAccountForAddress(address: string): InternalAccount | null {\n const isEvm = address.startsWith('0x');\n\n return (\n this.#getWalletAccounts().find((candidate) =>\n isEvm\n ? candidate.address.toLowerCase() === address.toLowerCase()\n : candidate.address === address,\n ) ?? null\n );\n }\n\n /**\n * Resolve the accounts of the selected account group from the wallet,\n * mirroring `AssetsController.#getSelectedAccounts`.\n *\n * @returns The accounts of the selected account group.\n */\n #getWalletAccounts(): InternalAccount[] {\n const accounts = this.#messenger.call(\n 'AccountTreeController:getAccountsFromSelectedAccountGroup',\n );\n if (accounts.length > 0) {\n return accounts;\n }\n\n const selectedAccount = this.#messenger.call(\n 'AccountsController:getSelectedAccount',\n );\n return selectedAccount ? [selectedAccount] : [];\n }\n\n // ============================================================================\n // STATUS CHANGES\n // ============================================================================\n\n /**\n * Handle a `statusChanged` notification. Chains reported \"up\" are claimed as\n * active (WebSocket provides real-time data); chains reported \"down\" are\n * released so polling data sources take over. The change is applied directly;\n * coalescing and jitter are handled by `AssetsController`.\n *\n * @param options - The status change notification.\n * @param options.chainIds - The CAIP-2 chain IDs whose status changed.\n * @param options.status - Whether the chains are `up` or `down`.\n * @param options.timestamp - Optional timestamp of the status change.\n */\n readonly #onAccountActivityStatusChanged = ({\n chainIds,\n status,\n }: {\n chainIds: string[];\n status: 'up' | 'down';\n timestamp?: number;\n }): void => {\n try {\n // Act on every namespace (eip155, solana, etc.); AssetsController is\n // multichain. Only skip identifiers that are not valid CAIP-2 chain IDs.\n const validChains = chainIds.filter((chainId) => isCaipChainId(chainId));\n\n if (validChains.length === 0) {\n return;\n }\n\n const next = new Set(this.state.activeChains);\n if (status === 'up') {\n for (const chainId of validChains) {\n next.add(chainId);\n }\n } else {\n for (const chainId of validChains) {\n next.delete(chainId);\n }\n }\n\n const previous = [...this.state.activeChains];\n this.updateActiveChains(Array.from(next), (updatedChains) =>\n this.#onActiveChainsUpdated(this.getName(), updatedChains, previous),\n );\n } catch (error) {\n log('Error handling status change', error);\n }\n };\n\n // ============================================================================\n // CLEANUP\n // ============================================================================\n\n destroy(): void {\n try {\n this.#messenger.unsubscribe(\n 'AccountActivityService:balanceUpdated',\n this.#onBalanceUpdatedBound,\n );\n } catch (error) {\n log('Failed to unsubscribe from balanceUpdated', { error });\n }\n\n try {\n this.#messenger.unsubscribe(\n 'AccountActivityService:statusChanged',\n this.#onAccountActivityStatusChanged,\n );\n } catch (error) {\n log('Failed to unsubscribe from statusChanged', { error });\n }\n\n super.destroy();\n }\n}\n\n// ============================================================================\n// FACTORY FUNCTION\n// ============================================================================\n\n/**\n * Creates an AccountActivityDataSource instance.\n *\n * @param options - Configuration options for the data source.\n * @returns A new AccountActivityDataSource instance.\n */\nexport function createAccountActivityDataSource(\n options: AccountActivityDataSourceOptions,\n): AccountActivityDataSource {\n return new AccountActivityDataSource(options);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AccountActivityDataSource.js","sourceRoot":"","sources":["../../src/data-sources/AccountActivityDataSource.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,cAAc,CAAC;AAGxD,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAQjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAG7D,+EAA+E;AAC/E,YAAY;AACZ,+EAA+E;AAE/E,MAAM,eAAe,GAAG,2BAA2B,CAAC;AAEpD,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,eAAe,CAAC,CAAC;AAE/D,+EAA+E;AAC/E,4BAA4B;AAC5B,+EAA+E;AAE/E;;;;;;;GAOG;AACH,SAAS,oCAAoC,CAC3C,OAAwB,EACxB,SAAiB;IAEjB,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAGvC,CAAC;IACF,aAAa,CAAC,SAAS,CAAC,GAAG,MAAM,CAA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edEvent,\n AccountActivityServiceStatusChangedEvent,\n BalanceUpdate,\n} from '@metamask/core-backend';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { isCaipChainId } from '@metamask/utils';\nimport { BigNumber as BigNumberJS } from 'bignumber.js';\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} from '../types.js';\nimport { safeNormalizeAssetId } from '../utils/index.js';\nimport { AbstractDataSource } from './AbstractDataSource.js';\nimport type { DataSourceState } from './AbstractDataSource.js';\n\n// ============================================================================\n// CONSTANTS\n// ============================================================================\n\nconst CONTROLLER_NAME = 'AccountActivityDataSource';\n\nconst log = createModuleLogger(projectLogger, CONTROLLER_NAME);\n\n// ============================================================================\n// BALANCE UPDATE PROCESSING\n// ============================================================================\n\n/**\n * Convert AccountActivityMessage balance updates into a {@link DataResponse}\n * for AssetsController.\n *\n * @param updates - Balance updates from account-activity websocket payload.\n * @param accountId - Internal account UUID.\n * @returns DataResponse with merge mode when balances are present.\n */\nfunction processAccountActivityBalanceUpdates(\n updates: BalanceUpdate[],\n accountId: string,\n): DataResponse {\n const assetsBalance = Object.create(null) as Record<\n string,\n Record<Caip19AssetId, AssetBalance>\n >;\n assetsBalance[accountId] = Object.create(null) as Record<\n Caip19AssetId,\n AssetBalance\n >;\n\n for (const update of updates) {\n const { asset, postBalance } = update;\n\n if (!asset || !postBalance) {\n continue;\n }\n\n // The websocket sends lower-case ERC-20 addresses, while state and the\n // rest of the pipeline key assets by their checksummed ID. Normalizing\n // here keeps middleware comparisons (detection, occurrence filtering)\n // from treating an existing holding as brand new.\n const assetId = safeNormalizeAssetId(asset.type as Caip19AssetId);\n\n if (asset.decimals === undefined) {\n continue;\n }\n\n const rawBalanceStr = postBalance.amount.startsWith('0x')\n ? BigInt(postBalance.amount).toString()\n : postBalance.amount;\n\n const humanReadableAmount = new BigNumberJS(rawBalanceStr)\n .dividedBy(new BigNumberJS(10).pow(asset.decimals))\n .toFixed();\n\n assetsBalance[accountId][assetId] = {\n amount: humanReadableAmount,\n ...(postBalance.metadata ? { metadata: postBalance.metadata } : {}),\n };\n }\n\n const response: DataResponse = { updateMode: 'merge' };\n if (Object.keys(assetsBalance[accountId]).length > 0) {\n response.assetsBalance = assetsBalance;\n }\n\n return response;\n}\n\n// ============================================================================\n// MESSENGER TYPES\n// ============================================================================\n\n/** Allowed events that AccountActivityDataSource subscribes to. */\nexport type AccountActivityDataSourceAllowedEvents =\n | AccountActivityServiceBalanceUpdatedEvent\n | AccountActivityServiceStatusChangedEvent;\n\n// ============================================================================\n// STATE\n// ============================================================================\n\nexport type AccountActivityDataSourceState = DataSourceState;\n\nconst defaultState: AccountActivityDataSourceState = {\n activeChains: [],\n};\n\n// ============================================================================\n// OPTIONS\n// ============================================================================\n\nexport type AccountActivityDataSourceOptions = {\n /** The AssetsController messenger (shared by all data sources). */\n messenger: AssetsControllerMessenger;\n /** Called when active chains are updated. Pass dataSourceName so the controller knows the source. */\n onActiveChainsUpdated: (\n dataSourceName: string,\n chains: ChainId[],\n previousChains: ChainId[],\n ) => void;\n /**\n * Pushes decoded balance updates to the controller (bound to\n * `AssetsController.handleAssetsUpdate`). AADS is event-driven and never\n * takes part in the controller's subscribe handoff, so it receives this\n * callback directly instead of via a `SubscriptionRequest`.\n */\n onAssetsUpdate: (\n response: DataResponse,\n request?: DataRequest,\n ) => void | Promise<void>;\n state?: Partial<AccountActivityDataSourceState>;\n};\n\n// ============================================================================\n// ACCOUNT ACTIVITY DATA SOURCE\n// ============================================================================\n\n/**\n * Data source that consumes real-time updates from `AccountActivityService`.\n *\n * `AccountActivityService` owns the WebSocket connection and channel\n * subscriptions; this data source is a thin consumer of the two high-level\n * events that it publishes:\n *\n * - `AccountActivityService:balanceUpdated` — post-transaction balances for the\n * subscribed account(s). The address is resolved against the wallet's\n * selected account group, transformed into a {@link DataResponse} (via\n * {@link processAccountActivityBalanceUpdates}), and pushed to the controller\n * through the injected `onAssetsUpdate` callback.\n * - `AccountActivityService:statusChanged` — per-chain \"up\"/\"down\" notifications.\n * A chain reported \"up\" is claimed as an active chain (WebSocket is providing\n * real-time data); a chain reported \"down\" is released so polling data sources\n * can take over. Each change is applied directly via `updateActiveChains`,\n * which notifies the controller through `onActiveChainsUpdated`.\n *\n * This data source does NOT debounce, jitter, or gate chain updates itself.\n * Coalescing (collapsing bursts) and jitter (staggering the WS-subscribe herd\n * across clients) live in `AssetsController`, where the expensive re-subscribe\n * happens and where updates from all data sources converge. `activeChains` are\n * never seeded from the accounts API; they only ever reflect live\n * `statusChanged` events (the service flushes all tracked chains as \"down\" when\n * the WebSocket disconnects, releasing them).\n *\n * It subscribes to these events in its constructor (the same way\n * `TokenBalancesController` does). Unlike the polling data sources it does not\n * take part in the controller's subscribe/unsubscribe handoff: `subscribe` is a\n * no-op, balance updates are routed by resolving the address against the\n * wallet, and updates are pushed through the injected `onAssetsUpdate` callback.\n */\nexport class AccountActivityDataSource extends AbstractDataSource<\n typeof CONTROLLER_NAME,\n AccountActivityDataSourceState\n> {\n readonly #messenger: AssetsControllerMessenger;\n\n readonly #onActiveChainsUpdated: (\n dataSourceName: string,\n chains: ChainId[],\n previousChains: ChainId[],\n ) => void;\n\n readonly #onAssetsUpdate: (\n response: DataResponse,\n request?: DataRequest,\n ) => void | Promise<void>;\n\n readonly #onBalanceUpdatedBound: (event: {\n address: string;\n chain: string;\n updates: BalanceUpdate[];\n }) => void;\n\n constructor(options: AccountActivityDataSourceOptions) {\n super(CONTROLLER_NAME, {\n ...defaultState,\n ...options.state,\n });\n\n this.#messenger = options.messenger;\n this.#onActiveChainsUpdated = options.onActiveChainsUpdated;\n this.#onAssetsUpdate = options.onAssetsUpdate;\n this.#onBalanceUpdatedBound = this.#onBalanceUpdated.bind(this);\n\n this.#subscribeToEvents();\n }\n\n // ============================================================================\n // EVENT SUBSCRIPTIONS\n // ============================================================================\n\n #subscribeToEvents(): void {\n this.#messenger.subscribe(\n 'AccountActivityService:balanceUpdated',\n this.#onBalanceUpdatedBound,\n );\n this.#messenger.subscribe(\n 'AccountActivityService:statusChanged',\n this.#onAccountActivityStatusChanged,\n );\n }\n\n // ============================================================================\n // SUBSCRIBE / UNSUBSCRIBE\n // ============================================================================\n\n /**\n * AADS is event-driven and chain-agnostic: it never participates in the\n * controller's subscribe/unsubscribe handoff. Incoming `balanceUpdated`\n * events are routed by resolving the address against the wallet's accounts\n * (see `#onBalanceUpdated`), and updates are pushed through the injected\n * `#onAssetsUpdate` callback. This override exists only to satisfy the\n * abstract contract and is intentionally a no-op.\n */\n async subscribe(): Promise<void> {\n // Intentionally empty — see method doc.\n }\n\n // ============================================================================\n // BALANCE UPDATES\n // ============================================================================\n\n #onBalanceUpdated({\n address,\n chain,\n updates,\n }: {\n address: string;\n chain: string;\n updates: BalanceUpdate[];\n }): void {\n try {\n if (!address || !chain || !updates || updates.length === 0) {\n return;\n }\n\n const account = this.#findAccountForAddress(address);\n if (!account) {\n return;\n }\n\n const chainId = chain as ChainId;\n\n const response = processAccountActivityBalanceUpdates(\n updates,\n account.id,\n );\n\n if (!response.assetsBalance) {\n return;\n }\n\n const request: DataRequest = {\n accountsWithSupportedChains: [{ account, supportedChains: [chainId] }],\n chainIds: [chainId],\n dataTypes: ['balance', 'metadata', 'price'],\n };\n\n Promise.resolve(this.#onAssetsUpdate(response, request)).catch(\n (error) => {\n log('Failed to report balance update', { error });\n },\n );\n } catch (error) {\n log('Error handling balance update', error);\n }\n }\n\n /**\n * Find the wallet account matching the given activity address. EVM addresses\n * are matched case-insensitively; other namespaces are matched exactly.\n *\n * The candidate set is the accounts of the selected account group, resolved\n * from the wallet at event time (rather than from a stored subscription), so\n * AADS does not need to be re-subscribed whenever the account set changes.\n *\n * @param address - The account address from the activity message.\n * @returns The matching account, or null.\n */\n #findAccountForAddress(address: string): InternalAccount | null {\n const isEvm = address.startsWith('0x');\n\n return (\n this.#getWalletAccounts().find((candidate) =>\n isEvm\n ? candidate.address.toLowerCase() === address.toLowerCase()\n : candidate.address === address,\n ) ?? null\n );\n }\n\n /**\n * Resolve the accounts of the selected account group from the wallet,\n * mirroring `AssetsController.#getSelectedAccounts`.\n *\n * @returns The accounts of the selected account group.\n */\n #getWalletAccounts(): InternalAccount[] {\n const accounts = this.#messenger.call(\n 'AccountTreeController:getAccountsFromSelectedAccountGroup',\n );\n if (accounts.length > 0) {\n return accounts;\n }\n\n const selectedAccount = this.#messenger.call(\n 'AccountsController:getSelectedAccount',\n );\n return selectedAccount ? [selectedAccount] : [];\n }\n\n // ============================================================================\n // STATUS CHANGES\n // ============================================================================\n\n /**\n * Handle a `statusChanged` notification. Chains reported \"up\" are claimed as\n * active (WebSocket provides real-time data); chains reported \"down\" are\n * released so polling data sources take over. The change is applied directly;\n * coalescing and jitter are handled by `AssetsController`.\n *\n * @param options - The status change notification.\n * @param options.chainIds - The CAIP-2 chain IDs whose status changed.\n * @param options.status - Whether the chains are `up` or `down`.\n * @param options.timestamp - Optional timestamp of the status change.\n */\n readonly #onAccountActivityStatusChanged = ({\n chainIds,\n status,\n }: {\n chainIds: string[];\n status: 'up' | 'down';\n timestamp?: number;\n }): void => {\n try {\n // Act on every namespace (eip155, solana, etc.); AssetsController is\n // multichain. Only skip identifiers that are not valid CAIP-2 chain IDs.\n const validChains = chainIds.filter((chainId) => isCaipChainId(chainId));\n\n if (validChains.length === 0) {\n return;\n }\n\n const next = new Set(this.state.activeChains);\n if (status === 'up') {\n for (const chainId of validChains) {\n next.add(chainId);\n }\n } else {\n for (const chainId of validChains) {\n next.delete(chainId);\n }\n }\n\n const previous = [...this.state.activeChains];\n this.updateActiveChains(Array.from(next), (updatedChains) =>\n this.#onActiveChainsUpdated(this.getName(), updatedChains, previous),\n );\n } catch (error) {\n log('Error handling status change', error);\n }\n };\n\n // ============================================================================\n // CLEANUP\n // ============================================================================\n\n destroy(): void {\n try {\n this.#messenger.unsubscribe(\n 'AccountActivityService:balanceUpdated',\n this.#onBalanceUpdatedBound,\n );\n } catch (error) {\n log('Failed to unsubscribe from balanceUpdated', { error });\n }\n\n try {\n this.#messenger.unsubscribe(\n 'AccountActivityService:statusChanged',\n this.#onAccountActivityStatusChanged,\n );\n } catch (error) {\n log('Failed to unsubscribe from statusChanged', { error });\n }\n\n super.destroy();\n }\n}\n\n// ============================================================================\n// FACTORY FUNCTION\n// ============================================================================\n\n/**\n * Creates an AccountActivityDataSource instance.\n *\n * @param options - Configuration options for the data source.\n * @returns A new AccountActivityDataSource instance.\n */\nexport function createAccountActivityDataSource(\n options: AccountActivityDataSourceOptions,\n): AccountActivityDataSource {\n return new AccountActivityDataSource(options);\n}\n"]}
|
|
@@ -2,7 +2,6 @@ import type { SupportedCurrency } from '@metamask/core-backend';
|
|
|
2
2
|
import { ApiPlatformClient } from '@metamask/core-backend';
|
|
3
3
|
import type { Caip19AssetId, DataRequest, DataResponse, FungibleAssetPrice, Middleware, AssetsControllerState } from '../types.js';
|
|
4
4
|
import type { SubscriptionRequest } from './AbstractDataSource.js';
|
|
5
|
-
import type { MarketStatsPriceStreamMessenger } from './MarketStatsPriceStream.js';
|
|
6
5
|
/** Optional configuration for PriceDataSource. */
|
|
7
6
|
export type PriceDataSourceConfig = {
|
|
8
7
|
/** Polling interval in ms (default: 60000) */
|
|
@@ -20,7 +19,6 @@ export type PriceDataSourceConfig = {
|
|
|
20
19
|
*/
|
|
21
20
|
priceFreshnessTtlMs?: number;
|
|
22
21
|
};
|
|
23
|
-
export type { MarketStatsPriceStreamMessenger } from './MarketStatsPriceStream.js';
|
|
24
22
|
export type PriceDataSourceOptions = PriceDataSourceConfig & {
|
|
25
23
|
/** ApiPlatformClient for API calls with caching */
|
|
26
24
|
queryApiClient: ApiPlatformClient;
|
|
@@ -28,12 +26,6 @@ export type PriceDataSourceOptions = PriceDataSourceConfig & {
|
|
|
28
26
|
getSelectedCurrency: () => SupportedCurrency;
|
|
29
27
|
/** Current AssetsController state. Used for balance-based pricing and freshness checks. */
|
|
30
28
|
getAssetsState: () => AssetsControllerState;
|
|
31
|
-
/**
|
|
32
|
-
* Messenger that can call MarketStatsService. When the service is registered,
|
|
33
|
-
* assets with `wssSupport` stream as well as polling. When it is not
|
|
34
|
-
* registered, every asset stays on the poll.
|
|
35
|
-
*/
|
|
36
|
-
messenger: MarketStatsPriceStreamMessenger;
|
|
37
29
|
};
|
|
38
30
|
/**
|
|
39
31
|
* Asset reference patterns that should NOT be sent to the Price API.
|
|
@@ -47,13 +39,8 @@ export { isPriceableAsset } from '../utils/getAssetIdsForPriceFetch.js';
|
|
|
47
39
|
* - Fetches prices from Price API v3 spot-prices endpoint
|
|
48
40
|
* - Supports one-time fetch and subscription-based polling
|
|
49
41
|
* - In subscribe mode, uses constructor `getAssetsState` to read assetsBalance and fetch prices
|
|
50
|
-
* - Streams the same assets the price poll tracks, when the spot-price
|
|
51
|
-
* response marks them `wssSupport: true`, on market-stats.v1. The poll
|
|
52
|
-
* itself is the same as before: every tracked asset, on the same interval.
|
|
53
|
-
* Socket ticks are not written into controller state. The UI reads
|
|
54
|
-
* `MarketStatsService:pricesUpdated`.
|
|
55
42
|
*
|
|
56
|
-
* Usage: Create with queryApiClient
|
|
43
|
+
* Usage: Create with queryApiClient and getAssetsState; subscribe() polls prices for held assets.
|
|
57
44
|
*/
|
|
58
45
|
export declare class PriceDataSource {
|
|
59
46
|
#private;
|
|
@@ -94,31 +81,17 @@ export declare class PriceDataSource {
|
|
|
94
81
|
fetch(request: DataRequest): Promise<DataResponse>;
|
|
95
82
|
/**
|
|
96
83
|
* Subscribe to price updates.
|
|
97
|
-
*
|
|
84
|
+
* Sets up polling that fetches prices for all assets in assetsBalance state.
|
|
98
85
|
*
|
|
99
86
|
* @param subscriptionRequest - The subscription request configuration.
|
|
100
87
|
*/
|
|
101
88
|
subscribe(subscriptionRequest: SubscriptionRequest): Promise<void>;
|
|
102
89
|
/**
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
* @param _subscriptionId - Ignored. The controller passes its subscription key.
|
|
106
|
-
*/
|
|
107
|
-
unsubscribe(_subscriptionId?: string): Promise<void>;
|
|
108
|
-
/**
|
|
109
|
-
* Drop market-stats channels and open them again for the current currency.
|
|
110
|
-
* Called when the selected currency changes so batches match `assetsPrice`.
|
|
111
|
-
*/
|
|
112
|
-
resubscribeForCurrencyChange(): Promise<void>;
|
|
113
|
-
/**
|
|
114
|
-
* Align market-stats channels with the price-fetch set and the `wssSupport`
|
|
115
|
-
* already stored in `assetsPrice`.
|
|
90
|
+
* Unsubscribe from price updates.
|
|
116
91
|
*
|
|
117
|
-
*
|
|
118
|
-
* update reconciles from `AssetsController` once that write has landed.
|
|
119
|
-
* The price poll reconciles at the end of its own tick.
|
|
92
|
+
* @param subscriptionId - The ID of the subscription to cancel.
|
|
120
93
|
*/
|
|
121
|
-
|
|
94
|
+
unsubscribe(subscriptionId: string): Promise<void>;
|
|
122
95
|
/**
|
|
123
96
|
* Invalidate the price freshness cache, forcing the next fetch to call the
|
|
124
97
|
* API regardless of TTL. Use when external state changes (e.g. selected
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PriceDataSource.d.ts","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,iBAAiB,EAElB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAI3D,OAAO,KAAK,EACV,aAAa,EACb,WAAW,EACX,YAAY,EACZ,kBAAkB,EAClB,UAAU,EACV,qBAAqB,EACtB,MAAM,aAAa,CAAC;AASrB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"PriceDataSource.d.ts","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,iBAAiB,EAElB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,i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CAAC,IAAI,CAAC,CA6FvE;IAED;;;;OAIG;IACG,WAAW,CAAC,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAMvD;IAED;;;;OAIG;IACH,oBAAoB,IAAI,IAAI,CAE3B;IAED;;OAEG;IACH,OAAO,IAAI,IAAI,CAMd;CACF"}
|
|
@@ -4,7 +4,6 @@ import { DedupingBatchFetcher } from '../utils/dedupingBatchFetcher.js';
|
|
|
4
4
|
import { filterAssetsBySupportedNetworks, getAssetIdsForPriceFetch, getUnpricedResponseAssetIds, isPriceableAsset, } from '../utils/getAssetIdsForPriceFetch.js';
|
|
5
5
|
import { fetchWithTimeout } from '../utils/index.js';
|
|
6
6
|
import { reduceInBatchesSerially } from './evm-rpc-services/index.js';
|
|
7
|
-
import { MarketStatsPriceStream, readSpotPriceStreamEligibility, } from './MarketStatsPriceStream.js';
|
|
8
7
|
// ============================================================================
|
|
9
8
|
// CONSTANTS
|
|
10
9
|
// ============================================================================
|
|
@@ -75,13 +74,8 @@ function isValidMarketData(data) {
|
|
|
75
74
|
* - Fetches prices from Price API v3 spot-prices endpoint
|
|
76
75
|
* - Supports one-time fetch and subscription-based polling
|
|
77
76
|
* - In subscribe mode, uses constructor `getAssetsState` to read assetsBalance and fetch prices
|
|
78
|
-
* - Streams the same assets the price poll tracks, when the spot-price
|
|
79
|
-
* response marks them `wssSupport: true`, on market-stats.v1. The poll
|
|
80
|
-
* itself is the same as before: every tracked asset, on the same interval.
|
|
81
|
-
* Socket ticks are not written into controller state. The UI reads
|
|
82
|
-
* `MarketStatsService:pricesUpdated`.
|
|
83
77
|
*
|
|
84
|
-
* Usage: Create with queryApiClient
|
|
78
|
+
* Usage: Create with queryApiClient and getAssetsState; subscribe() polls prices for held assets.
|
|
85
79
|
*/
|
|
86
80
|
export class PriceDataSource {
|
|
87
81
|
static controllerName = CONTROLLER_NAME;
|
|
@@ -101,19 +95,14 @@ export class PriceDataSource {
|
|
|
101
95
|
*/
|
|
102
96
|
#deduper;
|
|
103
97
|
#getAssetsState;
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
#subscription = null;
|
|
98
|
+
/** Active subscriptions by ID */
|
|
99
|
+
#activeSubscriptions = new Map();
|
|
107
100
|
constructor(options) {
|
|
108
101
|
this.#getSelectedCurrency = options.getSelectedCurrency;
|
|
109
102
|
this.#pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL;
|
|
110
103
|
this.#apiClient = options.queryApiClient;
|
|
111
104
|
this.#fetchTimeoutMs = options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
|
|
112
105
|
this.#getAssetsState = options.getAssetsState;
|
|
113
|
-
this.#marketStats = new MarketStatsPriceStream({
|
|
114
|
-
messenger: options.messenger,
|
|
115
|
-
getSelectedCurrency: () => this.#getSelectedCurrency(),
|
|
116
|
-
});
|
|
117
106
|
this.#deduper = new DedupingBatchFetcher({
|
|
118
107
|
fetchBatch: (assetIds) => this.#executeBatchFetch(assetIds),
|
|
119
108
|
freshnessTtlMs: options.priceFreshnessTtlMs ?? this.#pollInterval,
|
|
@@ -193,7 +182,6 @@ export class PriceDataSource {
|
|
|
193
182
|
const selectedCurrencyPrices = await fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
|
|
194
183
|
currency: selectedCurrency,
|
|
195
184
|
includeMarketData: true,
|
|
196
|
-
includeWssSupportField: true,
|
|
197
185
|
}), this.#fetchTimeoutMs);
|
|
198
186
|
return { selectedCurrencyPrices, usdPrices: selectedCurrencyPrices };
|
|
199
187
|
}
|
|
@@ -201,12 +189,10 @@ export class PriceDataSource {
|
|
|
201
189
|
fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
|
|
202
190
|
currency: selectedCurrency,
|
|
203
191
|
includeMarketData: true,
|
|
204
|
-
includeWssSupportField: true,
|
|
205
192
|
}), this.#fetchTimeoutMs),
|
|
206
193
|
fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
|
|
207
194
|
currency: 'usd',
|
|
208
195
|
includeMarketData: true,
|
|
209
|
-
includeWssSupportField: true,
|
|
210
196
|
}), this.#fetchTimeoutMs),
|
|
211
197
|
]);
|
|
212
198
|
return { selectedCurrencyPrices, usdPrices };
|
|
@@ -336,18 +322,8 @@ export class PriceDataSource {
|
|
|
336
322
|
* @returns DataResponse containing asset prices.
|
|
337
323
|
*/
|
|
338
324
|
async fetch(request) {
|
|
339
|
-
const assetIds = await this.#filterToSupportedPriceableAssets(this.#getAssetIdsFromBalanceState(request));
|
|
340
|
-
return this.#fetchAssetIdList(assetIds);
|
|
341
|
-
}
|
|
342
|
-
/**
|
|
343
|
-
* Fetch spot prices for an explicit id list. Empty when there is nothing to
|
|
344
|
-
* price or the Price API call fails.
|
|
345
|
-
*
|
|
346
|
-
* @param assetIds - CAIP-19 asset IDs already filtered to priceable assets.
|
|
347
|
-
* @returns DataResponse containing asset prices.
|
|
348
|
-
*/
|
|
349
|
-
async #fetchAssetIdList(assetIds) {
|
|
350
325
|
const response = {};
|
|
326
|
+
const assetIds = await this.#filterToSupportedPriceableAssets(this.#getAssetIdsFromBalanceState(request));
|
|
351
327
|
if (assetIds.length === 0) {
|
|
352
328
|
return response;
|
|
353
329
|
}
|
|
@@ -368,78 +344,99 @@ export class PriceDataSource {
|
|
|
368
344
|
// ============================================================================
|
|
369
345
|
/**
|
|
370
346
|
* Subscribe to price updates.
|
|
371
|
-
*
|
|
347
|
+
* Sets up polling that fetches prices for all assets in assetsBalance state.
|
|
372
348
|
*
|
|
373
349
|
* @param subscriptionRequest - The subscription request configuration.
|
|
374
350
|
*/
|
|
375
351
|
async subscribe(subscriptionRequest) {
|
|
376
|
-
const { request,
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
this.#
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
request,
|
|
401
|
-
onAssetsUpdate,
|
|
402
|
-
};
|
|
403
|
-
}
|
|
404
|
-
await this.#runPoll();
|
|
405
|
-
}
|
|
406
|
-
/**
|
|
407
|
-
* Stop the price poll and release market-stats channels.
|
|
408
|
-
*
|
|
409
|
-
* @param _subscriptionId - Ignored. The controller passes its subscription key.
|
|
410
|
-
*/
|
|
411
|
-
async unsubscribe(_subscriptionId) {
|
|
412
|
-
if (!this.#subscription) {
|
|
413
|
-
return;
|
|
414
|
-
}
|
|
415
|
-
this.#subscription.cleanup();
|
|
416
|
-
this.#subscription = null;
|
|
417
|
-
await this.#marketStats.releaseSubscriptions();
|
|
418
|
-
}
|
|
419
|
-
/**
|
|
420
|
-
* Drop market-stats channels and open them again for the current currency.
|
|
421
|
-
* Called when the selected currency changes so batches match `assetsPrice`.
|
|
422
|
-
*/
|
|
423
|
-
async resubscribeForCurrencyChange() {
|
|
424
|
-
if (!this.#subscription) {
|
|
425
|
-
return;
|
|
352
|
+
const { request, subscriptionId, isUpdate } = subscriptionRequest;
|
|
353
|
+
// Handle subscription update: refresh request and fetch immediately so
|
|
354
|
+
// newly held / still-unpriced assets (e.g. seeded natives) do not wait
|
|
355
|
+
// for the next poll tick. Deduper freshness TTL skips recently priced IDs.
|
|
356
|
+
if (isUpdate) {
|
|
357
|
+
const existing = this.#activeSubscriptions.get(subscriptionId);
|
|
358
|
+
if (existing) {
|
|
359
|
+
existing.request = request;
|
|
360
|
+
existing.onAssetsUpdate = subscriptionRequest.onAssetsUpdate;
|
|
361
|
+
try {
|
|
362
|
+
const fetchResponse = await this.fetch(request);
|
|
363
|
+
if (fetchResponse.assetsPrice &&
|
|
364
|
+
Object.keys(fetchResponse.assetsPrice).length > 0) {
|
|
365
|
+
await existing.onAssetsUpdate({
|
|
366
|
+
...fetchResponse,
|
|
367
|
+
updateMode: 'merge',
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
catch (error) {
|
|
372
|
+
log('Subscription update fetch failed', { subscriptionId, error });
|
|
373
|
+
}
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
426
376
|
}
|
|
427
|
-
|
|
428
|
-
await this
|
|
377
|
+
// Clean up existing subscription
|
|
378
|
+
await this.unsubscribe(subscriptionId);
|
|
379
|
+
const pollInterval = request.updateInterval ?? this.#pollInterval;
|
|
380
|
+
// Cap the freshness TTL strictly below the effective poll interval.
|
|
381
|
+
// `fetchedAt` is stamped when a fetch completes (slightly after the tick
|
|
382
|
+
// that triggered it), so a TTL equal to the poll interval would leave the
|
|
383
|
+
// asset still "fresh" at the next tick, making the subscription re-fetch
|
|
384
|
+
// only every other poll. The margin also absorbs network latency / jitter.
|
|
385
|
+
this.#deduper.freshnessTtlMs = Math.min(this.#deduper.freshnessTtlMs, Math.floor(pollInterval * FRESHNESS_TTL_POLL_RATIO));
|
|
386
|
+
// Create poll function - fetches prices using constructor getAssetsState.
|
|
387
|
+
// The freshness TTL naturally gates re-fetches: assets fetched less than
|
|
388
|
+
// `priceFreshnessTtlMs` ago are skipped, preventing duplicates when middleware
|
|
389
|
+
// or other triggers already fetched the same assets between polls.
|
|
390
|
+
// Concurrent middleware calls will join the inflight promise rather than
|
|
391
|
+
// issuing duplicate requests.
|
|
392
|
+
const pollFn = async () => {
|
|
393
|
+
try {
|
|
394
|
+
const subscription = this.#activeSubscriptions.get(subscriptionId);
|
|
395
|
+
if (!subscription) {
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
const fetchResponse = await this.fetch(subscription.request);
|
|
399
|
+
// Only report if we got prices
|
|
400
|
+
if (fetchResponse.assetsPrice &&
|
|
401
|
+
Object.keys(fetchResponse.assetsPrice).length > 0) {
|
|
402
|
+
await subscription.onAssetsUpdate({
|
|
403
|
+
...fetchResponse,
|
|
404
|
+
// merge overwrites existing spot prices on each poll; update would
|
|
405
|
+
// seed-only and leave the first price forever.
|
|
406
|
+
updateMode: 'merge',
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
catch (error) {
|
|
411
|
+
log('Subscription poll failed', { subscriptionId, error });
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
// Set up polling
|
|
415
|
+
const timer = setInterval(() => {
|
|
416
|
+
pollFn().catch(console.error);
|
|
417
|
+
}, pollInterval);
|
|
418
|
+
// Store subscription
|
|
419
|
+
this.#activeSubscriptions.set(subscriptionId, {
|
|
420
|
+
cleanup: () => {
|
|
421
|
+
clearInterval(timer);
|
|
422
|
+
},
|
|
423
|
+
request,
|
|
424
|
+
onAssetsUpdate: subscriptionRequest.onAssetsUpdate,
|
|
425
|
+
});
|
|
426
|
+
// Initial fetch
|
|
427
|
+
await pollFn();
|
|
429
428
|
}
|
|
430
429
|
/**
|
|
431
|
-
*
|
|
432
|
-
* already stored in `assetsPrice`.
|
|
430
|
+
* Unsubscribe from price updates.
|
|
433
431
|
*
|
|
434
|
-
*
|
|
435
|
-
* update reconciles from `AssetsController` once that write has landed.
|
|
436
|
-
* The price poll reconciles at the end of its own tick.
|
|
432
|
+
* @param subscriptionId - The ID of the subscription to cancel.
|
|
437
433
|
*/
|
|
438
|
-
async
|
|
439
|
-
|
|
440
|
-
|
|
434
|
+
async unsubscribe(subscriptionId) {
|
|
435
|
+
const subscription = this.#activeSubscriptions.get(subscriptionId);
|
|
436
|
+
if (subscription) {
|
|
437
|
+
subscription.cleanup();
|
|
438
|
+
this.#activeSubscriptions.delete(subscriptionId);
|
|
441
439
|
}
|
|
442
|
-
await this.#reconcileMarketStats();
|
|
443
440
|
}
|
|
444
441
|
/**
|
|
445
442
|
* Invalidate the price freshness cache, forcing the next fetch to call the
|
|
@@ -453,50 +450,11 @@ export class PriceDataSource {
|
|
|
453
450
|
* Destroy the data source and clean up all subscriptions.
|
|
454
451
|
*/
|
|
455
452
|
destroy() {
|
|
456
|
-
this.#
|
|
457
|
-
|
|
458
|
-
this.#marketStats.destroy();
|
|
459
|
-
this.#deduper.destroy();
|
|
460
|
-
}
|
|
461
|
-
/**
|
|
462
|
-
* One poll tick: REST-fetch every tracked asset, then open market-stats
|
|
463
|
-
* channels for assets the response marks `wssSupport`.
|
|
464
|
-
*/
|
|
465
|
-
async #runPoll() {
|
|
466
|
-
const subscription = this.#subscription;
|
|
467
|
-
if (!subscription) {
|
|
468
|
-
return;
|
|
469
|
-
}
|
|
470
|
-
try {
|
|
471
|
-
const fetchResponse = await this.fetch(subscription.request);
|
|
472
|
-
if (fetchResponse.assetsPrice &&
|
|
473
|
-
Object.keys(fetchResponse.assetsPrice).length > 0) {
|
|
474
|
-
await subscription.onAssetsUpdate({
|
|
475
|
-
...fetchResponse,
|
|
476
|
-
updateMode: 'merge',
|
|
477
|
-
});
|
|
478
|
-
}
|
|
479
|
-
await this.#reconcileMarketStats();
|
|
480
|
-
}
|
|
481
|
-
catch (error) {
|
|
482
|
-
log('Subscription poll failed', { error });
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
async #reconcileMarketStats() {
|
|
486
|
-
const subscription = this.#subscription;
|
|
487
|
-
if (!subscription) {
|
|
488
|
-
return;
|
|
453
|
+
for (const subscription of this.#activeSubscriptions.values()) {
|
|
454
|
+
subscription.cleanup();
|
|
489
455
|
}
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
}
|
|
493
|
-
#candidatesFor(assetIds) {
|
|
494
|
-
const prices = this.#getAssetsState().assetsPrice ?? {};
|
|
495
|
-
return assetIds.map((assetId) => ({
|
|
496
|
-
assetId,
|
|
497
|
-
wssSupport: prices[assetId] !== undefined &&
|
|
498
|
-
readSpotPriceStreamEligibility(prices[assetId]),
|
|
499
|
-
}));
|
|
456
|
+
this.#activeSubscriptions.clear();
|
|
457
|
+
this.#deduper.destroy();
|
|
500
458
|
}
|
|
501
459
|
}
|
|
502
460
|
//# sourceMappingURL=PriceDataSource.js.map
|