@metamask-previews/assets-controller 20.4.1-preview-70269bbdb → 20.4.1-preview-c62310f6e

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 +1 -23
  2. package/README.md +0 -3
  3. package/dist/AssetsController-method-action-types.d.ts +2 -6
  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 +15 -14
  7. package/dist/AssetsController.d.ts.map +1 -1
  8. package/dist/AssetsController.js +411 -55
  9. package/dist/AssetsController.js.map +1 -1
  10. package/dist/data-sources/AccountActivityDataSource.d.ts +2 -4
  11. package/dist/data-sources/AccountActivityDataSource.d.ts.map +1 -1
  12. package/dist/data-sources/AccountActivityDataSource.js +3 -5
  13. package/dist/data-sources/AccountActivityDataSource.js.map +1 -1
  14. package/dist/data-sources/AccountsApiDataSource.d.ts +26 -3
  15. package/dist/data-sources/AccountsApiDataSource.d.ts.map +1 -1
  16. package/dist/data-sources/AccountsApiDataSource.js +203 -2
  17. package/dist/data-sources/AccountsApiDataSource.js.map +1 -1
  18. package/dist/data-sources/PriceDataSource.d.ts +2 -29
  19. package/dist/data-sources/PriceDataSource.d.ts.map +1 -1
  20. package/dist/data-sources/PriceDataSource.js +37 -113
  21. package/dist/data-sources/PriceDataSource.js.map +1 -1
  22. package/dist/data-sources/RpcDataSource.d.ts +6 -0
  23. package/dist/data-sources/RpcDataSource.d.ts.map +1 -1
  24. package/dist/data-sources/RpcDataSource.js +179 -4
  25. package/dist/data-sources/RpcDataSource.js.map +1 -1
  26. package/dist/data-sources/SnapDataSource.d.ts +2 -0
  27. package/dist/data-sources/SnapDataSource.d.ts.map +1 -1
  28. package/dist/data-sources/SnapDataSource.js +67 -1
  29. package/dist/data-sources/SnapDataSource.js.map +1 -1
  30. package/dist/data-sources/evm-rpc-services/clients/MulticallClient.d.ts.map +1 -1
  31. package/dist/data-sources/evm-rpc-services/clients/MulticallClient.js +1 -0
  32. package/dist/data-sources/evm-rpc-services/clients/MulticallClient.js.map +1 -1
  33. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.d.ts +12 -0
  34. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.d.ts.map +1 -1
  35. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.js +70 -9
  36. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.js.map +1 -1
  37. package/dist/data-sources/index.d.ts +1 -1
  38. package/dist/data-sources/index.d.ts.map +1 -1
  39. package/dist/data-sources/index.js.map +1 -1
  40. package/dist/index.d.ts +4 -6
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +1 -3
  43. package/dist/index.js.map +1 -1
  44. package/dist/middlewares/CustomAssetGraduationMiddleware.d.ts +34 -0
  45. package/dist/middlewares/CustomAssetGraduationMiddleware.d.ts.map +1 -0
  46. package/dist/middlewares/CustomAssetGraduationMiddleware.js +117 -0
  47. package/dist/middlewares/CustomAssetGraduationMiddleware.js.map +1 -0
  48. package/dist/middlewares/RpcFallbackMiddleware.d.ts +18 -4
  49. package/dist/middlewares/RpcFallbackMiddleware.d.ts.map +1 -1
  50. package/dist/middlewares/RpcFallbackMiddleware.js +163 -5
  51. package/dist/middlewares/RpcFallbackMiddleware.js.map +1 -1
  52. package/dist/middlewares/index.d.ts +2 -0
  53. package/dist/middlewares/index.d.ts.map +1 -1
  54. package/dist/middlewares/index.js +1 -0
  55. package/dist/middlewares/index.js.map +1 -1
  56. package/dist/pipeline/buildFastFetchSources.d.ts +13 -6
  57. package/dist/pipeline/buildFastFetchSources.d.ts.map +1 -1
  58. package/dist/pipeline/buildFastFetchSources.js +15 -7
  59. package/dist/pipeline/buildFastFetchSources.js.map +1 -1
  60. package/dist/pipeline/buildUpdateSources.d.ts +3 -0
  61. package/dist/pipeline/buildUpdateSources.d.ts.map +1 -1
  62. package/dist/pipeline/buildUpdateSources.js +5 -1
  63. package/dist/pipeline/buildUpdateSources.js.map +1 -1
  64. package/dist/pipeline/buildWsUpdateSources.d.ts +5 -2
  65. package/dist/pipeline/buildWsUpdateSources.d.ts.map +1 -1
  66. package/dist/pipeline/buildWsUpdateSources.js +14 -9
  67. package/dist/pipeline/buildWsUpdateSources.js.map +1 -1
  68. package/dist/types.d.ts +8 -5
  69. package/dist/types.d.ts.map +1 -1
  70. package/dist/types.js.map +1 -1
  71. package/dist/utils/customAssetsRpcSupplement.d.ts +60 -0
  72. package/dist/utils/customAssetsRpcSupplement.d.ts.map +1 -0
  73. package/dist/utils/customAssetsRpcSupplement.js +68 -0
  74. package/dist/utils/customAssetsRpcSupplement.js.map +1 -0
  75. package/dist/utils/native-assets.d.ts.map +1 -1
  76. package/dist/utils/native-assets.js +1 -0
  77. package/dist/utils/native-assets.js.map +1 -1
  78. package/package.json +3 -3
  79. package/dist/data-sources/MarketStatsPriceStream.d.ts +0 -67
  80. package/dist/data-sources/MarketStatsPriceStream.d.ts.map +0 -1
  81. package/dist/data-sources/MarketStatsPriceStream.js +0 -181
  82. package/dist/data-sources/MarketStatsPriceStream.js.map +0 -1
  83. package/dist/store/MarketStatsStore.d.ts +0 -72
  84. package/dist/store/MarketStatsStore.d.ts.map +0 -1
  85. package/dist/store/MarketStatsStore.js +0 -182
  86. package/dist/store/MarketStatsStore.js.map +0 -1
@@ -49,6 +49,7 @@ 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';
52
53
  import { createParallelBalanceMiddleware, createParallelMiddleware, } from './middlewares/ParallelMiddleware.js';
53
54
  import { RpcFallbackMiddleware } from './middlewares/RpcFallbackMiddleware.js';
54
55
  import { dropBalancesOutsideAccountScopes } from './migrations/dropBalancesOutsideAccountScopes.js';
@@ -58,6 +59,7 @@ import { syncAusUserAssets } from './syncAusUserAssets.js';
58
59
  import { trackAssetsLoading, trackBackgroundAssetsLoading, } from './trackAssetsLoading.js';
59
60
  import { getAssetVisibility } from './utils/assetVisibility.js';
60
61
  import { UNKNOWN_EVM_NATIVE_ASSET_REFERENCE, ZERO_ADDRESS, } from './utils/constants.js';
62
+ import { pickRpcCustomAssetsSupplement } from './utils/customAssetsRpcSupplement.js';
61
63
  import { normalizeAmountString, normalizeAssetId, formatExchangeRatesForBridge, formatStateForTransactionPay, buildNativeAssetsFromConstant, buildNativeAssetsFromApi, getDefaultNativeAssetBalance, getZeroAssetBalance, } from './utils/index.js';
62
64
  import { emitTrace, withTrace } from './utils/trace.js';
63
65
  const NATIVE_ASSETS_QUERY_KEY = ['nativeAssets'];
@@ -225,18 +227,61 @@ function normalizeResponse(response) {
225
227
  if (response.updateMode) {
226
228
  normalized.updateMode = response.updateMode;
227
229
  }
230
+ if (response.replaceCoveredChainBalances) {
231
+ normalized.replaceCoveredChainBalances = true;
232
+ }
228
233
  return normalized;
229
234
  }
230
235
  /**
231
- * Compute the effective account balances for an update.
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.
232
277
  *
233
278
  * `merge` overlays the incoming balances on prior state (Account Activity,
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`.
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`.
240
285
  *
241
286
  * @param previousBalances - Balances already in state for this account.
242
287
  * @param updatedBalances - Balances from the incoming response.
@@ -248,7 +293,7 @@ function normalizeResponse(response) {
248
293
  * each updated chain slice except undeletable and staking assets.
249
294
  * @returns The effective balance map for the account.
250
295
  */
251
- function resolveAccountBalances(previousBalances, updatedBalances, undeletableAssetIds, updateMode) {
296
+ function effectiveAccountBalancesV6(previousBalances, updatedBalances, undeletableAssetIds, updateMode) {
252
297
  if (updateMode === 'merge') {
253
298
  return { ...previousBalances, ...updatedBalances };
254
299
  }
@@ -465,6 +510,7 @@ let AssetsController = (() => {
465
510
  ];
466
511
  }
467
512
  #priceDataSource;
513
+ #customAssetGraduationMiddleware;
468
514
  #rpcFallbackMiddleware;
469
515
  #tokenDataSource;
470
516
  #unsubscribeBasicFunctionality = null;
@@ -518,18 +564,22 @@ let AssetsController = (() => {
518
564
  queryApiClient,
519
565
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
520
566
  ...accountsApiDataSourceConfig,
567
+ isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
568
+ getAssetsState: () => this.state,
521
569
  getAssetVisibility: this.#getAssetVisibility.bind(this),
522
570
  });
523
571
  this.#snapDataSource = new SnapDataSource({
524
572
  messenger: this.messenger,
525
573
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
526
574
  onAssetsUpdate: (response) => this.handleAssetsUpdate(response, 'SnapDataSource'),
575
+ isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
527
576
  getAssetVisibility: this.#getAssetVisibility.bind(this),
528
577
  getAssetsState: () => this.state,
529
578
  });
530
579
  this.#rpcDataSource = new RpcDataSource({
531
580
  messenger: this.messenger,
532
581
  getAssetsState: () => this.state,
582
+ isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
533
583
  getAssetVisibility: this.#getAssetVisibility.bind(this),
534
584
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
535
585
  getNativeAssetForChain: (chainId) => this.#getNativeAssetForChain(chainId),
@@ -553,13 +603,26 @@ let AssetsController = (() => {
553
603
  });
554
604
  this.#priceDataSource = new PriceDataSource({
555
605
  queryApiClient,
556
- messenger: this.messenger,
557
606
  getSelectedCurrency: () => this.state.selectedCurrency,
558
607
  getAssetsState: () => this.state,
559
608
  ...priceDataSourceConfig,
560
609
  });
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
+ });
561
622
  this.#rpcFallbackMiddleware = new RpcFallbackMiddleware({
562
623
  rpcDataSource: this.#rpcDataSource,
624
+ isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
625
+ getAssetsState: () => this.state,
563
626
  });
564
627
  log('Initializing AssetsController', {
565
628
  defaultUpdateInterval: this.#defaultUpdateInterval,
@@ -794,9 +857,9 @@ let AssetsController = (() => {
794
857
  });
795
858
  }
796
859
  /**
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).
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).
800
863
  */
801
864
  #runOutOfScopeBalanceCleanup() {
802
865
  const accounts = this.#getSelectedAccounts();
@@ -1013,7 +1076,7 @@ let AssetsController = (() => {
1013
1076
  });
1014
1077
  }
1015
1078
  /**
1016
- * Run a forced fetch.
1079
+ * Run a forced fetch on the v5 or v6 pipeline.
1017
1080
  *
1018
1081
  * @param params - Accounts, chains, and request fields for this fetch.
1019
1082
  * @param params.accounts - Accounts in this fetch.
@@ -1024,15 +1087,55 @@ let AssetsController = (() => {
1024
1087
  const pipelineTrace = this.#firstInitFetchReported
1025
1088
  ? undefined
1026
1089
  : 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, }) {
1027
1130
  const isBasicFunctionality = this.#isBasicFunctionality();
1028
- const request = this.#buildDataRequest(accounts, chainIds, requestOptions);
1029
1131
  const fastSources = buildFastFetchSources({
1030
1132
  accountsApiDataSource: this.#accountsApiDataSource,
1133
+ customAssetGraduationMiddleware: this.#customAssetGraduationMiddleware,
1031
1134
  rpcFallbackMiddleware: this.#rpcFallbackMiddleware,
1032
1135
  tokenDataSource: this.#tokenDataSource,
1033
1136
  priceDataSource: this.#priceDataSource,
1034
- }, { isBasicFunctionality });
1035
- const fastResponse = await this.#runFastFetch({
1137
+ }, { isBasicFunctionality, includeCustomAssetGraduation: true });
1138
+ const fastResponse = await this.#runFastFetchV5({
1036
1139
  accounts,
1037
1140
  chainIds,
1038
1141
  request,
@@ -1049,7 +1152,72 @@ let AssetsController = (() => {
1049
1152
  isBasicFunctionality,
1050
1153
  });
1051
1154
  }
1052
- async #runFastFetch({ accounts, chainIds, request, pipelineTrace, fastSources, isBasicFunctionality, }) {
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, }) {
1053
1221
  const { response } = await withTrace({
1054
1222
  name: TRACE_FETCH_PIPELINE,
1055
1223
  trace: pipelineTrace,
@@ -1175,8 +1343,8 @@ let AssetsController = (() => {
1175
1343
  * `fiatValue`) for an account directly from controller state.
1176
1344
  *
1177
1345
  * Reuses the same state-composition and filtering logic as `getAssets`
1178
- * (balance and metadata are required, a missing price falls back to a
1179
- * fungible price of `0` with `fiatValue: 0`, and hidden or
1346
+ * (balance and metadata are required, a missing price falls back to
1347
+ * `{ price: 0, lastUpdated: 0 }` with `fiatValue: 0`, and hidden or
1180
1348
  * otherwise filtered assets are excluded) so the returned shape never
1181
1349
  * drifts from `getAssets`. Reads from current state only and does not
1182
1350
  * trigger a data-source refresh.
@@ -1365,12 +1533,8 @@ let AssetsController = (() => {
1365
1533
  * @param accountId - The account ID to add the custom asset for.
1366
1534
  * @param assetId - The CAIP-19 asset ID to add.
1367
1535
  * @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.
1372
1536
  */
1373
- async addCustomAsset(accountId, assetId, pendingMetadata, bypassServerCache) {
1537
+ async addCustomAsset(accountId, assetId, pendingMetadata) {
1374
1538
  const normalizedAssetId = normalizeAssetId(assetId);
1375
1539
  log('Adding custom asset', { accountId, assetId: normalizedAssetId });
1376
1540
  this.update((state) => {
@@ -1427,7 +1591,6 @@ let AssetsController = (() => {
1427
1591
  dataTypes: ['balance', 'metadata', 'price'],
1428
1592
  assetTypes: ['fungible'],
1429
1593
  forceUpdate: true,
1430
- bypassServerCache,
1431
1594
  });
1432
1595
  }
1433
1596
  // Re-evaluate subscriptions so polls pick up the new pin.
@@ -1440,6 +1603,16 @@ let AssetsController = (() => {
1440
1603
  * @param assetId - The CAIP-19 asset ID to remove.
1441
1604
  */
1442
1605
  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) {
1443
1616
  const normalizedAssetId = normalizeAssetId(assetId);
1444
1617
  log('Removing custom asset', { accountId, assetId: normalizedAssetId });
1445
1618
  this.update((state) => {
@@ -1517,6 +1690,24 @@ let AssetsController = (() => {
1517
1690
  }
1518
1691
  this.#subscribeAssets();
1519
1692
  }
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
+ }
1520
1711
  // ============================================================================
1521
1712
  // CURRENT CURRENCY MANAGEMENT
1522
1713
  // ============================================================================
@@ -1542,9 +1733,6 @@ let AssetsController = (() => {
1542
1733
  }
1543
1734
  // Currency changed — old cached prices are in the wrong currency.
1544
1735
  this.#priceDataSource.invalidatePriceCache();
1545
- this.#priceDataSource.resubscribeForCurrencyChange().catch((error) => {
1546
- log('Failed to resubscribe market stats after currency change', error);
1547
- });
1548
1736
  this.syncAssetsPrices(Object.values(this.state.assetsBalance).flatMap((balances) => Object.keys(balances))).catch((error) => {
1549
1737
  log('Failed to fetch asset prices after current currency change', error);
1550
1738
  });
@@ -1644,7 +1832,7 @@ let AssetsController = (() => {
1644
1832
  });
1645
1833
  }
1646
1834
  /**
1647
- * Lowercased asset IDs a `full` snapshot must keep for an account, even
1835
+ * Lowercased asset IDs a v6 `full` snapshot must keep for an account, even
1648
1836
  * when the response omits them: natives, pins, and default tracked assets
1649
1837
  * the client asked for. Hidden assets are sent as `excludeAssetIds` and are
1650
1838
  * dropped here; unhide is expected to fetch a new snapshot. Everything else
@@ -1862,7 +2050,7 @@ let AssetsController = (() => {
1862
2050
  async #updateState(response) {
1863
2051
  const normalizedResponse = normalizeResponse(response);
1864
2052
  const mode = normalizedResponse.updateMode ?? 'merge';
1865
- let wroteBalances = false;
2053
+ const isBalanceV6Enabled = this.#isBalanceV6Enabled();
1866
2054
  const releaseLock = await this.#controllerMutex.acquire();
1867
2055
  try {
1868
2056
  const previousState = this.state;
@@ -1920,10 +2108,31 @@ let AssetsController = (() => {
1920
2108
  }
1921
2109
  }
1922
2110
  if (normalizedResponse.assetsBalance) {
1923
- const applyAccountBalanceUpdate = (accountId, accountBalances, previousBalances) => {
1924
- const effectiveAccountBalances = resolveAccountBalances(previousBalances, accountBalances, this.#getUndeletableAssetIds(state, accountId, accountBalances), mode);
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
+ }
1925
2127
  for (const [assetId, balance] of Object.entries(effectiveAccountBalances)) {
1926
2128
  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.
1927
2136
  const assetDecimals = metadata[assetId]?.decimals;
1928
2137
  const newAmount = normalizeAmountString(balance.amount, assetDecimals);
1929
2138
  const newMetadata = balance.metadata ??
@@ -1933,7 +2142,40 @@ let AssetsController = (() => {
1933
2142
  ...(newMetadata === undefined ? {} : { metadata: newMetadata }),
1934
2143
  };
1935
2144
  const oldAmount = previousBalance?.amount;
1936
- // A snapshot reports assets the account holds none of (its
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
1937
2179
  // `includeAssetIds`) at zero. Publishing those as a change would
1938
2180
  // emit `0 -> 0`, since a missing previous amount reads as '0'.
1939
2181
  const isNewZero = oldAmount === undefined && newAmount === '0';
@@ -1952,7 +2194,12 @@ let AssetsController = (() => {
1952
2194
  };
1953
2195
  for (const [accountId, accountBalances] of Object.entries(normalizedResponse.assetsBalance)) {
1954
2196
  const previousBalances = previousState.assetsBalance[accountId] ?? {};
1955
- applyAccountBalanceUpdate(accountId, accountBalances, previousBalances);
2197
+ if (isBalanceV6Enabled) {
2198
+ applyV6AccountBalanceUpdate(accountId, accountBalances, previousBalances);
2199
+ }
2200
+ else {
2201
+ applyV5AccountBalanceUpdate(accountId, accountBalances, previousBalances);
2202
+ }
1956
2203
  }
1957
2204
  }
1958
2205
  if (normalizedResponse.assetsPrice) {
@@ -1988,22 +2235,24 @@ let AssetsController = (() => {
1988
2235
  newAmount: change.newAmount,
1989
2236
  });
1990
2237
  }
1991
- wroteBalances = Boolean(normalizedResponse.assetsBalance);
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
+ }
1992
2252
  }
1993
2253
  finally {
1994
2254
  releaseLock();
1995
2255
  }
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
- }
2007
2256
  }
2008
2257
  #getAssetsFromState(accounts, chainIds, assetTypes) {
2009
2258
  const result = Object.create(null);
@@ -2072,9 +2321,7 @@ let AssetsController = (() => {
2072
2321
  }
2073
2322
  const priceRaw = this.state.assetsPrice[assetId];
2074
2323
  const price = priceRaw ?? {
2075
- assetPriceType: 'fungible',
2076
2324
  price: 0,
2077
- usdPrice: 0,
2078
2325
  lastUpdated: 0,
2079
2326
  };
2080
2327
  // Compute fiat value using BigNumber for precision
@@ -2232,9 +2479,10 @@ let AssetsController = (() => {
2232
2479
  * 2. Map chains to accounts based on their scopes
2233
2480
  * 3. Split by data source (priority order) — each source gets one
2234
2481
  * subscription for the chains it was assigned (accounts + chains only).
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).
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.
2238
2486
  *
2239
2487
  * @param accounts - Accounts to subscribe balance updates for.
2240
2488
  * @param chainIds - Chain IDs to subscribe for.
@@ -2247,6 +2495,7 @@ let AssetsController = (() => {
2247
2495
  const balanceDataSources = this.#isBasicFunctionality()
2248
2496
  ? this.#allBalanceDataSources
2249
2497
  : [this.#rpcDataSource];
2498
+ let rpcAssignedChains = new Set();
2250
2499
  for (const source of balanceDataSources) {
2251
2500
  const availableChains = new Set(source.getActiveChainsSync());
2252
2501
  const assignedChains = [];
@@ -2260,6 +2509,9 @@ let AssetsController = (() => {
2260
2509
  this.#unsubscribeDataSource(source);
2261
2510
  continue;
2262
2511
  }
2512
+ if (source === this.#rpcDataSource) {
2513
+ rpcAssignedChains = new Set(assignedChains);
2514
+ }
2263
2515
  const seenIds = new Set();
2264
2516
  const accountsForSource = assignedChains
2265
2517
  .flatMap((chainId) => chainToAccounts.get(chainId) ?? [])
@@ -2279,6 +2531,43 @@ let AssetsController = (() => {
2279
2531
  });
2280
2532
  }
2281
2533
  }
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
+ });
2282
2571
  }
2283
2572
  /**
2284
2573
  * Unsubscribe a data source by an explicit subscription key.
@@ -2352,6 +2641,8 @@ let AssetsController = (() => {
2352
2641
  * @param chains - Array of chain IDs to subscribe for.
2353
2642
  * @param options - Optional subscription overrides.
2354
2643
  * @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).
2355
2646
  * @param options.skipInitialFetch - When true, skip the data source's subscribe-time fetch.
2356
2647
  */
2357
2648
  #subscribeDataSource(source, accounts, chains, options = {}) {
@@ -2365,6 +2656,7 @@ let AssetsController = (() => {
2365
2656
  isUpdate,
2366
2657
  accountCount: accounts.length,
2367
2658
  chainCount: chains.length,
2659
+ customAssetsOnly: options.customAssetsOnly === true,
2368
2660
  skipInitialFetch: options.skipInitialFetch === true,
2369
2661
  });
2370
2662
  const subscribeReq = {
@@ -2372,6 +2664,9 @@ let AssetsController = (() => {
2372
2664
  assetTypes: ['fungible'],
2373
2665
  dataTypes: ['balance'],
2374
2666
  updateInterval: this.#defaultUpdateInterval,
2667
+ ...(options.customAssetsOnly === true
2668
+ ? { customAssetsOnly: true }
2669
+ : {}),
2375
2670
  }),
2376
2671
  subscriptionId: subscriptionKey,
2377
2672
  isUpdate,
@@ -2706,9 +3001,8 @@ let AssetsController = (() => {
2706
3001
  /**
2707
3002
  * Handle assets updated from a data source.
2708
3003
  * Called via the onAssetsUpdate callback passed in SubscriptionRequest when the controller subscribes to a data source.
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.
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.
2712
3006
  *
2713
3007
  * @param response - The data response with updated assets
2714
3008
  * @param sourceId - The data source ID reporting the update
@@ -2720,6 +3014,65 @@ let AssetsController = (() => {
2720
3014
  assetsBalance: response.assetsBalance,
2721
3015
  assetsPrice: response.assetsPrice,
2722
3016
  });
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) {
2723
3076
  const pipelineTrace = this.#firstInitFetchReported
2724
3077
  ? undefined
2725
3078
  : this.#trace;
@@ -2733,16 +3086,19 @@ let AssetsController = (() => {
2733
3086
  const isBasicFunctionality = this.#isBasicFunctionality();
2734
3087
  const enrichmentSources = sourceId === 'AccountActivityDataSource'
2735
3088
  ? buildWsUpdateSources({
3089
+ customAssetGraduationMiddleware: this.#customAssetGraduationMiddleware,
2736
3090
  rpcFallbackMiddleware: this.#rpcFallbackMiddleware,
2737
3091
  tokenDataSource: this.#tokenDataSource,
2738
3092
  priceDataSource: this.#priceDataSource,
2739
- }, { isBasicFunctionality })
3093
+ }, { isBasicFunctionality, includeCustomAssetGraduation: false })
2740
3094
  : buildUpdateSources({
3095
+ customAssetGraduationMiddleware: this.#customAssetGraduationMiddleware,
2741
3096
  rpcFallbackMiddleware: this.#rpcFallbackMiddleware,
2742
3097
  tokenDataSource: this.#tokenDataSource,
2743
3098
  priceDataSource: this.#priceDataSource,
2744
3099
  }, {
2745
3100
  isBasicFunctionality,
3101
+ includeCustomAssetGraduation: false,
2746
3102
  includeRpcFallback: isBasicFunctionality,
2747
3103
  });
2748
3104
  const { response: enrichedResponse } = await this.#executeMiddlewares({