@metamask-previews/assets-controller 20.4.1-preview-c62310f6e → 20.4.1-preview-c552582c8

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 (86) hide show
  1. package/CHANGELOG.md +23 -1
  2. package/README.md +3 -0
  3. package/dist/AssetsController-method-action-types.d.ts +6 -2
  4. package/dist/AssetsController-method-action-types.d.ts.map +1 -1
  5. package/dist/AssetsController-method-action-types.js.map +1 -1
  6. package/dist/AssetsController.d.ts +14 -15
  7. package/dist/AssetsController.d.ts.map +1 -1
  8. package/dist/AssetsController.js +55 -411
  9. package/dist/AssetsController.js.map +1 -1
  10. package/dist/data-sources/AccountActivityDataSource.d.ts +4 -2
  11. package/dist/data-sources/AccountActivityDataSource.d.ts.map +1 -1
  12. package/dist/data-sources/AccountActivityDataSource.js +5 -3
  13. package/dist/data-sources/AccountActivityDataSource.js.map +1 -1
  14. package/dist/data-sources/AccountsApiDataSource.d.ts +3 -26
  15. package/dist/data-sources/AccountsApiDataSource.d.ts.map +1 -1
  16. package/dist/data-sources/AccountsApiDataSource.js +2 -203
  17. package/dist/data-sources/AccountsApiDataSource.js.map +1 -1
  18. package/dist/data-sources/MarketStatsPriceStream.d.ts +67 -0
  19. package/dist/data-sources/MarketStatsPriceStream.d.ts.map +1 -0
  20. package/dist/data-sources/MarketStatsPriceStream.js +181 -0
  21. package/dist/data-sources/MarketStatsPriceStream.js.map +1 -0
  22. package/dist/data-sources/PriceDataSource.d.ts +32 -5
  23. package/dist/data-sources/PriceDataSource.d.ts.map +1 -1
  24. package/dist/data-sources/PriceDataSource.js +133 -91
  25. package/dist/data-sources/PriceDataSource.js.map +1 -1
  26. package/dist/data-sources/RpcDataSource.d.ts +0 -6
  27. package/dist/data-sources/RpcDataSource.d.ts.map +1 -1
  28. package/dist/data-sources/RpcDataSource.js +4 -179
  29. package/dist/data-sources/RpcDataSource.js.map +1 -1
  30. package/dist/data-sources/SnapDataSource.d.ts +0 -2
  31. package/dist/data-sources/SnapDataSource.d.ts.map +1 -1
  32. package/dist/data-sources/SnapDataSource.js +1 -67
  33. package/dist/data-sources/SnapDataSource.js.map +1 -1
  34. package/dist/data-sources/evm-rpc-services/clients/MulticallClient.d.ts.map +1 -1
  35. package/dist/data-sources/evm-rpc-services/clients/MulticallClient.js +0 -1
  36. package/dist/data-sources/evm-rpc-services/clients/MulticallClient.js.map +1 -1
  37. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.d.ts +0 -12
  38. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.d.ts.map +1 -1
  39. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.js +9 -70
  40. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.js.map +1 -1
  41. package/dist/data-sources/index.d.ts +1 -1
  42. package/dist/data-sources/index.d.ts.map +1 -1
  43. package/dist/data-sources/index.js.map +1 -1
  44. package/dist/index.d.ts +6 -4
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +3 -1
  47. package/dist/index.js.map +1 -1
  48. package/dist/middlewares/RpcFallbackMiddleware.d.ts +4 -18
  49. package/dist/middlewares/RpcFallbackMiddleware.d.ts.map +1 -1
  50. package/dist/middlewares/RpcFallbackMiddleware.js +5 -163
  51. package/dist/middlewares/RpcFallbackMiddleware.js.map +1 -1
  52. package/dist/middlewares/index.d.ts +0 -2
  53. package/dist/middlewares/index.d.ts.map +1 -1
  54. package/dist/middlewares/index.js +0 -1
  55. package/dist/middlewares/index.js.map +1 -1
  56. package/dist/pipeline/buildFastFetchSources.d.ts +6 -13
  57. package/dist/pipeline/buildFastFetchSources.d.ts.map +1 -1
  58. package/dist/pipeline/buildFastFetchSources.js +7 -15
  59. package/dist/pipeline/buildFastFetchSources.js.map +1 -1
  60. package/dist/pipeline/buildUpdateSources.d.ts +0 -3
  61. package/dist/pipeline/buildUpdateSources.d.ts.map +1 -1
  62. package/dist/pipeline/buildUpdateSources.js +1 -5
  63. package/dist/pipeline/buildUpdateSources.js.map +1 -1
  64. package/dist/pipeline/buildWsUpdateSources.d.ts +2 -5
  65. package/dist/pipeline/buildWsUpdateSources.d.ts.map +1 -1
  66. package/dist/pipeline/buildWsUpdateSources.js +9 -14
  67. package/dist/pipeline/buildWsUpdateSources.js.map +1 -1
  68. package/dist/store/MarketStatsStore.d.ts +72 -0
  69. package/dist/store/MarketStatsStore.d.ts.map +1 -0
  70. package/dist/store/MarketStatsStore.js +182 -0
  71. package/dist/store/MarketStatsStore.js.map +1 -0
  72. package/dist/types.d.ts +5 -8
  73. package/dist/types.d.ts.map +1 -1
  74. package/dist/types.js.map +1 -1
  75. package/dist/utils/native-assets.d.ts.map +1 -1
  76. package/dist/utils/native-assets.js +0 -1
  77. package/dist/utils/native-assets.js.map +1 -1
  78. package/package.json +3 -3
  79. package/dist/middlewares/CustomAssetGraduationMiddleware.d.ts +0 -34
  80. package/dist/middlewares/CustomAssetGraduationMiddleware.d.ts.map +0 -1
  81. package/dist/middlewares/CustomAssetGraduationMiddleware.js +0 -117
  82. package/dist/middlewares/CustomAssetGraduationMiddleware.js.map +0 -1
  83. package/dist/utils/customAssetsRpcSupplement.d.ts +0 -60
  84. package/dist/utils/customAssetsRpcSupplement.d.ts.map +0 -1
  85. package/dist/utils/customAssetsRpcSupplement.js +0 -68
  86. package/dist/utils/customAssetsRpcSupplement.js.map +0 -1
@@ -49,7 +49,6 @@ import { StakedBalanceDataSource } from './data-sources/StakedBalanceDataSource.
49
49
  import { CaipAssetNamespace, TokenDataSource, } from './data-sources/TokenDataSource.js';
50
50
  import { CHAINS_WITH_DEFAULT_TRACKED_ASSETS, DEFAULT_TRACKED_ASSETS_BY_CHAIN, buildDefaultAssetsInfo, getDefaultAssetMetadata, } from './defaults.js';
51
51
  import { projectLogger, createModuleLogger } from './logger.js';
52
- import { CustomAssetGraduationMiddleware } from './middlewares/CustomAssetGraduationMiddleware.js';
53
52
  import { createParallelBalanceMiddleware, createParallelMiddleware, } from './middlewares/ParallelMiddleware.js';
54
53
  import { RpcFallbackMiddleware } from './middlewares/RpcFallbackMiddleware.js';
55
54
  import { dropBalancesOutsideAccountScopes } from './migrations/dropBalancesOutsideAccountScopes.js';
@@ -59,7 +58,6 @@ import { syncAusUserAssets } from './syncAusUserAssets.js';
59
58
  import { trackAssetsLoading, trackBackgroundAssetsLoading, } from './trackAssetsLoading.js';
60
59
  import { getAssetVisibility } from './utils/assetVisibility.js';
61
60
  import { UNKNOWN_EVM_NATIVE_ASSET_REFERENCE, ZERO_ADDRESS, } from './utils/constants.js';
62
- import { pickRpcCustomAssetsSupplement } from './utils/customAssetsRpcSupplement.js';
63
61
  import { normalizeAmountString, normalizeAssetId, formatExchangeRatesForBridge, formatStateForTransactionPay, buildNativeAssetsFromConstant, buildNativeAssetsFromApi, getDefaultNativeAssetBalance, getZeroAssetBalance, } from './utils/index.js';
64
62
  import { emitTrace, withTrace } from './utils/trace.js';
65
63
  const NATIVE_ASSETS_QUERY_KEY = ['nativeAssets'];
@@ -227,61 +225,18 @@ function normalizeResponse(response) {
227
225
  if (response.updateMode) {
228
226
  normalized.updateMode = response.updateMode;
229
227
  }
230
- if (response.replaceCoveredChainBalances) {
231
- normalized.replaceCoveredChainBalances = true;
232
- }
233
228
  return normalized;
234
229
  }
235
230
  /**
236
- * Compute the effective account balances from a data-source response and prior state.
237
- *
238
- * @param previousBalances - Balances already in state for this account.
239
- * @param accountBalances - Balances from the incoming response.
240
- * @param customAssetIds - Custom assets to preserve when replacing covered chains
241
- * on the Accounts API v5 path (`replaceCoveredChainBalances`).
242
- * @param replaceCoveredChains - When true (v5 force refresh), drop prior balances
243
- * on chains present in the response before applying it, then restore custom assets.
244
- * @returns The effective balance map for the account.
245
- */
246
- function effectiveAccountBalancesV5(previousBalances, accountBalances, customAssetIds, replaceCoveredChains) {
247
- if (!replaceCoveredChains) {
248
- return { ...previousBalances, ...accountBalances };
249
- }
250
- const coveredChains = new Set(Object.keys(accountBalances).map((assetId) => assetId.split('/')[0]));
251
- const next = {};
252
- for (const [assetId, balance] of Object.entries(previousBalances)) {
253
- if (!coveredChains.has(assetId.split('/')[0])) {
254
- next[assetId] = balance;
255
- }
256
- }
257
- Object.assign(next, accountBalances);
258
- for (const customId of customAssetIds) {
259
- if (!Object.prototype.hasOwnProperty.call(next, customId)) {
260
- const prev = previousBalances[customId];
261
- next[customId] = prev ?? getZeroAssetBalance(customId);
262
- }
263
- }
264
- // Staked vault balances are owned by StakedBalanceDataSource. When an
265
- // Accounts API (or other) chain-slice replace omits them, keep the prior
266
- // on-chain staked amount instead of clearing it to missing/0.
267
- for (const [assetId, balance] of Object.entries(previousBalances)) {
268
- if (isStakingContractAssetId(assetId) &&
269
- !Object.prototype.hasOwnProperty.call(next, assetId)) {
270
- next[assetId] = balance;
271
- }
272
- }
273
- return next;
274
- }
275
- /**
276
- * Compute the effective account balances for an Accounts API v6 update.
231
+ * Compute the effective account balances for an update.
277
232
  *
278
233
  * `merge` overlays the incoming balances on prior state (Account Activity,
279
- * Snap events, staking). `full` replaces each covered chain slice. v6 asks
280
- * for natives, pins, and default tracked assets through `includeAssetIds`
281
- * and either returns them (at zero when the account holds none) or names
282
- * them in `unprocessedIncludeAssetIds`. Assets the client tracks on purpose
283
- * survive a `full` replace even when the response omits them, so an upstream
284
- * gap cannot wipe them — see `shouldKeepAsset`.
234
+ * Snap events, staking). `full` replaces each covered chain slice. The client
235
+ * asks for natives, pins, and default tracked assets through
236
+ * `includeAssetIds` and either gets them back (at zero when the account holds
237
+ * none) or sees them in `unprocessedIncludeAssetIds`. Assets the client tracks
238
+ * on purpose survive a `full` replace even when the response omits them, so an
239
+ * upstream gap cannot wipe them — see `shouldKeepAsset`.
285
240
  *
286
241
  * @param previousBalances - Balances already in state for this account.
287
242
  * @param updatedBalances - Balances from the incoming response.
@@ -293,7 +248,7 @@ function effectiveAccountBalancesV5(previousBalances, accountBalances, customAss
293
248
  * each updated chain slice except undeletable and staking assets.
294
249
  * @returns The effective balance map for the account.
295
250
  */
296
- function effectiveAccountBalancesV6(previousBalances, updatedBalances, undeletableAssetIds, updateMode) {
251
+ function resolveAccountBalances(previousBalances, updatedBalances, undeletableAssetIds, updateMode) {
297
252
  if (updateMode === 'merge') {
298
253
  return { ...previousBalances, ...updatedBalances };
299
254
  }
@@ -510,7 +465,6 @@ let AssetsController = (() => {
510
465
  ];
511
466
  }
512
467
  #priceDataSource;
513
- #customAssetGraduationMiddleware;
514
468
  #rpcFallbackMiddleware;
515
469
  #tokenDataSource;
516
470
  #unsubscribeBasicFunctionality = null;
@@ -564,22 +518,18 @@ let AssetsController = (() => {
564
518
  queryApiClient,
565
519
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
566
520
  ...accountsApiDataSourceConfig,
567
- isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
568
- getAssetsState: () => this.state,
569
521
  getAssetVisibility: this.#getAssetVisibility.bind(this),
570
522
  });
571
523
  this.#snapDataSource = new SnapDataSource({
572
524
  messenger: this.messenger,
573
525
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
574
526
  onAssetsUpdate: (response) => this.handleAssetsUpdate(response, 'SnapDataSource'),
575
- isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
576
527
  getAssetVisibility: this.#getAssetVisibility.bind(this),
577
528
  getAssetsState: () => this.state,
578
529
  });
579
530
  this.#rpcDataSource = new RpcDataSource({
580
531
  messenger: this.messenger,
581
532
  getAssetsState: () => this.state,
582
- isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
583
533
  getAssetVisibility: this.#getAssetVisibility.bind(this),
584
534
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
585
535
  getNativeAssetForChain: (chainId) => this.#getNativeAssetForChain(chainId),
@@ -603,26 +553,13 @@ let AssetsController = (() => {
603
553
  });
604
554
  this.#priceDataSource = new PriceDataSource({
605
555
  queryApiClient,
556
+ messenger: this.messenger,
606
557
  getSelectedCurrency: () => this.state.selectedCurrency,
607
558
  getAssetsState: () => this.state,
608
559
  ...priceDataSourceConfig,
609
560
  });
610
- this.#customAssetGraduationMiddleware = new CustomAssetGraduationMiddleware({
611
- getSelectedAccountId: () => {
612
- try {
613
- return this.#getSelectedAccounts()[0]?.id;
614
- }
615
- catch {
616
- return undefined;
617
- }
618
- },
619
- removeCustomAsset: (accountId, assetId) => this.#removeCustomAssetInternal(accountId, assetId),
620
- getAssetsState: () => this.state,
621
- });
622
561
  this.#rpcFallbackMiddleware = new RpcFallbackMiddleware({
623
562
  rpcDataSource: this.#rpcDataSource,
624
- isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
625
- getAssetsState: () => this.state,
626
563
  });
627
564
  log('Initializing AssetsController', {
628
565
  defaultUpdateInterval: this.#defaultUpdateInterval,
@@ -857,9 +794,9 @@ let AssetsController = (() => {
857
794
  });
858
795
  }
859
796
  /**
860
- * One-time cleanup of balances a v5 update stamped onto accounts after a
861
- * group switch. Runs on unlock, the same point as spam cleanup, and only
862
- * touches the selected accounts (their scopes are what define ownership).
797
+ * One-time cleanup of balances written onto accounts outside their scopes
798
+ * after a group switch. Runs on unlock, the same point as spam cleanup, and
799
+ * only touches the selected accounts (their scopes are what define ownership).
863
800
  */
864
801
  #runOutOfScopeBalanceCleanup() {
865
802
  const accounts = this.#getSelectedAccounts();
@@ -1076,7 +1013,7 @@ let AssetsController = (() => {
1076
1013
  });
1077
1014
  }
1078
1015
  /**
1079
- * Run a forced fetch on the v5 or v6 pipeline.
1016
+ * Run a forced fetch.
1080
1017
  *
1081
1018
  * @param params - Accounts, chains, and request fields for this fetch.
1082
1019
  * @param params.accounts - Accounts in this fetch.
@@ -1087,55 +1024,15 @@ let AssetsController = (() => {
1087
1024
  const pipelineTrace = this.#firstInitFetchReported
1088
1025
  ? undefined
1089
1026
  : this.#trace;
1090
- if (this.#isBalanceV6Enabled()) {
1091
- await this.#forceUpdateAssetsV6({
1092
- accounts,
1093
- chainIds,
1094
- request: this.#buildDataRequest(accounts, chainIds, requestOptions),
1095
- pipelineTrace,
1096
- });
1097
- return;
1098
- }
1099
- await this.#forceUpdateAssetsV5({
1100
- accounts,
1101
- chainIds,
1102
- request: this.#buildForceUpdateRequestV5(accounts, chainIds, requestOptions),
1103
- pipelineTrace,
1104
- });
1105
- }
1106
- /**
1107
- * v5 force-update request: every pin of the requested accounts, unscoped.
1108
- * Delete with the rest of the v5 path when `assetsAccountsApiV6` is the default.
1109
- *
1110
- * @param accounts - Accounts in this fetch.
1111
- * @param chainIds - Chains in this fetch.
1112
- * @param requestOptions - Shared force-update request fields.
1113
- * @param requestOptions.assetTypes - Asset types to fetch.
1114
- * @param requestOptions.dataTypes - Data types to fetch.
1115
- * @param requestOptions.forceUpdate - Always `true` to bypass caches.
1116
- * @param requestOptions.bypassServerCache - Also bypass server-side HTTP caches.
1117
- * @returns The v5 data request.
1118
- */
1119
- #buildForceUpdateRequestV5(accounts, chainIds, requestOptions) {
1120
- const customAssets = [];
1121
- for (const account of accounts) {
1122
- customAssets.push(...this.getCustomAssets(account.id));
1123
- }
1124
- return this.#buildDataRequest(accounts, chainIds, {
1125
- ...requestOptions,
1126
- customAssets: customAssets.length > 0 ? customAssets : undefined,
1127
- });
1128
- }
1129
- async #forceUpdateAssetsV5({ accounts, chainIds, request, pipelineTrace, }) {
1130
1027
  const isBasicFunctionality = this.#isBasicFunctionality();
1028
+ const request = this.#buildDataRequest(accounts, chainIds, requestOptions);
1131
1029
  const fastSources = buildFastFetchSources({
1132
1030
  accountsApiDataSource: this.#accountsApiDataSource,
1133
- customAssetGraduationMiddleware: this.#customAssetGraduationMiddleware,
1134
1031
  rpcFallbackMiddleware: this.#rpcFallbackMiddleware,
1135
1032
  tokenDataSource: this.#tokenDataSource,
1136
1033
  priceDataSource: this.#priceDataSource,
1137
- }, { isBasicFunctionality, includeCustomAssetGraduation: true });
1138
- const fastResponse = await this.#runFastFetchV5({
1034
+ }, { isBasicFunctionality });
1035
+ const fastResponse = await this.#runFastFetch({
1139
1036
  accounts,
1140
1037
  chainIds,
1141
1038
  request,
@@ -1152,72 +1049,7 @@ let AssetsController = (() => {
1152
1049
  isBasicFunctionality,
1153
1050
  });
1154
1051
  }
1155
- async #forceUpdateAssetsV6({ accounts, chainIds, request, pipelineTrace, }) {
1156
- const isBasicFunctionality = this.#isBasicFunctionality();
1157
- const fastSources = buildFastFetchSources({
1158
- accountsApiDataSource: this.#accountsApiDataSource,
1159
- customAssetGraduationMiddleware: this.#customAssetGraduationMiddleware,
1160
- rpcFallbackMiddleware: this.#rpcFallbackMiddleware,
1161
- tokenDataSource: this.#tokenDataSource,
1162
- priceDataSource: this.#priceDataSource,
1163
- }, {
1164
- isBasicFunctionality,
1165
- includeCustomAssetGraduation: false,
1166
- });
1167
- const fastResponse = await this.#runFastFetchV6({
1168
- accounts,
1169
- chainIds,
1170
- request,
1171
- pipelineTrace,
1172
- fastSources,
1173
- isBasicFunctionality,
1174
- });
1175
- this.#firstInitFetchReported = true;
1176
- this.#runBackgroundFetch({
1177
- accounts,
1178
- request,
1179
- pipelineTrace,
1180
- chainIds: this.#getSlowPipelineChainIds(chainIds, fastResponse),
1181
- isBasicFunctionality,
1182
- });
1183
- }
1184
- async #runFastFetchV5({ accounts, chainIds, request, pipelineTrace, fastSources, isBasicFunctionality, }) {
1185
- const { response } = await withTrace({
1186
- name: TRACE_FETCH_PIPELINE,
1187
- trace: pipelineTrace,
1188
- data: {
1189
- chain_count: chainIds.length,
1190
- account_count: accounts.length,
1191
- basic_functionality: isBasicFunctionality,
1192
- },
1193
- fn: async (parentContext) => {
1194
- const startTime = performance.now();
1195
- const result = await this.#executeMiddlewares({
1196
- sources: fastSources,
1197
- request,
1198
- parentContext,
1199
- trace: pipelineTrace,
1200
- });
1201
- await this.#updateState({
1202
- ...result.response,
1203
- updateMode: 'merge',
1204
- replaceCoveredChainBalances: true,
1205
- });
1206
- this.#emitFastFetchTraces({
1207
- accounts,
1208
- chainIds,
1209
- result,
1210
- durationMs: performance.now() - startTime,
1211
- isBasicFunctionality,
1212
- parentContext,
1213
- pipelineTrace,
1214
- });
1215
- return result;
1216
- },
1217
- });
1218
- return response;
1219
- }
1220
- async #runFastFetchV6({ accounts, chainIds, request, pipelineTrace, fastSources, isBasicFunctionality, }) {
1052
+ async #runFastFetch({ accounts, chainIds, request, pipelineTrace, fastSources, isBasicFunctionality, }) {
1221
1053
  const { response } = await withTrace({
1222
1054
  name: TRACE_FETCH_PIPELINE,
1223
1055
  trace: pipelineTrace,
@@ -1343,8 +1175,8 @@ let AssetsController = (() => {
1343
1175
  * `fiatValue`) for an account directly from controller state.
1344
1176
  *
1345
1177
  * Reuses the same state-composition and filtering logic as `getAssets`
1346
- * (balance and metadata are required, a missing price falls back to
1347
- * `{ price: 0, lastUpdated: 0 }` with `fiatValue: 0`, and hidden or
1178
+ * (balance and metadata are required, a missing price falls back to a
1179
+ * fungible price of `0` with `fiatValue: 0`, and hidden or
1348
1180
  * otherwise filtered assets are excluded) so the returned shape never
1349
1181
  * drifts from `getAssets`. Reads from current state only and does not
1350
1182
  * trigger a data-source refresh.
@@ -1533,8 +1365,12 @@ let AssetsController = (() => {
1533
1365
  * @param accountId - The account ID to add the custom asset for.
1534
1366
  * @param assetId - The CAIP-19 asset ID to add.
1535
1367
  * @param pendingMetadata - Optional token metadata from the UI (pendingTokens format).
1368
+ * @param bypassServerCache - Also bypass server-side HTTP caches (e.g. the
1369
+ * Accounts API's 60s cache) on the force-fetch, e.g. right after a
1370
+ * transaction that changed this asset's balance. Only applies when
1371
+ * `accountId` belongs to the selected account group.
1536
1372
  */
1537
- async addCustomAsset(accountId, assetId, pendingMetadata) {
1373
+ async addCustomAsset(accountId, assetId, pendingMetadata, bypassServerCache) {
1538
1374
  const normalizedAssetId = normalizeAssetId(assetId);
1539
1375
  log('Adding custom asset', { accountId, assetId: normalizedAssetId });
1540
1376
  this.update((state) => {
@@ -1591,6 +1427,7 @@ let AssetsController = (() => {
1591
1427
  dataTypes: ['balance', 'metadata', 'price'],
1592
1428
  assetTypes: ['fungible'],
1593
1429
  forceUpdate: true,
1430
+ bypassServerCache,
1594
1431
  });
1595
1432
  }
1596
1433
  // Re-evaluate subscriptions so polls pick up the new pin.
@@ -1603,16 +1440,6 @@ let AssetsController = (() => {
1603
1440
  * @param assetId - The CAIP-19 asset ID to remove.
1604
1441
  */
1605
1442
  removeCustomAsset(accountId, assetId) {
1606
- this.#removeCustomAssetInternal(accountId, assetId);
1607
- }
1608
- /**
1609
- * Remove a custom asset without mirroring the removal to AUS (used by
1610
- * auto-graduation, which is not user intent).
1611
- *
1612
- * @param accountId - The account ID to remove the custom asset from.
1613
- * @param assetId - The CAIP-19 asset ID to remove.
1614
- */
1615
- #removeCustomAssetInternal(accountId, assetId) {
1616
1443
  const normalizedAssetId = normalizeAssetId(assetId);
1617
1444
  log('Removing custom asset', { accountId, assetId: normalizedAssetId });
1618
1445
  this.update((state) => {
@@ -1690,24 +1517,6 @@ let AssetsController = (() => {
1690
1517
  }
1691
1518
  this.#subscribeAssets();
1692
1519
  }
1693
- /**
1694
- * Whether Accounts API v6 (and the v6 custom-asset path) is enabled.
1695
- * Injected into AccountsApiDataSource and RpcFallbackMiddleware.
1696
- *
1697
- * `RemoteFeatureFlagController` resolves a threshold-scoped flag to the
1698
- * selected group's `value`, so processed state is a boolean.
1699
- *
1700
- * @returns `true` when the v6 remote flag is on.
1701
- */
1702
- #isBalanceV6Enabled() {
1703
- try {
1704
- const { remoteFeatureFlags } = this.messenger.call('RemoteFeatureFlagController:getState');
1705
- return remoteFeatureFlags?.assetsAccountsApiV6 === true;
1706
- }
1707
- catch {
1708
- return false;
1709
- }
1710
- }
1711
1520
  // ============================================================================
1712
1521
  // CURRENT CURRENCY MANAGEMENT
1713
1522
  // ============================================================================
@@ -1733,6 +1542,9 @@ let AssetsController = (() => {
1733
1542
  }
1734
1543
  // Currency changed — old cached prices are in the wrong currency.
1735
1544
  this.#priceDataSource.invalidatePriceCache();
1545
+ this.#priceDataSource.resubscribeForCurrencyChange().catch((error) => {
1546
+ log('Failed to resubscribe market stats after currency change', error);
1547
+ });
1736
1548
  this.syncAssetsPrices(Object.values(this.state.assetsBalance).flatMap((balances) => Object.keys(balances))).catch((error) => {
1737
1549
  log('Failed to fetch asset prices after current currency change', error);
1738
1550
  });
@@ -1832,7 +1644,7 @@ let AssetsController = (() => {
1832
1644
  });
1833
1645
  }
1834
1646
  /**
1835
- * Lowercased asset IDs a v6 `full` snapshot must keep for an account, even
1647
+ * Lowercased asset IDs a `full` snapshot must keep for an account, even
1836
1648
  * when the response omits them: natives, pins, and default tracked assets
1837
1649
  * the client asked for. Hidden assets are sent as `excludeAssetIds` and are
1838
1650
  * dropped here; unhide is expected to fetch a new snapshot. Everything else
@@ -2050,7 +1862,7 @@ let AssetsController = (() => {
2050
1862
  async #updateState(response) {
2051
1863
  const normalizedResponse = normalizeResponse(response);
2052
1864
  const mode = normalizedResponse.updateMode ?? 'merge';
2053
- const isBalanceV6Enabled = this.#isBalanceV6Enabled();
1865
+ let wroteBalances = false;
2054
1866
  const releaseLock = await this.#controllerMutex.acquire();
2055
1867
  try {
2056
1868
  const previousState = this.state;
@@ -2108,31 +1920,10 @@ let AssetsController = (() => {
2108
1920
  }
2109
1921
  }
2110
1922
  if (normalizedResponse.assetsBalance) {
2111
- const applyV5AccountBalanceUpdate = (accountId, accountBalances, previousBalances) => {
2112
- const customAssetIds = state.customAssets[accountId] ?? [];
2113
- const replaceCoveredChains = mode === 'full' ||
2114
- normalizedResponse.replaceCoveredChainBalances === true;
2115
- const effectiveAccountBalances = effectiveAccountBalancesV5(previousBalances, accountBalances, customAssetIds, replaceCoveredChains);
2116
- // Ensure native tokens have an entry (0 if missing) for chains this account supports
2117
- const account = this.#getSelectedAccounts().find((a) => a.id === accountId);
2118
- const nativeAssetIdsForAccount = account
2119
- ? this.#getNativeAssetIdsForAccount(account)
2120
- : [];
2121
- for (const nativeAssetId of nativeAssetIdsForAccount) {
2122
- if (!Object.prototype.hasOwnProperty.call(effectiveAccountBalances, nativeAssetId)) {
2123
- effectiveAccountBalances[nativeAssetId] =
2124
- getDefaultNativeAssetBalance(nativeAssetId);
2125
- }
2126
- }
1923
+ const applyAccountBalanceUpdate = (accountId, accountBalances, previousBalances) => {
1924
+ const effectiveAccountBalances = resolveAccountBalances(previousBalances, accountBalances, this.#getUndeletableAssetIds(state, accountId, accountBalances), mode);
2127
1925
  for (const [assetId, balance] of Object.entries(effectiveAccountBalances)) {
2128
1926
  const previousBalance = previousBalances[assetId];
2129
- // Coerce amounts (e.g. "1e-18" from a data source stringifying
2130
- // a JS Number) into a plain decimal so downstream BigInt()
2131
- // consumers don't crash. Decimals are read from the freshest
2132
- // merged metadata when available; when metadata is not yet
2133
- // known, the amount is left at its natural precision (only
2134
- // exponent form is rewritten) so balances arriving before
2135
- // their metadata aren't lossily truncated.
2136
1927
  const assetDecimals = metadata[assetId]?.decimals;
2137
1928
  const newAmount = normalizeAmountString(balance.amount, assetDecimals);
2138
1929
  const newMetadata = balance.metadata ??
@@ -2142,40 +1933,7 @@ let AssetsController = (() => {
2142
1933
  ...(newMetadata === undefined ? {} : { metadata: newMetadata }),
2143
1934
  };
2144
1935
  const oldAmount = previousBalance?.amount;
2145
- const isNewSeededZero = oldAmount === undefined &&
2146
- newAmount === '0' &&
2147
- (nativeAssetIdsForAccount.includes(assetId) ||
2148
- getDefaultAssetMetadata(assetId) !==
2149
- undefined);
2150
- if (oldAmount !== newAmount && !isNewSeededZero) {
2151
- changedBalances.push({
2152
- accountId,
2153
- assetId,
2154
- oldAmount,
2155
- newAmount,
2156
- });
2157
- }
2158
- }
2159
- if (!isEqual(previousBalances, effectiveAccountBalances)) {
2160
- balances[accountId] = effectiveAccountBalances;
2161
- }
2162
- };
2163
- // Delete with the rest of the v6 path if `assetsAccountsApiV6` is
2164
- // rolled back; v5 keeps using `applyV5AccountBalanceUpdate`.
2165
- const applyV6AccountBalanceUpdate = (accountId, accountBalances, previousBalances) => {
2166
- const effectiveAccountBalances = effectiveAccountBalancesV6(previousBalances, accountBalances, this.#getUndeletableAssetIds(state, accountId, accountBalances), mode);
2167
- for (const [assetId, balance] of Object.entries(effectiveAccountBalances)) {
2168
- const previousBalance = previousBalances[assetId];
2169
- const assetDecimals = metadata[assetId]?.decimals;
2170
- const newAmount = normalizeAmountString(balance.amount, assetDecimals);
2171
- const newMetadata = balance.metadata ??
2172
- previousBalance?.metadata;
2173
- effectiveAccountBalances[assetId] = {
2174
- amount: newAmount,
2175
- ...(newMetadata === undefined ? {} : { metadata: newMetadata }),
2176
- };
2177
- const oldAmount = previousBalance?.amount;
2178
- // A v6 snapshot reports assets the account holds none of (its
1936
+ // A snapshot reports assets the account holds none of (its
2179
1937
  // `includeAssetIds`) at zero. Publishing those as a change would
2180
1938
  // emit `0 -> 0`, since a missing previous amount reads as '0'.
2181
1939
  const isNewZero = oldAmount === undefined && newAmount === '0';
@@ -2194,12 +1952,7 @@ let AssetsController = (() => {
2194
1952
  };
2195
1953
  for (const [accountId, accountBalances] of Object.entries(normalizedResponse.assetsBalance)) {
2196
1954
  const previousBalances = previousState.assetsBalance[accountId] ?? {};
2197
- if (isBalanceV6Enabled) {
2198
- applyV6AccountBalanceUpdate(accountId, accountBalances, previousBalances);
2199
- }
2200
- else {
2201
- applyV5AccountBalanceUpdate(accountId, accountBalances, previousBalances);
2202
- }
1955
+ applyAccountBalanceUpdate(accountId, accountBalances, previousBalances);
2203
1956
  }
2204
1957
  }
2205
1958
  if (normalizedResponse.assetsPrice) {
@@ -2235,24 +1988,22 @@ let AssetsController = (() => {
2235
1988
  newAmount: change.newAmount,
2236
1989
  });
2237
1990
  }
2238
- // Publish price changed event with full price data
2239
- if (changedPriceAssets.length > 0 && normalizedResponse.assetsPrice) {
2240
- // Build prices object with only changed prices
2241
- const changedPrices = {};
2242
- for (const assetId of changedPriceAssets) {
2243
- const price = normalizedResponse.assetsPrice[assetId];
2244
- if (price) {
2245
- changedPrices[assetId] = price;
2246
- }
2247
- }
2248
- this.messenger.publish('AssetsController:priceChanged', {
2249
- prices: changedPrices,
2250
- });
2251
- }
1991
+ wroteBalances = Boolean(normalizedResponse.assetsBalance);
2252
1992
  }
2253
1993
  finally {
2254
1994
  releaseLock();
2255
1995
  }
1996
+ // Balances and any prices fetched for them are in state now. The price
1997
+ // poll reconciles itself; a price-only write does not reach here.
1998
+ if (wroteBalances) {
1999
+ await this.#priceDataSource
2000
+ .reconcileMarketStreams()
2001
+ .catch((error) => {
2002
+ log('Failed to reconcile market stats after balance update', {
2003
+ error,
2004
+ });
2005
+ });
2006
+ }
2256
2007
  }
2257
2008
  #getAssetsFromState(accounts, chainIds, assetTypes) {
2258
2009
  const result = Object.create(null);
@@ -2321,7 +2072,9 @@ let AssetsController = (() => {
2321
2072
  }
2322
2073
  const priceRaw = this.state.assetsPrice[assetId];
2323
2074
  const price = priceRaw ?? {
2075
+ assetPriceType: 'fungible',
2324
2076
  price: 0,
2077
+ usdPrice: 0,
2325
2078
  lastUpdated: 0,
2326
2079
  };
2327
2080
  // Compute fiat value using BigNumber for precision
@@ -2479,10 +2232,9 @@ let AssetsController = (() => {
2479
2232
  * 2. Map chains to accounts based on their scopes
2480
2233
  * 3. Split by data source (priority order) — each source gets one
2481
2234
  * subscription for the chains it was assigned (accounts + chains only).
2482
- * v6 sources read pins/hides/defaults from state themselves (Accounts API
2483
- * sends `includeAssetIds` / `excludeAssetIds`; RPC polls native, balances,
2484
- * pins, and default tracked assets). v5 uses a separate RPC
2485
- * `customAssetsOnly` supplement for pins on chains another source owns.
2235
+ * Sources read pins, hides, and defaults from state themselves (Accounts
2236
+ * API sends `includeAssetIds` / `excludeAssetIds`; RPC polls native,
2237
+ * balances, pins, and default tracked assets).
2486
2238
  *
2487
2239
  * @param accounts - Accounts to subscribe balance updates for.
2488
2240
  * @param chainIds - Chain IDs to subscribe for.
@@ -2495,7 +2247,6 @@ let AssetsController = (() => {
2495
2247
  const balanceDataSources = this.#isBasicFunctionality()
2496
2248
  ? this.#allBalanceDataSources
2497
2249
  : [this.#rpcDataSource];
2498
- let rpcAssignedChains = new Set();
2499
2250
  for (const source of balanceDataSources) {
2500
2251
  const availableChains = new Set(source.getActiveChainsSync());
2501
2252
  const assignedChains = [];
@@ -2509,9 +2260,6 @@ let AssetsController = (() => {
2509
2260
  this.#unsubscribeDataSource(source);
2510
2261
  continue;
2511
2262
  }
2512
- if (source === this.#rpcDataSource) {
2513
- rpcAssignedChains = new Set(assignedChains);
2514
- }
2515
2263
  const seenIds = new Set();
2516
2264
  const accountsForSource = assignedChains
2517
2265
  .flatMap((chainId) => chainToAccounts.get(chainId) ?? [])
@@ -2531,43 +2279,6 @@ let AssetsController = (() => {
2531
2279
  });
2532
2280
  }
2533
2281
  }
2534
- if (!this.#isBalanceV6Enabled()) {
2535
- this.#subscribeRpcCustomAssetsSupplement(accounts, chainToAccounts, rpcAssignedChains);
2536
- }
2537
- }
2538
- /**
2539
- * Guarantee that customAssets are **always** polled by RPC, even when
2540
- * AccountsApi or another data source has claimed the chain in the
2541
- * regular handoff. RPC is the sole balance fetcher for user-imported
2542
- * tokens on the Accounts API v5 path (see `pickRpcCustomAssetsSupplement`).
2543
- *
2544
- * @param accounts - Accounts to consider for customAssets.
2545
- * @param chainToAccounts - Map of chain → accounts (built by caller).
2546
- * @param rpcAssignedChains - Chains RPC was assigned in the regular handoff.
2547
- */
2548
- #subscribeRpcCustomAssetsSupplement(accounts, chainToAccounts, rpcAssignedChains) {
2549
- const rpc = this.#rpcDataSource;
2550
- const supplementalKey = `ds:${rpc.getName()}:custom`;
2551
- const decision = pickRpcCustomAssetsSupplement({
2552
- accountIds: accounts.map((account) => account.id),
2553
- customAssetsByAccount: this.state.customAssets,
2554
- rpcAssignedChains,
2555
- rpcAvailableChains: new Set(rpc.getActiveChainsSync()),
2556
- enabledChains: new Set(chainToAccounts.keys()),
2557
- });
2558
- if (decision.chains.length === 0) {
2559
- this.#unsubscribeBySubscriptionKey(rpc, supplementalKey);
2560
- return;
2561
- }
2562
- const supplementalAccounts = accounts.filter((account) => decision.accountIds.has(account.id));
2563
- if (supplementalAccounts.length === 0) {
2564
- this.#unsubscribeBySubscriptionKey(rpc, supplementalKey);
2565
- return;
2566
- }
2567
- this.#subscribeDataSource(rpc, supplementalAccounts, decision.chains, {
2568
- subscriptionKey: supplementalKey,
2569
- customAssetsOnly: true,
2570
- });
2571
2282
  }
2572
2283
  /**
2573
2284
  * Unsubscribe a data source by an explicit subscription key.
@@ -2641,8 +2352,6 @@ let AssetsController = (() => {
2641
2352
  * @param chains - Array of chain IDs to subscribe for.
2642
2353
  * @param options - Optional subscription overrides.
2643
2354
  * @param options.subscriptionKey - Custom subscription key (default: `ds:<sourceId>`).
2644
- * @param options.customAssetsOnly - When true, only poll customAssets for these
2645
- * chains (Accounts API v5 supplemental RPC subscription).
2646
2355
  * @param options.skipInitialFetch - When true, skip the data source's subscribe-time fetch.
2647
2356
  */
2648
2357
  #subscribeDataSource(source, accounts, chains, options = {}) {
@@ -2656,7 +2365,6 @@ let AssetsController = (() => {
2656
2365
  isUpdate,
2657
2366
  accountCount: accounts.length,
2658
2367
  chainCount: chains.length,
2659
- customAssetsOnly: options.customAssetsOnly === true,
2660
2368
  skipInitialFetch: options.skipInitialFetch === true,
2661
2369
  });
2662
2370
  const subscribeReq = {
@@ -2664,9 +2372,6 @@ let AssetsController = (() => {
2664
2372
  assetTypes: ['fungible'],
2665
2373
  dataTypes: ['balance'],
2666
2374
  updateInterval: this.#defaultUpdateInterval,
2667
- ...(options.customAssetsOnly === true
2668
- ? { customAssetsOnly: true }
2669
- : {}),
2670
2375
  }),
2671
2376
  subscriptionId: subscriptionKey,
2672
2377
  isUpdate,
@@ -3001,8 +2706,9 @@ let AssetsController = (() => {
3001
2706
  /**
3002
2707
  * Handle assets updated from a data source.
3003
2708
  * Called via the onAssetsUpdate callback passed in SubscriptionRequest when the controller subscribes to a data source.
3004
- * Runs detection, then (when basic functionality is enabled) token metadata and price enrichment before updating state.
3005
- * When basic functionality is disabled (RPC-only mode), only detection runs; token and price APIs are not used.
2709
+ * Runs enrichment, then updates state.
2710
+ * When basic functionality is enabled, token metadata and price enrichment run.
2711
+ * When basic functionality is disabled (RPC-only mode), those APIs are not used.
3006
2712
  *
3007
2713
  * @param response - The data response with updated assets
3008
2714
  * @param sourceId - The data source ID reporting the update
@@ -3014,65 +2720,6 @@ let AssetsController = (() => {
3014
2720
  assetsBalance: response.assetsBalance,
3015
2721
  assetsPrice: response.assetsPrice,
3016
2722
  });
3017
- if (this.#isBalanceV6Enabled()) {
3018
- await this.#handleAssetsUpdateV6(response, sourceId, request);
3019
- return;
3020
- }
3021
- await this.#handleAssetsUpdateV5(response, sourceId, request);
3022
- }
3023
- async #handleAssetsUpdateV5(response, sourceId, request) {
3024
- const pipelineTrace = this.#firstInitFetchReported
3025
- ? undefined
3026
- : this.#trace;
3027
- await withTrace({
3028
- name: TRACE_UPDATE_PARENT,
3029
- trace: pipelineTrace,
3030
- data: this.#getUpdateTraceData(response, sourceId),
3031
- fn: async (parentContext) => {
3032
- const updateStart = performance.now();
3033
- const pipelineRequest = this.#getUpdatePipelineRequest(request);
3034
- const isBasicFunctionality = this.#isBasicFunctionality();
3035
- const isAccountsApiUpdate = sourceId === 'AccountsApiDataSource';
3036
- const enrichmentSources = sourceId === 'AccountActivityDataSource'
3037
- ? buildWsUpdateSources({
3038
- customAssetGraduationMiddleware: this.#customAssetGraduationMiddleware,
3039
- rpcFallbackMiddleware: this.#rpcFallbackMiddleware,
3040
- tokenDataSource: this.#tokenDataSource,
3041
- priceDataSource: this.#priceDataSource,
3042
- }, { isBasicFunctionality, includeCustomAssetGraduation: true })
3043
- : buildUpdateSources({
3044
- customAssetGraduationMiddleware: this.#customAssetGraduationMiddleware,
3045
- rpcFallbackMiddleware: this.#rpcFallbackMiddleware,
3046
- tokenDataSource: this.#tokenDataSource,
3047
- priceDataSource: this.#priceDataSource,
3048
- }, {
3049
- isBasicFunctionality,
3050
- includeCustomAssetGraduation: isAccountsApiUpdate,
3051
- includeRpcFallback: isAccountsApiUpdate,
3052
- });
3053
- const { response: enrichedResponse } = await this.#executeMiddlewares({
3054
- sources: enrichmentSources,
3055
- request: pipelineRequest,
3056
- initialResponse: response,
3057
- parentContext,
3058
- trace: pipelineTrace,
3059
- });
3060
- await this.#updateState({
3061
- ...enrichedResponse,
3062
- replaceCoveredChainBalances: response.replaceCoveredChainBalances,
3063
- });
3064
- this.#emitUpdateTrace({
3065
- response,
3066
- sourceId,
3067
- enrichedResponse,
3068
- updateStart,
3069
- pipelineTrace,
3070
- parentContext,
3071
- });
3072
- },
3073
- });
3074
- }
3075
- async #handleAssetsUpdateV6(response, sourceId, request) {
3076
2723
  const pipelineTrace = this.#firstInitFetchReported
3077
2724
  ? undefined
3078
2725
  : this.#trace;
@@ -3086,19 +2733,16 @@ let AssetsController = (() => {
3086
2733
  const isBasicFunctionality = this.#isBasicFunctionality();
3087
2734
  const enrichmentSources = sourceId === 'AccountActivityDataSource'
3088
2735
  ? buildWsUpdateSources({
3089
- customAssetGraduationMiddleware: this.#customAssetGraduationMiddleware,
3090
2736
  rpcFallbackMiddleware: this.#rpcFallbackMiddleware,
3091
2737
  tokenDataSource: this.#tokenDataSource,
3092
2738
  priceDataSource: this.#priceDataSource,
3093
- }, { isBasicFunctionality, includeCustomAssetGraduation: false })
2739
+ }, { isBasicFunctionality })
3094
2740
  : buildUpdateSources({
3095
- customAssetGraduationMiddleware: this.#customAssetGraduationMiddleware,
3096
2741
  rpcFallbackMiddleware: this.#rpcFallbackMiddleware,
3097
2742
  tokenDataSource: this.#tokenDataSource,
3098
2743
  priceDataSource: this.#priceDataSource,
3099
2744
  }, {
3100
2745
  isBasicFunctionality,
3101
- includeCustomAssetGraduation: false,
3102
2746
  includeRpcFallback: isBasicFunctionality,
3103
2747
  });
3104
2748
  const { response: enrichedResponse } = await this.#executeMiddlewares({