@metamask-previews/assets-controller 9.1.0-preview-9298fa429 → 9.1.0-preview-574b60e35

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 (62) hide show
  1. package/CHANGELOG.md +6 -6
  2. package/dist/AssetsController.cjs +130 -150
  3. package/dist/AssetsController.cjs.map +1 -1
  4. package/dist/AssetsController.d.cts +7 -10
  5. package/dist/AssetsController.d.cts.map +1 -1
  6. package/dist/AssetsController.d.mts +7 -10
  7. package/dist/AssetsController.d.mts.map +1 -1
  8. package/dist/AssetsController.mjs +130 -150
  9. package/dist/AssetsController.mjs.map +1 -1
  10. package/dist/data-sources/AccountsApiDataSource.cjs +1 -1
  11. package/dist/data-sources/AccountsApiDataSource.cjs.map +1 -1
  12. package/dist/data-sources/AccountsApiDataSource.mjs +1 -1
  13. package/dist/data-sources/AccountsApiDataSource.mjs.map +1 -1
  14. package/dist/data-sources/BackendWebsocketDataSource.cjs +60 -26
  15. package/dist/data-sources/BackendWebsocketDataSource.cjs.map +1 -1
  16. package/dist/data-sources/BackendWebsocketDataSource.d.cts.map +1 -1
  17. package/dist/data-sources/BackendWebsocketDataSource.d.mts.map +1 -1
  18. package/dist/data-sources/BackendWebsocketDataSource.mjs +57 -26
  19. package/dist/data-sources/BackendWebsocketDataSource.mjs.map +1 -1
  20. package/dist/data-sources/PriceDataSource.cjs +0 -2
  21. package/dist/data-sources/PriceDataSource.cjs.map +1 -1
  22. package/dist/data-sources/PriceDataSource.d.cts.map +1 -1
  23. package/dist/data-sources/PriceDataSource.d.mts.map +1 -1
  24. package/dist/data-sources/PriceDataSource.mjs +0 -2
  25. package/dist/data-sources/PriceDataSource.mjs.map +1 -1
  26. package/dist/data-sources/RpcDataSource.cjs +2 -3
  27. package/dist/data-sources/RpcDataSource.cjs.map +1 -1
  28. package/dist/data-sources/RpcDataSource.d.cts.map +1 -1
  29. package/dist/data-sources/RpcDataSource.d.mts.map +1 -1
  30. package/dist/data-sources/RpcDataSource.mjs +2 -3
  31. package/dist/data-sources/RpcDataSource.mjs.map +1 -1
  32. package/dist/data-sources/SnapDataSource.cjs +3 -3
  33. package/dist/data-sources/SnapDataSource.cjs.map +1 -1
  34. package/dist/data-sources/SnapDataSource.mjs +3 -3
  35. package/dist/data-sources/SnapDataSource.mjs.map +1 -1
  36. package/dist/middlewares/ParallelMiddleware.cjs +0 -9
  37. package/dist/middlewares/ParallelMiddleware.cjs.map +1 -1
  38. package/dist/middlewares/ParallelMiddleware.d.cts.map +1 -1
  39. package/dist/middlewares/ParallelMiddleware.d.mts.map +1 -1
  40. package/dist/middlewares/ParallelMiddleware.mjs +0 -9
  41. package/dist/middlewares/ParallelMiddleware.mjs.map +1 -1
  42. package/dist/selectors/balance.cjs +5 -1
  43. package/dist/selectors/balance.cjs.map +1 -1
  44. package/dist/selectors/balance.d.cts.map +1 -1
  45. package/dist/selectors/balance.d.mts.map +1 -1
  46. package/dist/selectors/balance.mjs +5 -1
  47. package/dist/selectors/balance.mjs.map +1 -1
  48. package/dist/types.cjs.map +1 -1
  49. package/dist/types.d.cts +10 -8
  50. package/dist/types.d.cts.map +1 -1
  51. package/dist/types.d.mts +10 -8
  52. package/dist/types.d.mts.map +1 -1
  53. package/dist/types.mjs.map +1 -1
  54. package/package.json +1 -1
  55. package/dist/utils/processAccountActivityBalanceUpdates.cjs +0 -54
  56. package/dist/utils/processAccountActivityBalanceUpdates.cjs.map +0 -1
  57. package/dist/utils/processAccountActivityBalanceUpdates.d.cts +0 -13
  58. package/dist/utils/processAccountActivityBalanceUpdates.d.cts.map +0 -1
  59. package/dist/utils/processAccountActivityBalanceUpdates.d.mts +0 -13
  60. package/dist/utils/processAccountActivityBalanceUpdates.d.mts.map +0 -1
  61. package/dist/utils/processAccountActivityBalanceUpdates.mjs +0 -47
  62. package/dist/utils/processAccountActivityBalanceUpdates.mjs.map +0 -1
@@ -9,7 +9,7 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
10
10
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
11
11
  };
12
- var _AssetsController_instances, _AssetsController_isEnabled, _AssetsController_isBasicFunctionality, _AssetsController_defaultUpdateInterval, _AssetsController_trace, _AssetsController_captureException, _AssetsController_firstInitFetchReported, _AssetsController_stateSizeReported, _AssetsController_emitTrace, _AssetsController_emitStateSizeTrace, _AssetsController_uiOpen, _AssetsController_keyringUnlocked, _AssetsController_controllerMutex, _AssetsController_accountRefreshMutex, _AssetsController_activeSubscriptions, _AssetsController_enabledChains, _AssetsController_lastKnownAccountIds, _AssetsController_getSelectedAccounts, _AssetsController_backendWebsocketDataSource, _AssetsController_accountsApiDataSource, _AssetsController_snapDataSource, _AssetsController_rpcDataSource, _AssetsController_stakedBalanceDataSource, _AssetsController_allBalanceDataSources_get, _AssetsController_priceDataSource, _AssetsController_detectionMiddleware, _AssetsController_customAssetGraduationMiddleware, _AssetsController_rpcFallbackMiddleware, _AssetsController_tokenDataSource, _AssetsController_unsubscribeBasicFunctionality, _AssetsController_queryApiClient, _AssetsController_onActiveChainsUpdated, _AssetsController_initializeNativeAssetsMap, _AssetsController_initializeState, _AssetsController_extractEnabledChains, _AssetsController_normalizeChainReference, _AssetsController_subscribeToEvents, _AssetsController_onUnapprovedTransactionAdded, _AssetsController_onAccountActivityBalanceUpdated, _AssetsController_updateActive, _AssetsController_handleAccountTreeStateChange, _AssetsController_runAccountTreeRefresh, _AssetsController_registerActionHandlers, _AssetsController_handleActiveChainsUpdate, _AssetsController_executeMiddlewares, _AssetsController_getNativeAssetMap, _AssetsController_isNativeAsset, _AssetsController_getAssetType, _AssetsController_resolveNativeAssetIds, _AssetsController_getNativeAssetIdsForEnabledChains, _AssetsController_getNativeAssetIdsForAccount, _AssetsController_getSlowPipelineChainIds, _AssetsController_ensureNativeBalancesDefaultZero, _AssetsController_ensureDefaultTrackedAssetsSeeded, _AssetsController_updateState, _AssetsController_getAssetsFromState, _AssetsController_shouldHideNativeToken, _AssetsController_tokenStandardToAssetType, _AssetsController_start, _AssetsController_stop, _AssetsController_subscribeAssets, _AssetsController_subscribeAssetsBalance, _AssetsController_subscribeRpcCustomAssetsSupplement, _AssetsController_unsubscribeBySubscriptionKey, _AssetsController_subscribeStakedBalance, _AssetsController_buildChainToAccountsMap, _AssetsController_subscribeDataSource, _AssetsController_unsubscribeDataSource, _AssetsController_buildDataRequest, _AssetsController_getEnabledChainsForAccount, _AssetsController_handleAccountGroupChanged, _AssetsController_handleEnabledNetworksChanged, _AssetsController_handleNetworkAdded, _AssetsController_refreshAssetsAfterNetworkChange;
12
+ var _AssetsController_instances, _AssetsController_isEnabled, _AssetsController_isBasicFunctionality, _AssetsController_defaultUpdateInterval, _AssetsController_trace, _AssetsController_captureException, _AssetsController_firstInitFetchReported, _AssetsController_stateSizeReported, _AssetsController_emitTrace, _AssetsController_emitStateSizeTrace, _AssetsController_uiOpen, _AssetsController_keyringUnlocked, _AssetsController_controllerMutex, _AssetsController_accountRefreshMutex, _AssetsController_activeSubscriptions, _AssetsController_enabledChains, _AssetsController_lastKnownAccountIds, _AssetsController_wsBalanceFreshUntil, _AssetsController_getSelectedAccounts, _AssetsController_backendWebsocketDataSource, _AssetsController_accountsApiDataSource, _AssetsController_snapDataSource, _AssetsController_rpcDataSource, _AssetsController_stakedBalanceDataSource, _AssetsController_allBalanceDataSources_get, _AssetsController_priceDataSource, _AssetsController_detectionMiddleware, _AssetsController_customAssetGraduationMiddleware, _AssetsController_rpcFallbackMiddleware, _AssetsController_tokenDataSource, _AssetsController_unsubscribeBasicFunctionality, _AssetsController_queryApiClient, _AssetsController_onActiveChainsUpdated, _AssetsController_initializeNativeAssetsMap, _AssetsController_initializeState, _AssetsController_extractEnabledChains, _AssetsController_normalizeChainReference, _AssetsController_subscribeToEvents, _AssetsController_onUnapprovedTransactionAdded, _AssetsController_updateActive, _AssetsController_handleAccountTreeStateChange, _AssetsController_runAccountTreeRefresh, _AssetsController_registerActionHandlers, _AssetsController_handleActiveChainsUpdate, _AssetsController_executeMiddlewares, _AssetsController_getNativeAssetMap, _AssetsController_isNativeAsset, _AssetsController_getAssetType, _AssetsController_resolveNativeAssetIds, _AssetsController_getNativeAssetIdsForEnabledChains, _AssetsController_getNativeAssetIdsForAccount, _AssetsController_ensureNativeBalancesDefaultZero, _AssetsController_ensureDefaultTrackedAssetsSeeded, _AssetsController_filterBalancesRespectingWsFreshness, _AssetsController_markWsBalancesFresh, _AssetsController_clearWsBalanceFreshness, _AssetsController_updateState, _AssetsController_getAssetsFromState, _AssetsController_shouldHideNativeToken, _AssetsController_tokenStandardToAssetType, _AssetsController_start, _AssetsController_stop, _AssetsController_subscribeAssets, _AssetsController_subscribeAssetsBalance, _AssetsController_subscribeRpcCustomAssetsSupplement, _AssetsController_unsubscribeBySubscriptionKey, _AssetsController_subscribeStakedBalance, _AssetsController_buildChainToAccountsMap, _AssetsController_subscribeDataSource, _AssetsController_unsubscribeDataSource, _AssetsController_buildDataRequest, _AssetsController_getEnabledChainsForAccount, _AssetsController_handleAccountGroupChanged, _AssetsController_handleEnabledNetworksChanged, _AssetsController_handleNetworkAdded, _AssetsController_refreshAssetsAfterNetworkChange;
13
13
  import { BaseController } from "@metamask/base-controller";
14
14
  import { clientControllerSelectors } from "@metamask/client-controller";
15
15
  import { isCaipChainId, isStrictHexString, KnownCaipNamespace, parseCaipAssetType, parseCaipChainId } from "@metamask/utils";
@@ -35,7 +35,6 @@ import { RpcFallbackMiddleware } from "./middlewares/RpcFallbackMiddleware.mjs";
35
35
  import { normalizeAmountString, normalizeAssetId, formatExchangeRatesForBridge, formatStateForTransactionPay, buildNativeAssetsFromConstant, buildNativeAssetsFromApi } from "./utils/index.mjs";
36
36
  import { ZERO_ADDRESS } from "./utils/constants.mjs";
37
37
  import { pickRpcCustomAssetsSupplement } from "./utils/customAssetsRpcSupplement.mjs";
38
- import { processAccountActivityBalanceUpdates } from "./utils/processAccountActivityBalanceUpdates.mjs";
39
38
  const NATIVE_ASSETS_QUERY_KEY = ['nativeAssets'];
40
39
  // ============================================================================
41
40
  // CONTROLLER CONSTANTS
@@ -58,6 +57,15 @@ const MESSENGER_EXPOSED_METHODS = [
58
57
  ];
59
58
  /** Default polling interval hint for data sources (30 seconds) */
60
59
  const DEFAULT_POLLING_INTERVAL_MS = 30000;
60
+ /** Sources whose passive polling must not overwrite recent websocket balances. */
61
+ const POLLING_BALANCE_SOURCES = new Set([
62
+ 'AccountsApiDataSource',
63
+ 'RpcDataSource',
64
+ 'SnapDataSource',
65
+ 'StakedBalanceDataSource',
66
+ ]);
67
+ /** How long websocket balance updates block stale polling overwrites. */
68
+ const WS_BALANCE_FRESHNESS_MS = 120000;
61
69
  // ============================================================================
62
70
  // TRACE NAMES — used in Sentry spans (search these strings in Discover)
63
71
  // ============================================================================
@@ -187,6 +195,9 @@ function normalizeResponse(response) {
187
195
  if (response.updateMode) {
188
196
  normalized.updateMode = response.updateMode;
189
197
  }
198
+ if (response.sourceId) {
199
+ normalized.sourceId = response.sourceId;
200
+ }
190
201
  return normalized;
191
202
  }
192
203
  // ============================================================================
@@ -267,6 +278,11 @@ export class AssetsController extends BaseController {
267
278
  * re-subscriptions when the account set hasn't actually changed.
268
279
  */
269
280
  _AssetsController_lastKnownAccountIds.set(this, new Set());
281
+ /**
282
+ * Per `accountId:assetId`, timestamp until which websocket balance updates
283
+ * should not be overwritten by polling/API fetches.
284
+ */
285
+ _AssetsController_wsBalanceFreshUntil.set(this, new Map());
270
286
  _AssetsController_backendWebsocketDataSource.set(this, void 0);
271
287
  _AssetsController_accountsApiDataSource.set(this, void 0);
272
288
  _AssetsController_snapDataSource.set(this, void 0);
@@ -415,9 +431,9 @@ export class AssetsController extends BaseController {
415
431
  // creation, RPC is slow on many chains). Results are committed to state
416
432
  // immediately so the UI can display balances without waiting for them.
417
433
  //
418
- // Fast/slow pipelines use 'update' so partial API snapshots cannot wipe
419
- // tokens missing from the response (e.g. USDC when only native balance
420
- // is returned). Balances present in the response are still refreshed.
434
+ // Both the fast and background pipelines use 'merge' mode because neither
435
+ // alone represents the full set of data sources. Using 'full' in either
436
+ // would wipe balances from the sources handled by the other pipeline.
421
437
  const fastSources = __classPrivateFieldGet(this, _AssetsController_isBasicFunctionality, "f").call(this)
422
438
  ? [
423
439
  createParallelBalanceMiddleware([
@@ -437,32 +453,39 @@ export class AssetsController extends BaseController {
437
453
  ]
438
454
  : [__classPrivateFieldGet(this, _AssetsController_stakedBalanceDataSource, "f"), __classPrivateFieldGet(this, _AssetsController_detectionMiddleware, "f")];
439
455
  const { response, durationByDataSource } = await __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_executeMiddlewares).call(this, fastSources, request);
440
- await __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_updateState).call(this, { ...response, updateMode: 'update' });
456
+ // The fast pipeline only contains a subset of data sources (AccountsApi +
457
+ // StakedBalance), so it must always merge to avoid wiping Snap/RPC
458
+ // balances that the background pipeline hasn't yet replaced.
459
+ await __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_updateState).call(this, {
460
+ ...response,
461
+ updateMode: 'merge',
462
+ sourceId: 'getAssets:forceUpdate',
463
+ });
441
464
  // Background pipeline: snap and RPC run in parallel after the fast path
442
465
  // commits to state. Their balances are merged together before detection.
443
466
  // Token + price enrichment matches the pre-split behavior: only when basic
444
467
  // functionality is on (RPC-only mode must not call token/price APIs).
445
- const slowPipelineChainIds = __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_getSlowPipelineChainIds).call(this, chainIds, response);
446
- if (slowPipelineChainIds.length > 0) {
447
- const slowSources = __classPrivateFieldGet(this, _AssetsController_isBasicFunctionality, "f").call(this)
448
- ? [__classPrivateFieldGet(this, _AssetsController_snapDataSource, "f"), __classPrivateFieldGet(this, _AssetsController_rpcDataSource, "f")]
449
- : [__classPrivateFieldGet(this, _AssetsController_rpcDataSource, "f")];
450
- const slowRequest = { ...request, chainIds: slowPipelineChainIds };
451
- __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_executeMiddlewares).call(this, [
452
- createParallelBalanceMiddleware(slowSources),
453
- __classPrivateFieldGet(this, _AssetsController_detectionMiddleware, "f"),
454
- ...(__classPrivateFieldGet(this, _AssetsController_isBasicFunctionality, "f").call(this)
455
- ? [
456
- createParallelMiddleware([
457
- __classPrivateFieldGet(this, _AssetsController_tokenDataSource, "f"),
458
- __classPrivateFieldGet(this, _AssetsController_priceDataSource, "f"),
459
- ]),
460
- ]
461
- : []),
462
- ], slowRequest)
463
- .then(({ response: slowResponse }) => __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_updateState).call(this, { ...slowResponse, updateMode: 'update' }))
464
- .catch((error) => log('Background pipeline failed', { error }));
465
- }
468
+ const slowSources = __classPrivateFieldGet(this, _AssetsController_isBasicFunctionality, "f").call(this)
469
+ ? [__classPrivateFieldGet(this, _AssetsController_snapDataSource, "f"), __classPrivateFieldGet(this, _AssetsController_rpcDataSource, "f")]
470
+ : [__classPrivateFieldGet(this, _AssetsController_rpcDataSource, "f")];
471
+ __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_executeMiddlewares).call(this, [
472
+ createParallelBalanceMiddleware(slowSources),
473
+ __classPrivateFieldGet(this, _AssetsController_detectionMiddleware, "f"),
474
+ ...(__classPrivateFieldGet(this, _AssetsController_isBasicFunctionality, "f").call(this)
475
+ ? [
476
+ createParallelMiddleware([
477
+ __classPrivateFieldGet(this, _AssetsController_tokenDataSource, "f"),
478
+ __classPrivateFieldGet(this, _AssetsController_priceDataSource, "f"),
479
+ ]),
480
+ ]
481
+ : []),
482
+ ], request)
483
+ .then(({ response: slowResponse }) => __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_updateState).call(this, {
484
+ ...slowResponse,
485
+ updateMode: 'merge',
486
+ sourceId: 'getAssets:forceUpdate',
487
+ }))
488
+ .catch((error) => log('Background pipeline failed', { error }));
466
489
  const durationMs = performance.now() - startTime;
467
490
  // Emit trace for every full fetch (Assets Health dashboard)
468
491
  __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_emitTrace).call(this, TRACE_FULL_FETCH, {
@@ -854,8 +877,7 @@ export class AssetsController extends BaseController {
854
877
  // RPC already fetches custom assets on purpose, and Snap handles non-EVM
855
878
  // chains the rule does not apply to, so skip the middleware for those.
856
879
  const shouldGraduateCustomAssets = sourceId === 'AccountsApiDataSource' ||
857
- sourceId === 'BackendWebsocketDataSource' ||
858
- sourceId === 'AccountActivityService';
880
+ sourceId === 'BackendWebsocketDataSource';
859
881
  const enrichmentSources = [
860
882
  ...(shouldGraduateCustomAssets
861
883
  ? [__classPrivateFieldGet(this, _AssetsController_customAssetGraduationMiddleware, "f")]
@@ -869,7 +891,11 @@ export class AssetsController extends BaseController {
869
891
  ]));
870
892
  }
871
893
  const { response: enrichedResponse } = await __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_executeMiddlewares).call(this, enrichmentSources, pipelineRequest, response);
872
- await __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_updateState).call(this, enrichedResponse);
894
+ await __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_updateState).call(this, { ...enrichedResponse, sourceId });
895
+ if (sourceId === 'BackendWebsocketDataSource' &&
896
+ enrichedResponse.assetsBalance) {
897
+ __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_markWsBalancesFresh).call(this, enrichedResponse.assetsBalance);
898
+ }
873
899
  __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_emitTrace).call(this, TRACE_UPDATE_PIPELINE, {
874
900
  source: sourceId,
875
901
  duration_ms: performance.now() - updateStart,
@@ -916,7 +942,7 @@ export class AssetsController extends BaseController {
916
942
  this.messenger.unregisterActionHandler('AssetsController:setSelectedCurrency');
917
943
  }
918
944
  }
919
- _AssetsController_isEnabled = new WeakMap(), _AssetsController_isBasicFunctionality = new WeakMap(), _AssetsController_defaultUpdateInterval = new WeakMap(), _AssetsController_trace = new WeakMap(), _AssetsController_captureException = new WeakMap(), _AssetsController_firstInitFetchReported = new WeakMap(), _AssetsController_stateSizeReported = new WeakMap(), _AssetsController_uiOpen = new WeakMap(), _AssetsController_keyringUnlocked = new WeakMap(), _AssetsController_controllerMutex = new WeakMap(), _AssetsController_accountRefreshMutex = new WeakMap(), _AssetsController_activeSubscriptions = new WeakMap(), _AssetsController_enabledChains = new WeakMap(), _AssetsController_lastKnownAccountIds = new WeakMap(), _AssetsController_backendWebsocketDataSource = new WeakMap(), _AssetsController_accountsApiDataSource = new WeakMap(), _AssetsController_snapDataSource = new WeakMap(), _AssetsController_rpcDataSource = new WeakMap(), _AssetsController_stakedBalanceDataSource = new WeakMap(), _AssetsController_priceDataSource = new WeakMap(), _AssetsController_detectionMiddleware = new WeakMap(), _AssetsController_customAssetGraduationMiddleware = new WeakMap(), _AssetsController_rpcFallbackMiddleware = new WeakMap(), _AssetsController_tokenDataSource = new WeakMap(), _AssetsController_unsubscribeBasicFunctionality = new WeakMap(), _AssetsController_queryApiClient = new WeakMap(), _AssetsController_onActiveChainsUpdated = new WeakMap(), _AssetsController_instances = new WeakSet(), _AssetsController_emitTrace = function _AssetsController_emitTrace(name, data, tags = {
945
+ _AssetsController_isEnabled = new WeakMap(), _AssetsController_isBasicFunctionality = new WeakMap(), _AssetsController_defaultUpdateInterval = new WeakMap(), _AssetsController_trace = new WeakMap(), _AssetsController_captureException = new WeakMap(), _AssetsController_firstInitFetchReported = new WeakMap(), _AssetsController_stateSizeReported = new WeakMap(), _AssetsController_uiOpen = new WeakMap(), _AssetsController_keyringUnlocked = new WeakMap(), _AssetsController_controllerMutex = new WeakMap(), _AssetsController_accountRefreshMutex = new WeakMap(), _AssetsController_activeSubscriptions = new WeakMap(), _AssetsController_enabledChains = new WeakMap(), _AssetsController_lastKnownAccountIds = new WeakMap(), _AssetsController_wsBalanceFreshUntil = new WeakMap(), _AssetsController_backendWebsocketDataSource = new WeakMap(), _AssetsController_accountsApiDataSource = new WeakMap(), _AssetsController_snapDataSource = new WeakMap(), _AssetsController_rpcDataSource = new WeakMap(), _AssetsController_stakedBalanceDataSource = new WeakMap(), _AssetsController_priceDataSource = new WeakMap(), _AssetsController_detectionMiddleware = new WeakMap(), _AssetsController_customAssetGraduationMiddleware = new WeakMap(), _AssetsController_rpcFallbackMiddleware = new WeakMap(), _AssetsController_tokenDataSource = new WeakMap(), _AssetsController_unsubscribeBasicFunctionality = new WeakMap(), _AssetsController_queryApiClient = new WeakMap(), _AssetsController_onActiveChainsUpdated = new WeakMap(), _AssetsController_instances = new WeakSet(), _AssetsController_emitTrace = function _AssetsController_emitTrace(name, data, tags = {
920
946
  controller: 'AssetsController',
921
947
  }) {
922
948
  if (!__classPrivateFieldGet(this, _AssetsController_trace, "f")) {
@@ -1042,11 +1068,11 @@ _AssetsController_isEnabled = new WeakMap(), _AssetsController_isBasicFunctional
1042
1068
  // The base-controller `:stateChange` event is guaranteed to fire
1043
1069
  // when init() calls this.update(). #start() is idempotent so
1044
1070
  // repeated fires are safe.
1045
- this.messenger.subscribe('AccountTreeController:stateChanged', () => {
1071
+ this.messenger.subscribe('AccountTreeController:stateChange', () => {
1046
1072
  __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_handleAccountTreeStateChange).call(this);
1047
1073
  });
1048
1074
  // Subscribe to network enablement changes (only enabledNetworkMap)
1049
- this.messenger.subscribe('NetworkEnablementController:stateChanged', ({ enabledNetworkMap }) => {
1075
+ this.messenger.subscribe('NetworkEnablementController:stateChange', ({ enabledNetworkMap }) => {
1050
1076
  __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_handleEnabledNetworksChanged).call(this, enabledNetworkMap).catch(console.error);
1051
1077
  });
1052
1078
  // When a network is added or removed from NetworkController, refresh
@@ -1063,7 +1089,7 @@ _AssetsController_isEnabled = new WeakMap(), _AssetsController_isBasicFunctional
1063
1089
  __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_refreshAssetsAfterNetworkChange).call(this);
1064
1090
  });
1065
1091
  // Client + Keyring lifecycle: only run when UI is open AND keyring is unlocked
1066
- this.messenger.subscribe('ClientController:stateChanged', (isUiOpen) => {
1092
+ this.messenger.subscribe('ClientController:stateChange', (isUiOpen) => {
1067
1093
  __classPrivateFieldSet(this, _AssetsController_uiOpen, isUiOpen, "f");
1068
1094
  __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_updateActive).call(this);
1069
1095
  }, clientControllerSelectors.selectIsUiOpen);
@@ -1080,12 +1106,6 @@ _AssetsController_isEnabled = new WeakMap(), _AssetsController_isBasicFunctional
1080
1106
  this.messenger.subscribe('TransactionController:unapprovedTransactionAdded', (transactionMeta) => {
1081
1107
  __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_onUnapprovedTransactionAdded).call(this, transactionMeta);
1082
1108
  });
1083
- // Real-time post-tx balances from AccountActivityService (same WS payload as
1084
- // TokenBalancesController; BackendWebsocketDataSource may not receive the
1085
- // callback when AccountActivityService owns the server subscription).
1086
- this.messenger.subscribe('AccountActivityService:balanceUpdated', (event) => {
1087
- __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_onAccountActivityBalanceUpdated).call(this, event);
1088
- });
1089
1109
  }, _AssetsController_onUnapprovedTransactionAdded = function _AssetsController_onUnapprovedTransactionAdded(transactionMeta) {
1090
1110
  const hexChainId = transactionMeta.chainId;
1091
1111
  if (!hexChainId) {
@@ -1108,26 +1128,6 @@ _AssetsController_isEnabled = new WeakMap(), _AssetsController_isBasicFunctional
1108
1128
  error,
1109
1129
  });
1110
1130
  });
1111
- }, _AssetsController_onAccountActivityBalanceUpdated = function _AssetsController_onAccountActivityBalanceUpdated({ address, chain, updates, }) {
1112
- const account = __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_getSelectedAccounts).call(this).find((a) => a.address.startsWith('0x')
1113
- ? a.address.toLowerCase() === address.toLowerCase()
1114
- : a.address === address);
1115
- if (!account) {
1116
- return;
1117
- }
1118
- const chainId = chain;
1119
- const response = processAccountActivityBalanceUpdates(updates, account.id, (assetId) => __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_getAssetType).call(this, assetId));
1120
- if (!response.assetsBalance) {
1121
- return;
1122
- }
1123
- const request = {
1124
- accountsWithSupportedChains: [{ account, supportedChains: [chainId] }],
1125
- chainIds: [chainId],
1126
- dataTypes: ['balance', 'metadata'],
1127
- };
1128
- this.handleAssetsUpdate(response, 'AccountActivityService', request).catch((error) => {
1129
- log('Failed to apply AccountActivityService balance update', { error });
1130
- });
1131
1131
  }, _AssetsController_updateActive = function _AssetsController_updateActive() {
1132
1132
  const shouldRun = __classPrivateFieldGet(this, _AssetsController_uiOpen, "f") && __classPrivateFieldGet(this, _AssetsController_keyringUnlocked, "f");
1133
1133
  if (shouldRun) {
@@ -1337,17 +1337,6 @@ async function _AssetsController_executeMiddlewares(sources, request, initialRes
1337
1337
  return __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_resolveNativeAssetIds).call(this, __classPrivateFieldGet(this, _AssetsController_enabledChains, "f"));
1338
1338
  }, _AssetsController_getNativeAssetIdsForAccount = function _AssetsController_getNativeAssetIdsForAccount(account) {
1339
1339
  return __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_resolveNativeAssetIds).call(this, __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_getEnabledChainsForAccount).call(this, account));
1340
- }, _AssetsController_getSlowPipelineChainIds = function _AssetsController_getSlowPipelineChainIds(chainIds, fastResponse) {
1341
- const accountsApiChains = new Set(__classPrivateFieldGet(this, _AssetsController_accountsApiDataSource, "f").getActiveChainsSync());
1342
- return chainIds.filter((chainId) => {
1343
- if (fastResponse.errors?.[chainId]) {
1344
- return true;
1345
- }
1346
- if (!accountsApiChains.has(chainId)) {
1347
- return true;
1348
- }
1349
- return false;
1350
- });
1351
1340
  }, _AssetsController_ensureNativeBalancesDefaultZero = function _AssetsController_ensureNativeBalancesDefaultZero() {
1352
1341
  const accounts = __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_getSelectedAccounts).call(this);
1353
1342
  if (accounts.length === 0) {
@@ -1365,7 +1354,7 @@ async function _AssetsController_executeMiddlewares(sources, request, initialRes
1365
1354
  balances[accountId] = {};
1366
1355
  }
1367
1356
  for (const nativeAssetId of nativeAssetIds) {
1368
- if (!Object.prototype.hasOwnProperty.call(balances[accountId], nativeAssetId)) {
1357
+ if (!(nativeAssetId in balances[accountId])) {
1369
1358
  balances[accountId][nativeAssetId] = { amount: '0' };
1370
1359
  }
1371
1360
  }
@@ -1415,9 +1404,37 @@ async function _AssetsController_executeMiddlewares(sources, request, initialRes
1415
1404
  }
1416
1405
  }
1417
1406
  });
1407
+ }, _AssetsController_filterBalancesRespectingWsFreshness = function _AssetsController_filterBalancesRespectingWsFreshness(accountId, accountBalances, sourceId) {
1408
+ if (!sourceId || !POLLING_BALANCE_SOURCES.has(sourceId)) {
1409
+ return accountBalances;
1410
+ }
1411
+ const now = Date.now();
1412
+ const filtered = {};
1413
+ for (const [assetId, balance] of Object.entries(accountBalances)) {
1414
+ const freshUntil = __classPrivateFieldGet(this, _AssetsController_wsBalanceFreshUntil, "f").get(`${accountId}:${assetId}`);
1415
+ if (freshUntil !== undefined && now < freshUntil) {
1416
+ continue;
1417
+ }
1418
+ filtered[assetId] = balance;
1419
+ }
1420
+ return filtered;
1421
+ }, _AssetsController_markWsBalancesFresh = function _AssetsController_markWsBalancesFresh(assetsBalance) {
1422
+ const freshUntil = Date.now() + WS_BALANCE_FRESHNESS_MS;
1423
+ for (const [accountId, balances] of Object.entries(assetsBalance)) {
1424
+ for (const assetId of Object.keys(balances)) {
1425
+ __classPrivateFieldGet(this, _AssetsController_wsBalanceFreshUntil, "f").set(`${accountId}:${assetId}`, freshUntil);
1426
+ }
1427
+ }
1428
+ }, _AssetsController_clearWsBalanceFreshness = function _AssetsController_clearWsBalanceFreshness(assetsBalance) {
1429
+ for (const [accountId, balances] of Object.entries(assetsBalance)) {
1430
+ for (const assetId of Object.keys(balances)) {
1431
+ __classPrivateFieldGet(this, _AssetsController_wsBalanceFreshUntil, "f").delete(`${accountId}:${assetId}`);
1432
+ }
1433
+ }
1418
1434
  }, _AssetsController_updateState = async function _AssetsController_updateState(response) {
1419
1435
  const normalizedResponse = normalizeResponse(response);
1420
1436
  const mode = normalizedResponse.updateMode ?? 'merge';
1437
+ const assetsBalanceToApply = normalizedResponse.assetsBalance;
1421
1438
  const releaseLock = await __classPrivateFieldGet(this, _AssetsController_controllerMutex, "f").acquire();
1422
1439
  try {
1423
1440
  const previousState = this.state;
@@ -1433,43 +1450,29 @@ async function _AssetsController_executeMiddlewares(sources, request, initialRes
1433
1450
  const balances = state.assetsBalance;
1434
1451
  const prices = state.assetsPrice;
1435
1452
  if (normalizedResponse.assetsInfo) {
1436
- if (mode === 'update') {
1437
- // Balance-only refresh: patch amounts without overwriting metadata,
1438
- // but seed entries that are missing so RPC-only chains (e.g.
1439
- // Avalanche) can render native balances on first fetch.
1440
- for (const [key, value] of Object.entries(normalizedResponse.assetsInfo)) {
1441
- if (metadata[key]) {
1442
- continue;
1443
- }
1444
- metadata[key] = value;
1453
+ for (const [key, value] of Object.entries(normalizedResponse.assetsInfo)) {
1454
+ if (!isEqual(previousState.assetsInfo[key], value)) {
1445
1455
  changedMetadata.push(key);
1446
1456
  }
1447
- }
1448
- else {
1449
- for (const [key, value] of Object.entries(normalizedResponse.assetsInfo)) {
1450
- if (!isEqual(previousState.assetsInfo[key], value)) {
1451
- changedMetadata.push(key);
1452
- }
1453
- const existing = metadata[key];
1454
- const incoming = value;
1455
- // When the API returns no symbol or name for this token, it has no
1456
- // real knowledge of it (e.g. a user-deployed token not indexed by
1457
- // the API). Preserve richer metadata already in state (e.g. from
1458
- // pendingMetadata set by addCustomAsset) so that the correct
1459
- // decimals/symbol/name/image are not overwritten with empty values.
1460
- if (existing && !incoming.symbol && !incoming.name) {
1461
- metadata[key] = {
1462
- ...existing,
1463
- ...incoming,
1464
- symbol: existing.symbol,
1465
- name: existing.name,
1466
- decimals: existing.decimals ?? incoming.decimals,
1467
- image: existing.image ?? incoming.image,
1468
- };
1469
- }
1470
- else {
1471
- metadata[key] = value;
1472
- }
1457
+ const existing = metadata[key];
1458
+ const incoming = value;
1459
+ // When the API returns no symbol or name for this token, it has no
1460
+ // real knowledge of it (e.g. a user-deployed token not indexed by
1461
+ // the API). Preserve richer metadata already in state (e.g. from
1462
+ // pendingMetadata set by addCustomAsset) so that the correct
1463
+ // decimals/symbol/name/image are not overwritten with empty values.
1464
+ if (existing && !incoming.symbol && !incoming.name) {
1465
+ metadata[key] = {
1466
+ ...existing,
1467
+ ...incoming,
1468
+ symbol: existing.symbol,
1469
+ name: existing.name,
1470
+ decimals: existing.decimals ?? incoming.decimals,
1471
+ image: existing.image ?? incoming.image,
1472
+ };
1473
+ }
1474
+ else {
1475
+ metadata[key] = value;
1473
1476
  }
1474
1477
  }
1475
1478
  }
@@ -1492,21 +1495,21 @@ async function _AssetsController_executeMiddlewares(sources, request, initialRes
1492
1495
  }
1493
1496
  }
1494
1497
  }
1495
- if (normalizedResponse.assetsBalance) {
1496
- for (const [accountId, accountBalances] of Object.entries(normalizedResponse.assetsBalance)) {
1498
+ if (assetsBalanceToApply) {
1499
+ for (const [accountId, accountBalances] of Object.entries(assetsBalanceToApply)) {
1500
+ const filteredAccountBalances = __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_filterBalancesRespectingWsFreshness).call(this, accountId, accountBalances, normalizedResponse.sourceId);
1497
1501
  const previousBalances = previousState.assetsBalance[accountId] ?? {};
1498
1502
  const customAssetIds = state.customAssets[accountId] ?? [];
1499
1503
  // Full: response is authoritative for the chains it covered;
1500
1504
  // balances for chains not in the response are preserved from
1501
1505
  // previous state so unsupported chains (e.g. Ink on AccountsAPI)
1502
1506
  // are never inadvertently reset to zero.
1503
- // Merge / update: response overlays previous balances (update never
1504
- // removes tokens missing from a partial snapshot).
1505
- const effective = mode === 'merge' || mode === 'update'
1506
- ? { ...previousBalances, ...accountBalances }
1507
+ // Merge: response overlays previous balances.
1508
+ const effective = mode === 'merge'
1509
+ ? { ...previousBalances, ...filteredAccountBalances }
1507
1510
  : (() => {
1508
1511
  // Determine which chain namespaces this response covers.
1509
- const coveredChains = new Set(Object.keys(accountBalances).map((assetId) => assetId.split('/')[0]));
1512
+ const coveredChains = new Set(Object.keys(filteredAccountBalances).map((assetId) => assetId.split('/')[0]));
1510
1513
  // Start from previous balances, dropping only entries for
1511
1514
  // chains this response is authoritative over.
1512
1515
  const next = {};
@@ -1516,10 +1519,10 @@ async function _AssetsController_executeMiddlewares(sources, request, initialRes
1516
1519
  }
1517
1520
  }
1518
1521
  // Apply the response (authoritative for covered chains).
1519
- Object.assign(next, accountBalances);
1522
+ Object.assign(next, filteredAccountBalances);
1520
1523
  // Preserve custom assets that the response omitted.
1521
1524
  for (const customId of customAssetIds) {
1522
- if (!Object.prototype.hasOwnProperty.call(next, customId)) {
1525
+ if (!(customId in next)) {
1523
1526
  const prev = previousBalances[customId];
1524
1527
  next[customId] =
1525
1528
  prev ?? { amount: '0' };
@@ -1527,25 +1530,13 @@ async function _AssetsController_executeMiddlewares(sources, request, initialRes
1527
1530
  }
1528
1531
  return next;
1529
1532
  })();
1530
- // Chains present in this partial response (e.g. Accounts API returned
1531
- // ERC-20 zeros but omitted native after a max send).
1532
- const coveredChainsInResponse = new Set(Object.keys(accountBalances).map((assetId) => assetId.split('/')[0]));
1533
1533
  // Ensure native tokens have an entry (0 if missing) for chains this account supports
1534
1534
  const account = __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_getSelectedAccounts).call(this).find((a) => a.id === accountId);
1535
1535
  const nativeAssetIdsForAccount = account
1536
1536
  ? __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_getNativeAssetIdsForAccount).call(this, account)
1537
1537
  : __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_getNativeAssetIdsForEnabledChains).call(this);
1538
1538
  for (const nativeAssetId of nativeAssetIdsForAccount) {
1539
- const nativeChain = nativeAssetId.split('/')[0];
1540
- if (!Object.prototype.hasOwnProperty.call(effective, nativeAssetId)) {
1541
- effective[nativeAssetId] = { amount: '0' };
1542
- }
1543
- else if (mode === 'update' &&
1544
- coveredChainsInResponse.has(nativeChain) &&
1545
- !Object.prototype.hasOwnProperty.call(accountBalances, nativeAssetId)) {
1546
- // Update-mode overlay keeps previous native when the response
1547
- // omits it. If the API returned any balance on this chain,
1548
- // treat omitted native as zero instead of a stale pre-tx amount.
1539
+ if (!(nativeAssetId in effective)) {
1549
1540
  effective[nativeAssetId] = { amount: '0' };
1550
1541
  }
1551
1542
  }
@@ -1577,21 +1568,10 @@ async function _AssetsController_executeMiddlewares(sources, request, initialRes
1577
1568
  balances[accountId] = effective;
1578
1569
  }
1579
1570
  }
1580
- // Update prices in state. Update mode only seeds missing entries so
1581
- // balance-only refreshes do not clobber existing price data.
1571
+ // Update prices in state
1582
1572
  if (normalizedResponse.assetsPrice) {
1583
- if (mode === 'update') {
1584
- for (const [key, value] of Object.entries(normalizedResponse.assetsPrice)) {
1585
- if (prices[key]) {
1586
- continue;
1587
- }
1588
- prices[key] = value;
1589
- }
1590
- }
1591
- else {
1592
- for (const [key, value] of Object.entries(normalizedResponse.assetsPrice)) {
1593
- prices[key] = value;
1594
- }
1573
+ for (const [key, value] of Object.entries(normalizedResponse.assetsPrice)) {
1574
+ prices[key] = value;
1595
1575
  }
1596
1576
  }
1597
1577
  });
@@ -1651,6 +1631,12 @@ async function _AssetsController_executeMiddlewares(sources, request, initialRes
1651
1631
  });
1652
1632
  }
1653
1633
  }
1634
+ // Authoritative fetch on account switch — drop WS freshness locks so API
1635
+ // balances (e.g. receiver +1 USDC) replace stale values from a prior send.
1636
+ if (normalizedResponse.sourceId === 'getAssets:forceUpdate' &&
1637
+ assetsBalanceToApply) {
1638
+ __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_clearWsBalanceFreshness).call(this, assetsBalanceToApply);
1639
+ }
1654
1640
  }
1655
1641
  finally {
1656
1642
  releaseLock();
@@ -1834,13 +1820,7 @@ async function _AssetsController_executeMiddlewares(sources, request, initialRes
1834
1820
  const seenIds = new Set();
1835
1821
  const accountsForSource = assignedChains
1836
1822
  .flatMap((chainId) => chainToAccounts.get(chainId) ?? [])
1837
- .filter((account) => {
1838
- if (seenIds.has(account.id)) {
1839
- return false;
1840
- }
1841
- seenIds.add(account.id);
1842
- return true;
1843
- });
1823
+ .filter((account) => !seenIds.has(account.id) && (seenIds.add(account.id), true));
1844
1824
  if (accountsForSource.length > 0) {
1845
1825
  __classPrivateFieldGet(this, _AssetsController_instances, "m", _AssetsController_subscribeDataSource).call(this, source, accountsForSource, assignedChains);
1846
1826
  }