@metamask-previews/assets-controller 20.4.1-preview-e80304db4 → 20.4.1-preview-e92ccc12d

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +0 -11
  2. package/README.md +0 -3
  3. package/dist/AssetsController-method-action-types.d.ts +2 -2
  4. package/dist/AssetsController-method-action-types.js.map +1 -1
  5. package/dist/AssetsController.d.ts +12 -6
  6. package/dist/AssetsController.d.ts.map +1 -1
  7. package/dist/AssetsController.js +18 -11
  8. package/dist/AssetsController.js.map +1 -1
  9. package/dist/data-sources/AccountActivityDataSource.d.ts +2 -4
  10. package/dist/data-sources/AccountActivityDataSource.d.ts.map +1 -1
  11. package/dist/data-sources/AccountActivityDataSource.js +1 -3
  12. package/dist/data-sources/AccountActivityDataSource.js.map +1 -1
  13. package/dist/data-sources/PriceDataSource.d.ts +2 -32
  14. package/dist/data-sources/PriceDataSource.d.ts.map +1 -1
  15. package/dist/data-sources/PriceDataSource.js +37 -164
  16. package/dist/data-sources/PriceDataSource.js.map +1 -1
  17. package/dist/data-sources/index.d.ts +1 -1
  18. package/dist/data-sources/index.d.ts.map +1 -1
  19. package/dist/data-sources/index.js.map +1 -1
  20. package/dist/index.d.ts +2 -4
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +0 -2
  23. package/dist/index.js.map +1 -1
  24. package/dist/types.d.ts +0 -5
  25. package/dist/types.d.ts.map +1 -1
  26. package/dist/types.js.map +1 -1
  27. package/package.json +2 -2
  28. package/dist/data-sources/MarketStatsPriceStream.d.ts +0 -108
  29. package/dist/data-sources/MarketStatsPriceStream.d.ts.map +0 -1
  30. package/dist/data-sources/MarketStatsPriceStream.js +0 -297
  31. package/dist/data-sources/MarketStatsPriceStream.js.map +0 -1
  32. package/dist/store/MarketStatsStore.d.ts +0 -72
  33. package/dist/store/MarketStatsStore.d.ts.map +0 -1
  34. package/dist/store/MarketStatsStore.js +0 -182
  35. 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, SubscriptionRequest } from './AbstractDataSource.js';
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(_request?: SubscriptionRequest): Promise<void>;
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,EACV,eAAe,EACf,mBAAmB,EACpB,MAAM,yBAAyB,CAAC;AAMjC,QAAA,MAAM,eAAe,8BAA8B,CAAC;AAwEpD,mEAAmE;AACnE,MAAM,MAAM,sCAAsC,GAC9C,yCAAyC,GACzC,wCAAwC,CAAC;AAM7C,MAAM,MAAM,8BAA8B,GAAG,eAAe,CAAC;AAU7D,MAAM,MAAM,gCAAgC,GAAG;IAC7C,mEAAmE;IACnE,SAAS,EAAE,yBAAyB,CAAC;IACrC,qGAAqG;IACrG,qBAAqB,EAAE,CACrB,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,OAAO,EAAE,EACjB,cAAc,EAAE,OAAO,EAAE,KACtB,IAAI,CAAC;IACV;;;;;OAKG;IACH,cAAc,EAAE,CACd,QAAQ,EAAE,YAAY,EACtB,OAAO,CAAC,EAAE,WAAW,KAClB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,KAAK,CAAC,EAAE,OAAO,CAAC,8BAA8B,CAAC,CAAC;CACjD,CAAC;AAMF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,qBAAa,yBAA0B,SAAQ,kBAAkB,CAC/D,OAAO,eAAe,EACtB,8BAA8B,CAC/B;;IAoBC,YAAY,OAAO,EAAE,gCAAgC,EAYpD;IAqBD;;;;;;;;;OASG;IACG,SAAS,CAAC,QAAQ,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAE7D;IAuJD,OAAO,IAAI,IAAI,CAoBd;CACF;AAMD;;;;;GAKG;AACH,wBAAgB,+BAA+B,CAC7C,OAAO,EAAE,gCAAgC,GACxC,yBAAyB,CAE3B"}
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,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAM/D,QAAA,MAAM,eAAe,8BAA8B,CAAC;AAwEpD,mEAAmE;AACnE,MAAM,MAAM,sCAAsC,GAC9C,yCAAyC,GACzC,wCAAwC,CAAC;AAM7C,MAAM,MAAM,8BAA8B,GAAG,eAAe,CAAC;AAU7D,MAAM,MAAM,gCAAgC,GAAG;IAC7C,mEAAmE;IACnE,SAAS,EAAE,yBAAyB,CAAC;IACrC,qGAAqG;IACrG,qBAAqB,EAAE,CACrB,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,OAAO,EAAE,EACjB,cAAc,EAAE,OAAO,EAAE,KACtB,IAAI,CAAC;IACV;;;;;OAKG;IACH,cAAc,EAAE,CACd,QAAQ,EAAE,YAAY,EACtB,OAAO,CAAC,EAAE,WAAW,KAClB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,KAAK,CAAC,EAAE,OAAO,CAAC,8BAA8B,CAAC,CAAC;CACjD,CAAC;AAMF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,qBAAa,yBAA0B,SAAQ,kBAAkB,CAC/D,OAAO,eAAe,EACtB,8BAA8B,CAC/B;;IAoBC,YAAY,OAAO,EAAE,gCAAgC,EAYpD;IAqBD;;;;;;;OAOG;IACG,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,CAE/B;IAuJD,OAAO,IAAI,IAAI,CAoBd;CACF;AAMD;;;;;GAKG;AACH,wBAAgB,+BAA+B,CAC7C,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(_request) {
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,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,GAAG,MAAM,CAAC;QAEtC,IAAI,CAAC,KAAK,IAAI,CAAC,WAAW,EAAE,CAAC;YAC3B,SAAS;QACX,CAAC;QAED,uEAAuE;QACvE,uEAAuE;QACvE,yEAAyE;QACzE,wEAAwE;QACxE,MAAM,OAAO,GAAG,oBAAoB,CAAC,KAAK,CAAC,IAAqB,C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,aAAa,EAAE,QAAQ,CAAC,CACrE,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,CAAC,8BAA8B,EAAE,KAAK,CAAC,CAAC;QAC7C,CAAC;IACH,CAAC,CAAC;IAEF,+EAA+E;IAC/E,UAAU;IACV,+EAA+E;IAE/E,OAAO;QACL,IAAI,CAAC;YACH,IAAI,CAAC,UAAU,CAAC,WAAW,CACzB,uCAAuC,EACvC,IAAI,CAAC,sBAAsB,CAC5B,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,CAAC,2CAA2C,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC9D,CAAC;QAED,IAAI,CAAC;YACH,IAAI,CAAC,UAAU,CAAC,WAAW,CACzB,sCAAsC,EACtC,IAAI,CAAC,+BAA+B,CACrC,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,CAAC,0CAA0C,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC7D,CAAC;QAED,KAAK,CAAC,OAAO,EAAE,CAAC;IAClB,CAAC;CACF;AAED,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAC7C,OAAyC;IAEzC,OAAO,IAAI,yBAAyB,CAAC,OAAO,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import type {\n AccountActivityServiceBalanceUpdatedEvent,\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 {\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, custom-asset graduation,\n // occurrence filtering) 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,CAAC,MAAM,CAAC,IAAI,CAG5C,CAAC;IAEF,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,GAAG,MAAM,CAAC;QAEtC,IAAI,CAAC,KAAK,IAAI,CAAC,WAAW,EAAE,CAAC;YAC3B,SAAS;QACX,CAAC;QAED,uEAAuE;QACvE,uEAAuE;QACvE,yEAAyE;QACzE,wEAAwE;QACxE,MAAM,OAA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AI,CAAC,OAAO,EAAE,EAAE,aAAa,EAAE,QAAQ,CAAC,CACrE,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,CAAC,8BAA8B,EAAE,KAAK,CAAC,CAAC;QAC7C,CAAC;IACH,CAAC,CAAC;IAEF,+EAA+E;IAC/E,UAAU;IACV,+EAA+E;IAE/E,OAAO;QACL,IAAI,CAAC;YACH,IAAI,CAAC,UAAU,CAAC,WAAW,CACzB,uCAAuC,EACvC,IAAI,CAAC,sBAAsB,CAC5B,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,CAAC,2CAA2C,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC9D,CAAC;QAED,IAAI,CAAC;YACH,IAAI,CAAC,UAAU,CAAC,WAAW,CACzB,sCAAsC,EACtC,IAAI,CAAC,+BAA+B,CACrC,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,CAAC,0CAA0C,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC7D,CAAC;QAED,KAAK,CAAC,OAAO,EAAE,CAAC;IAClB,CAAC;CACF;AAED,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAC7C,OAAyC;IAEzC,OAAO,IAAI,yBAAyB,CAAC,OAAO,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import type {\n AccountActivityServiceBalanceUpdatedEvent,\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, custom-asset graduation,\n // occurrence filtering) 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 and the rest keep 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,15 +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. Socket ticks
52
- * are not written into controller state. The UI reads
53
- * `MarketStatsService:pricesUpdated`. The poll still writes `assetsPrice`
54
- * for tracked assets that are not streaming. A price for an asset this
55
- * controller does not track is a `MarketStatsService` subscription, not a
56
- * call into this data source.
57
42
  *
58
- * Usage: Create with queryApiClient, messenger, and getAssetsState; subscribe() polls prices for held assets.
43
+ * Usage: Create with queryApiClient and getAssetsState; subscribe() polls prices for held assets.
59
44
  */
60
45
  export declare class PriceDataSource {
61
46
  #private;
@@ -96,7 +81,7 @@ export declare class PriceDataSource {
96
81
  fetch(request: DataRequest): Promise<DataResponse>;
97
82
  /**
98
83
  * Subscribe to price updates.
99
- * Polls the Price API, and streams assets that support market-stats.v1.
84
+ * Sets up polling that fetches prices for all assets in assetsBalance state.
100
85
  *
101
86
  * @param subscriptionRequest - The subscription request configuration.
102
87
  */
@@ -107,21 +92,6 @@ export declare class PriceDataSource {
107
92
  * @param subscriptionId - The ID of the subscription to cancel.
108
93
  */
109
94
  unsubscribe(subscriptionId: string): Promise<void>;
110
- /**
111
- * Drop market-stats channels and open them again for the current currency.
112
- * Called when the selected currency changes so batches match `assetsPrice`.
113
- */
114
- resubscribeForCurrencyChange(): Promise<void>;
115
- /**
116
- * Align market-stats channels with the price-fetch set and the `wssSupport`
117
- * already stored in `assetsPrice`.
118
- *
119
- * The poll calls this after it writes the spot-price response. A balance
120
- * update does not. Stored flags can be from an earlier response, and
121
- * subscribing from them opens channels the latest response marks
122
- * `wssSupport: false`. A new balance waits for the next poll.
123
- */
124
- reconcileMarketStreams(): Promise<void>;
125
95
  /**
126
96
  * Invalidate the price freshness cache, forcing the next fetch to call the
127
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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AE,iBAAiB,CAAC;IAClC,qEAAqE;IACrE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;IAC7C,2FAA2F;IAC3F,cAAc,EAAE,MAAM,qBAAqB,CAAC;CAC7C,CAAC;AAMF;;;GAGG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AA0BxE;;;;;;;;;GASG;AACH,qBAAa,eAAe;;IAC1B,MAAM,CAAC,QAAQ,CAAC,cAAc,qBAAmB;IAEjD,OAAO,IAAI,MAAM,CAEhB;IA+BD,YAAY,OAAO,EAAE,sBAAsB,EAa1C;IAMD;;;;;;;;;;;;;OAaG;IACH,IAAI,gBAAgB,IAAI,UAAU,CA6BjC;IAED;;;;;OAKG;IACG,gBAAgB,CACpB,QAAQ,EAAE,aAAa,EAAE,GACxB,OAAO,CAAC,MAAM,CAAC,aAAa,EAAE,kBAAkB,CAAC,CAAC,CASpD;IA+MD;;;;;;;;OAQG;IACG,KAAK,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,YAAY,CAAC,CAsBvD;IAMD;;;;;OAKG;IACG,SAAS,CAAC,mBAAmB,EAAE,mBAAmB,GAAG,OAAO,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, chainIdFromAssetId, readSpotPriceStreamEligibility, } from './MarketStatsPriceStream.js';
8
7
  // ============================================================================
9
8
  // CONSTANTS
10
9
  // ============================================================================
@@ -75,15 +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. Socket ticks
80
- * are not written into controller state. The UI reads
81
- * `MarketStatsService:pricesUpdated`. The poll still writes `assetsPrice`
82
- * for tracked assets that are not streaming. A price for an asset this
83
- * controller does not track is a `MarketStatsService` subscription, not a
84
- * call into this data source.
85
77
  *
86
- * Usage: Create with queryApiClient, messenger, and getAssetsState; subscribe() polls prices for held assets.
78
+ * Usage: Create with queryApiClient and getAssetsState; subscribe() polls prices for held assets.
87
79
  */
88
80
  export class PriceDataSource {
89
81
  static controllerName = CONTROLLER_NAME;
@@ -103,11 +95,6 @@ export class PriceDataSource {
103
95
  */
104
96
  #deduper;
105
97
  #getAssetsState;
106
- #marketStats;
107
- /** Poll interval of the active subscription, used to size chain-down jitter. */
108
- #effectivePollInterval;
109
- /** Delays the next poll after a chain goes down or comes back. */
110
- #fallbackTimer;
111
98
  /** Active subscriptions by ID */
112
99
  #activeSubscriptions = new Map();
113
100
  constructor(options) {
@@ -116,18 +103,6 @@ export class PriceDataSource {
116
103
  this.#apiClient = options.queryApiClient;
117
104
  this.#fetchTimeoutMs = options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
118
105
  this.#getAssetsState = options.getAssetsState;
119
- this.#effectivePollInterval = this.#pollInterval;
120
- this.#marketStats = new MarketStatsPriceStream({
121
- messenger: options.messenger,
122
- getSelectedCurrency: () => this.#getSelectedCurrency(),
123
- getPollIntervalMs: () => this.#effectivePollInterval,
124
- requestPoll: (delayMs, details) => {
125
- if (details.status === 'down') {
126
- this.#invalidateChains(details.chainIds);
127
- }
128
- this.#scheduleStreamPoll(delayMs);
129
- },
130
- });
131
106
  this.#deduper = new DedupingBatchFetcher({
132
107
  fetchBatch: (assetIds) => this.#executeBatchFetch(assetIds),
133
108
  freshnessTtlMs: options.priceFreshnessTtlMs ?? this.#pollInterval,
@@ -207,7 +182,6 @@ export class PriceDataSource {
207
182
  const selectedCurrencyPrices = await fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
208
183
  currency: selectedCurrency,
209
184
  includeMarketData: true,
210
- includeWssSupportField: true,
211
185
  }), this.#fetchTimeoutMs);
212
186
  return { selectedCurrencyPrices, usdPrices: selectedCurrencyPrices };
213
187
  }
@@ -215,12 +189,10 @@ export class PriceDataSource {
215
189
  fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
216
190
  currency: selectedCurrency,
217
191
  includeMarketData: true,
218
- includeWssSupportField: true,
219
192
  }), this.#fetchTimeoutMs),
220
193
  fetchWithTimeout(() => this.#apiClient.prices.fetchV3SpotPrices(assetIds, {
221
194
  currency: 'usd',
222
195
  includeMarketData: true,
223
- includeWssSupportField: true,
224
196
  }), this.#fetchTimeoutMs),
225
197
  ]);
226
198
  return { selectedCurrencyPrices, usdPrices };
@@ -350,18 +322,8 @@ export class PriceDataSource {
350
322
  * @returns DataResponse containing asset prices.
351
323
  */
352
324
  async fetch(request) {
353
- const assetIds = await this.#filterToSupportedPriceableAssets(this.#getAssetIdsFromBalanceState(request));
354
- return this.#fetchAssetIdList(assetIds);
355
- }
356
- /**
357
- * Fetch spot prices for an explicit id list. Empty when there is nothing to
358
- * price or the Price API call fails.
359
- *
360
- * @param assetIds - CAIP-19 asset IDs already filtered to priceable assets.
361
- * @returns DataResponse containing asset prices.
362
- */
363
- async #fetchAssetIdList(assetIds) {
364
325
  const response = {};
326
+ const assetIds = await this.#filterToSupportedPriceableAssets(this.#getAssetIdsFromBalanceState(request));
365
327
  if (assetIds.length === 0) {
366
328
  return response;
367
329
  }
@@ -382,7 +344,7 @@ export class PriceDataSource {
382
344
  // ============================================================================
383
345
  /**
384
346
  * Subscribe to price updates.
385
- * Polls the Price API, and streams assets that support market-stats.v1.
347
+ * Sets up polling that fetches prices for all assets in assetsBalance state.
386
348
  *
387
349
  * @param subscriptionRequest - The subscription request configuration.
388
350
  */
@@ -405,7 +367,6 @@ export class PriceDataSource {
405
367
  updateMode: 'merge',
406
368
  });
407
369
  }
408
- await this.#reconcileMarketStats();
409
370
  }
410
371
  catch (error) {
411
372
  log('Subscription update fetch failed', { subscriptionId, error });
@@ -416,18 +377,43 @@ export class PriceDataSource {
416
377
  // Clean up existing subscription
417
378
  await this.unsubscribe(subscriptionId);
418
379
  const pollInterval = request.updateInterval ?? this.#pollInterval;
419
- this.#effectivePollInterval = pollInterval;
420
380
  // Cap the freshness TTL strictly below the effective poll interval.
421
381
  // `fetchedAt` is stamped when a fetch completes (slightly after the tick
422
382
  // that triggered it), so a TTL equal to the poll interval would leave the
423
383
  // asset still "fresh" at the next tick, making the subscription re-fetch
424
384
  // only every other poll. The margin also absorbs network latency / jitter.
425
385
  this.#deduper.freshnessTtlMs = Math.min(this.#deduper.freshnessTtlMs, Math.floor(pollInterval * FRESHNESS_TTL_POLL_RATIO));
426
- // Each tick skips assets `getSubscriptions` already has open on a healthy chain.
427
- const timer = setInterval(() => {
428
- this.#runPoll(subscriptionId).catch((error) => {
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) {
429
411
  log('Subscription poll failed', { subscriptionId, error });
430
- });
412
+ }
413
+ };
414
+ // Set up polling
415
+ const timer = setInterval(() => {
416
+ pollFn().catch(console.error);
431
417
  }, pollInterval);
432
418
  // Store subscription
433
419
  this.#activeSubscriptions.set(subscriptionId, {
@@ -438,7 +424,7 @@ export class PriceDataSource {
438
424
  onAssetsUpdate: subscriptionRequest.onAssetsUpdate,
439
425
  });
440
426
  // Initial fetch
441
- await this.#runPoll(subscriptionId);
427
+ await pollFn();
442
428
  }
443
429
  /**
444
430
  * Unsubscribe from price updates.
@@ -447,43 +433,10 @@ export class PriceDataSource {
447
433
  */
448
434
  async unsubscribe(subscriptionId) {
449
435
  const subscription = this.#activeSubscriptions.get(subscriptionId);
450
- if (!subscription) {
451
- return;
452
- }
453
- subscription.cleanup();
454
- this.#activeSubscriptions.delete(subscriptionId);
455
- if (this.#activeSubscriptions.size === 0) {
456
- this.#clearFallbackTimer();
457
- await this.#marketStats.releaseSubscriptions();
458
- return;
459
- }
460
- await this.#reconcileMarketStats();
461
- }
462
- /**
463
- * Drop market-stats channels and open them again for the current currency.
464
- * Called when the selected currency changes so batches match `assetsPrice`.
465
- */
466
- async resubscribeForCurrencyChange() {
467
- if (this.#activeSubscriptions.size === 0) {
468
- return;
469
- }
470
- await this.#marketStats.releaseSubscriptions();
471
- await this.#reconcileMarketStats();
472
- }
473
- /**
474
- * Align market-stats channels with the price-fetch set and the `wssSupport`
475
- * already stored in `assetsPrice`.
476
- *
477
- * The poll calls this after it writes the spot-price response. A balance
478
- * update does not. Stored flags can be from an earlier response, and
479
- * subscribing from them opens channels the latest response marks
480
- * `wssSupport: false`. A new balance waits for the next poll.
481
- */
482
- async reconcileMarketStreams() {
483
- if (this.#activeSubscriptions.size === 0) {
484
- return;
436
+ if (subscription) {
437
+ subscription.cleanup();
438
+ this.#activeSubscriptions.delete(subscriptionId);
485
439
  }
486
- await this.#reconcileMarketStats();
487
440
  }
488
441
  /**
489
442
  * Invalidate the price freshness cache, forcing the next fetch to call the
@@ -501,87 +454,7 @@ export class PriceDataSource {
501
454
  subscription.cleanup();
502
455
  }
503
456
  this.#activeSubscriptions.clear();
504
- this.#clearFallbackTimer();
505
- this.#marketStats.destroy();
506
457
  this.#deduper.destroy();
507
458
  }
508
- /**
509
- * One poll tick: REST-fetch assets that are not streaming, then align the
510
- * market-stats subscription with what the latest spot response can stream.
511
- *
512
- * @param subscriptionId - Active subscription to poll.
513
- */
514
- async #runPoll(subscriptionId) {
515
- const subscription = this.#activeSubscriptions.get(subscriptionId);
516
- if (!subscription) {
517
- return;
518
- }
519
- try {
520
- const assetIds = await this.#filterToSupportedPriceableAssets(this.#getAssetIdsFromBalanceState(subscription.request));
521
- const now = Date.now();
522
- const [subscribed, downChains] = await Promise.all([
523
- this.#marketStats.subscribedAssetIds(),
524
- this.#marketStats.downChainIds(),
525
- ]);
526
- const idsToFetch = assetIds.filter((assetId) => this.#marketStats.shouldPoll(assetId, now, subscribed, downChains));
527
- const fetchResponse = await this.#fetchAssetIdList(idsToFetch);
528
- if (fetchResponse.assetsPrice &&
529
- Object.keys(fetchResponse.assetsPrice).length > 0) {
530
- await subscription.onAssetsUpdate({
531
- ...fetchResponse,
532
- updateMode: 'merge',
533
- });
534
- }
535
- await this.#reconcileMarketStats();
536
- }
537
- catch (error) {
538
- log('Subscription poll failed', { subscriptionId, error });
539
- }
540
- }
541
- async #reconcileMarketStats() {
542
- const assetIds = new Set();
543
- for (const subscription of this.#activeSubscriptions.values()) {
544
- const ids = await this.#filterToSupportedPriceableAssets(this.#getAssetIdsFromBalanceState(subscription.request));
545
- for (const assetId of ids) {
546
- assetIds.add(assetId);
547
- }
548
- }
549
- await this.#marketStats.reconcile(this.#candidatesFor([...assetIds]));
550
- }
551
- #candidatesFor(assetIds) {
552
- const prices = this.#getAssetsState().assetsPrice ?? {};
553
- return assetIds.map((assetId) => ({
554
- assetId,
555
- wssSupport: prices[assetId] !== undefined &&
556
- readSpotPriceStreamEligibility(prices[assetId]),
557
- }));
558
- }
559
- #invalidateChains(chainIds) {
560
- const chains = new Set(chainIds);
561
- const assetIds = Object.keys(this.#getAssetsState().assetsPrice ?? {}).filter((assetId) => {
562
- const chainId = chainIdFromAssetId(assetId);
563
- return chainId !== undefined && chains.has(chainId);
564
- });
565
- if (assetIds.length > 0) {
566
- this.#deduper.invalidateKeys(assetIds);
567
- }
568
- }
569
- #scheduleStreamPoll(delayMs) {
570
- this.#clearFallbackTimer();
571
- this.#fallbackTimer = setTimeout(() => {
572
- this.#fallbackTimer = undefined;
573
- for (const subscriptionId of this.#activeSubscriptions.keys()) {
574
- this.#runPoll(subscriptionId).catch((error) => {
575
- log('Market stats fallback poll failed', { subscriptionId, error });
576
- });
577
- }
578
- }, delayMs);
579
- }
580
- #clearFallbackTimer() {
581
- if (this.#fallbackTimer) {
582
- clearTimeout(this.#fallbackTimer);
583
- this.#fallbackTimer = undefined;
584
- }
585
- }
586
459
  }
587
460
  //# sourceMappingURL=PriceDataSource.js.map