@metamask-previews/assets-controller 14.0.3-preview-e12b5ece6 → 14.0.3-preview-fe4b3be11

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 (80) hide show
  1. package/CHANGELOG.md +5 -10
  2. package/dist/AssetsController.cjs +592 -273
  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 +592 -273
  9. package/dist/AssetsController.mjs.map +1 -1
  10. package/dist/data-sources/AbstractDataSource.cjs +23 -0
  11. package/dist/data-sources/AbstractDataSource.cjs.map +1 -1
  12. package/dist/data-sources/AbstractDataSource.d.cts +13 -1
  13. package/dist/data-sources/AbstractDataSource.d.cts.map +1 -1
  14. package/dist/data-sources/AbstractDataSource.d.mts +13 -1
  15. package/dist/data-sources/AbstractDataSource.d.mts.map +1 -1
  16. package/dist/data-sources/AbstractDataSource.mjs +23 -0
  17. package/dist/data-sources/AbstractDataSource.mjs.map +1 -1
  18. package/dist/data-sources/AccountActivityDataSource.cjs +2 -0
  19. package/dist/data-sources/AccountActivityDataSource.cjs.map +1 -1
  20. package/dist/data-sources/AccountActivityDataSource.d.cts.map +1 -1
  21. package/dist/data-sources/AccountActivityDataSource.d.mts.map +1 -1
  22. package/dist/data-sources/AccountActivityDataSource.mjs +2 -0
  23. package/dist/data-sources/AccountActivityDataSource.mjs.map +1 -1
  24. package/dist/data-sources/AccountsApiDataSource.cjs +144 -31
  25. package/dist/data-sources/AccountsApiDataSource.cjs.map +1 -1
  26. package/dist/data-sources/AccountsApiDataSource.d.cts +18 -2
  27. package/dist/data-sources/AccountsApiDataSource.d.cts.map +1 -1
  28. package/dist/data-sources/AccountsApiDataSource.d.mts +18 -2
  29. package/dist/data-sources/AccountsApiDataSource.d.mts.map +1 -1
  30. package/dist/data-sources/AccountsApiDataSource.mjs +145 -32
  31. package/dist/data-sources/AccountsApiDataSource.mjs.map +1 -1
  32. package/dist/data-sources/RpcDataSource.cjs +163 -24
  33. package/dist/data-sources/RpcDataSource.cjs.map +1 -1
  34. package/dist/data-sources/RpcDataSource.d.cts +17 -0
  35. package/dist/data-sources/RpcDataSource.d.cts.map +1 -1
  36. package/dist/data-sources/RpcDataSource.d.mts +17 -0
  37. package/dist/data-sources/RpcDataSource.d.mts.map +1 -1
  38. package/dist/data-sources/RpcDataSource.mjs +164 -25
  39. package/dist/data-sources/RpcDataSource.mjs.map +1 -1
  40. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.cjs +21 -12
  41. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.cjs.map +1 -1
  42. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.d.cts +7 -2
  43. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.d.cts.map +1 -1
  44. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.d.mts +7 -2
  45. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.d.mts.map +1 -1
  46. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.mjs +21 -12
  47. package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.mjs.map +1 -1
  48. package/dist/data-sources/evm-rpc-services/types/state.cjs.map +1 -1
  49. package/dist/data-sources/evm-rpc-services/types/state.d.cts +3 -2
  50. package/dist/data-sources/evm-rpc-services/types/state.d.cts.map +1 -1
  51. package/dist/data-sources/evm-rpc-services/types/state.d.mts +3 -2
  52. package/dist/data-sources/evm-rpc-services/types/state.d.mts.map +1 -1
  53. package/dist/data-sources/evm-rpc-services/types/state.mjs.map +1 -1
  54. package/dist/middlewares/ParallelMiddleware.cjs +9 -0
  55. package/dist/middlewares/ParallelMiddleware.cjs.map +1 -1
  56. package/dist/middlewares/ParallelMiddleware.d.cts.map +1 -1
  57. package/dist/middlewares/ParallelMiddleware.d.mts.map +1 -1
  58. package/dist/middlewares/ParallelMiddleware.mjs +9 -0
  59. package/dist/middlewares/ParallelMiddleware.mjs.map +1 -1
  60. package/dist/middlewares/RpcFallbackMiddleware.cjs +158 -128
  61. package/dist/middlewares/RpcFallbackMiddleware.cjs.map +1 -1
  62. package/dist/middlewares/RpcFallbackMiddleware.d.cts +10 -14
  63. package/dist/middlewares/RpcFallbackMiddleware.d.cts.map +1 -1
  64. package/dist/middlewares/RpcFallbackMiddleware.d.mts +10 -14
  65. package/dist/middlewares/RpcFallbackMiddleware.d.mts.map +1 -1
  66. package/dist/middlewares/RpcFallbackMiddleware.mjs +158 -128
  67. package/dist/middlewares/RpcFallbackMiddleware.mjs.map +1 -1
  68. package/dist/selectors/balance.cjs +4 -9
  69. package/dist/selectors/balance.cjs.map +1 -1
  70. package/dist/selectors/balance.d.cts.map +1 -1
  71. package/dist/selectors/balance.d.mts.map +1 -1
  72. package/dist/selectors/balance.mjs +4 -9
  73. package/dist/selectors/balance.mjs.map +1 -1
  74. package/dist/types.cjs.map +1 -1
  75. package/dist/types.d.cts +28 -26
  76. package/dist/types.d.cts.map +1 -1
  77. package/dist/types.d.mts +28 -26
  78. package/dist/types.d.mts.map +1 -1
  79. package/dist/types.mjs.map +1 -1
  80. package/package.json +4 -4
@@ -24,11 +24,16 @@ export type BalancePollingInput = {
24
24
  accountId: AccountId;
25
25
  /** Account address */
26
26
  accountAddress: Address;
27
+ /**
28
+ * When present, fetch exactly these assets instead of the tracked
29
+ * `assetsBalance` entries (Accounts API v6 asset-scoped RPC poll). Must be
30
+ * deterministically ordered — the polling input is the dedupe key.
31
+ */
32
+ assetIds?: CaipAssetType[];
27
33
  /**
28
34
  * When true, only fetch balances for entries in `state.customAssets`,
29
35
  * skipping `state.assetsBalance`. Used by the supplemental RPC
30
- * subscription on chains that another data source is already covering
31
- * for regular balance refreshes.
36
+ * subscription on the Accounts API v5 path.
32
37
  */
33
38
  customAssetsOnly?: boolean;
34
39
  };
@@ -1 +1 @@
1
- {"version":3,"file":"BalanceFetcher.d.cts","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/services/BalanceFetcher.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,6BAA4B;AAC3D,OAAO,KAAK,EACV,SAAS,EACT,OAAO,EAEP,eAAe,EACf,kBAAkB,EAClB,kBAAkB,EAGlB,aAAa,EACb,OAAO,EACR,2BAA0B;AAK3B;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG;IACpC,IAAI,EAAE,CAAC,MAAM,EAAE,2BAA2B,KAAK,kBAAkB,CAAC;CACnE,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,4CAA4C;IAC5C,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,uEAAuE;IACvE,aAAa,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,OAAO,CAAC;CACpD,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAChC,4BAA4B;IAC5B,OAAO,EAAE,OAAO,CAAC;IACjB,iBAAiB;IACjB,SAAS,EAAE,SAAS,CAAC;IACrB,sBAAsB;IACtB,cAAc,EAAE,OAAO,CAAC;IACxB;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG,CACpC,MAAM,EAAE,kBAAkB,KACvB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;;;;;;;;;;;;;;;;;;AAE1B;;;;;;;;GAQG;AACH,qBAAa,cAAe,SAAQ,mBAA0D;;gBAc1F,eAAe,EAAE,eAAe,EAChC,SAAS,EAAE,uBAAuB,EAClC,MAAM,EAAE,oBAAoB;IAe9B;;;;OAIG;IACH,kBAAkB,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IAI3D;;;;;OAKG;IACG,YAAY,CAAC,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IA8G7D;;;;;;;;;;;OAWG;IACG,sBAAsB,CAC1B,OAAO,EAAE,OAAO,EAChB,SAAS,EAAE,SAAS,EACpB,cAAc,EAAE,OAAO,EACvB,MAAM,EAAE,eAAe,EAAE,GACxB,OAAO,CAAC,kBAAkB,CAAC;CA0J/B"}
1
+ {"version":3,"file":"BalanceFetcher.d.cts","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/services/BalanceFetcher.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,6BAA4B;AAC3D,OAAO,KAAK,EACV,SAAS,EACT,OAAO,EAEP,eAAe,EACf,kBAAkB,EAClB,kBAAkB,EAGlB,aAAa,EACb,OAAO,EACR,2BAA0B;AAK3B;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG;IACpC,IAAI,EAAE,CAAC,MAAM,EAAE,2BAA2B,KAAK,kBAAkB,CAAC;CACnE,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,4CAA4C;IAC5C,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,uEAAuE;IACvE,aAAa,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,OAAO,CAAC;CACpD,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAChC,4BAA4B;IAC5B,OAAO,EAAE,OAAO,CAAC;IACjB,iBAAiB;IACjB,SAAS,EAAE,SAAS,CAAC;IACrB,sBAAsB;IACtB,cAAc,EAAE,OAAO,CAAC;IACxB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,aAAa,EAAE,CAAC;IAC3B;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG,CACpC,MAAM,EAAE,kBAAkB,KACvB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;;;;;;;;;;;;;;;;;;AAE1B;;;;;;;;GAQG;AACH,qBAAa,cAAe,SAAQ,mBAA0D;;gBAc1F,eAAe,EAAE,eAAe,EAChC,SAAS,EAAE,uBAAuB,EAClC,MAAM,EAAE,oBAAoB;IAe9B;;;;OAIG;IACH,kBAAkB,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IAI3D;;;;;OAKG;IACG,YAAY,CAAC,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IAkI7D;;;;;;;;;;;OAWG;IACG,sBAAsB,CAC1B,OAAO,EAAE,OAAO,EAChB,SAAS,EAAE,SAAS,EACpB,cAAc,EAAE,OAAO,EACvB,MAAM,EAAE,eAAe,EAAE,GACxB,OAAO,CAAC,kBAAkB,CAAC;CA0J/B"}
@@ -24,11 +24,16 @@ export type BalancePollingInput = {
24
24
  accountId: AccountId;
25
25
  /** Account address */
26
26
  accountAddress: Address;
27
+ /**
28
+ * When present, fetch exactly these assets instead of the tracked
29
+ * `assetsBalance` entries (Accounts API v6 asset-scoped RPC poll). Must be
30
+ * deterministically ordered — the polling input is the dedupe key.
31
+ */
32
+ assetIds?: CaipAssetType[];
27
33
  /**
28
34
  * When true, only fetch balances for entries in `state.customAssets`,
29
35
  * skipping `state.assetsBalance`. Used by the supplemental RPC
30
- * subscription on chains that another data source is already covering
31
- * for regular balance refreshes.
36
+ * subscription on the Accounts API v5 path.
32
37
  */
33
38
  customAssetsOnly?: boolean;
34
39
  };
@@ -1 +1 @@
1
- {"version":3,"file":"BalanceFetcher.d.mts","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/services/BalanceFetcher.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,6BAA4B;AAC3D,OAAO,KAAK,EACV,SAAS,EACT,OAAO,EAEP,eAAe,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B,MAAM,EAAE,eAAe,EAAE,GACxB,OAAO,CAAC,kBAAkB,CAAC;CA0J/B"}
1
+ {"version":3,"file":"BalanceFetcher.d.mts","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/services/BalanceFetcher.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,6BAA4B;AAC3D,OAAO,KAAK,EACV,SAAS,EACT,OAAO,EAEP,eAAe,EACf,kBAAkB,EAClB,kBAAkB,EAGlB,aAAa,EACb,OAAO,EACR,2BAA0B;AAK3B;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG;IACpC,IAAI,EAAE,CAAC,MAAM,EAAE,2BAA2B,KAAK,kBAAkB,CAAC;CACnE,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,4CAA4C;IAC5C,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,uEAAuE;IACvE,aAAa,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,OAAO,CAAC;CACpD,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAChC,4BAA4B;IAC5B,OAAO,EAAE,OAAO,CAAC;IACjB,iBAAiB;IACjB,SAAS,EAAE,SAAS,CAAC;IACrB,sBAAsB;IACtB,cAAc,EAAE,OAAO,CAAC;IACxB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,aAAa,EAAE,CAAC;IAC3B;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG,CACpC,MAAM,EAAE,kBAAkB,KACvB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;;;;;;;;;;;;;;;;;;AAE1B;;;;;;;;GAQG;AACH,qBAAa,cAAe,SAAQ,mBAA0D;;gBAc1F,eAAe,EAAE,eAAe,EAChC,SAAS,EAAE,uBAAuB,EAClC,MAAM,EAAE,oBAAoB;IAe9B;;;;OAIG;IACH,kBAAkB,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IAI3D;;;;;OAKG;IACG,YAAY,CAAC,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IAkI7D;;;;;;;;;;;OAWG;IACG,sBAAsB,CAC1B,OAAO,EAAE,OAAO,EAChB,SAAS,EAAE,SAAS,EACpB,cAAc,EAAE,OAAO,EACvB,MAAM,EAAE,eAAe,EAAE,GACxB,OAAO,CAAC,kBAAkB,CAAC;CA0J/B"}
@@ -58,7 +58,7 @@ export class BalanceFetcher extends StaticIntervalPollingControllerOnly() {
58
58
  * @param input - The polling input.
59
59
  */
60
60
  async _executePoll(input) {
61
- const result = await __classPrivateFieldGet(this, _BalanceFetcher_instances, "m", _BalanceFetcher_fetchBalances).call(this, input.chainId, input.accountId, input.accountAddress, input.customAssetsOnly === true);
61
+ const result = await __classPrivateFieldGet(this, _BalanceFetcher_instances, "m", _BalanceFetcher_fetchBalances).call(this, input.chainId, input.accountId, input.accountAddress, input.assetIds, input.customAssetsOnly === true);
62
62
  if (__classPrivateFieldGet(this, _BalanceFetcher_onBalanceUpdate, "f") && result.balances.length > 0) {
63
63
  await __classPrivateFieldGet(this, _BalanceFetcher_onBalanceUpdate, "f").call(this, result);
64
64
  }
@@ -120,8 +120,7 @@ export class BalanceFetcher extends StaticIntervalPollingControllerOnly() {
120
120
  };
121
121
  }
122
122
  }
123
- _BalanceFetcher_multicallClient = new WeakMap(), _BalanceFetcher_messenger = new WeakMap(), _BalanceFetcher_config = new WeakMap(), _BalanceFetcher_isNativeAsset = new WeakMap(), _BalanceFetcher_onBalanceUpdate = new WeakMap(), _BalanceFetcher_instances = new WeakSet(), _BalanceFetcher_getAssetsToFetch = function _BalanceFetcher_getAssetsToFetch(chainId, accountId, customAssetsOnly) {
124
- const state = __classPrivateFieldGet(this, _BalanceFetcher_messenger, "f").call('AssetsController:getState');
123
+ _BalanceFetcher_multicallClient = new WeakMap(), _BalanceFetcher_messenger = new WeakMap(), _BalanceFetcher_config = new WeakMap(), _BalanceFetcher_isNativeAsset = new WeakMap(), _BalanceFetcher_onBalanceUpdate = new WeakMap(), _BalanceFetcher_instances = new WeakSet(), _BalanceFetcher_getAssetsToFetch = function _BalanceFetcher_getAssetsToFetch(chainId, accountId, assetIds, customAssetsOnly = false) {
125
124
  // Convert hex chainId to decimal for CAIP-2 matching
126
125
  // This is safe because we are filtring with an accountId that is for evm balances only
127
126
  const chainIdDecimal = parseInt(chainId, 16).toString();
@@ -143,9 +142,18 @@ _BalanceFetcher_multicallClient = new WeakMap(), _BalanceFetcher_messenger = new
143
142
  : parsed.assetReference.toLowerCase(),
144
143
  });
145
144
  };
146
- // 1. Assets already tracked with a balance entry — only when not in
147
- // "customAssetsOnly" mode (otherwise another data source is already
148
- // refreshing them and we'd double-poll).
145
+ // Asset-scoped poll: fetch only the input's assets; tracked balances on
146
+ // this chain are another source's responsibility.
147
+ if (assetIds) {
148
+ for (const assetId of assetIds) {
149
+ collect(assetId);
150
+ }
151
+ return Array.from(assetsToFetch.values());
152
+ }
153
+ const state = __classPrivateFieldGet(this, _BalanceFetcher_messenger, "f").call('AssetsController:getState');
154
+ // Assets tracked with a balance entry — only when not in
155
+ // "customAssetsOnly" mode (otherwise another data source is already
156
+ // refreshing them and we'd double-poll).
149
157
  if (!customAssetsOnly) {
150
158
  const accountBalances = state?.assetsBalance?.[accountId];
151
159
  if (accountBalances) {
@@ -154,10 +162,9 @@ _BalanceFetcher_multicallClient = new WeakMap(), _BalanceFetcher_messenger = new
154
162
  }
155
163
  }
156
164
  }
157
- // 2. User-added custom assets — RPC is the sole balance fetcher for
158
- // these, so they must be polled even if they have no balance entry
159
- // yet (e.g. zero balance, first fetch failed, or state was hydrated
160
- // from disk before any successful fetch).
165
+ // User-added custom assets — on the v5 path RPC is the sole balance
166
+ // fetcher for these, so they must be polled even if they have no balance
167
+ // entry yet. On the v6 path they are usually already in `assetsBalance`.
161
168
  const customAssets = state?.customAssets?.[accountId];
162
169
  if (customAssets) {
163
170
  for (const assetId of customAssets) {
@@ -173,11 +180,13 @@ _BalanceFetcher_multicallClient = new WeakMap(), _BalanceFetcher_messenger = new
173
180
  * @param chainId - Hex chain ID.
174
181
  * @param accountId - Account UUID.
175
182
  * @param accountAddress - On-chain address of the account.
183
+ * @param assetIds - When present, fetch exactly these assets instead of the
184
+ * tracked `assetsBalance` entries.
176
185
  * @param customAssetsOnly - When true, skip `assetsBalance` and only include `customAssets`.
177
186
  * @returns Balance fetch result.
178
187
  */
179
- async function _BalanceFetcher_fetchBalances(chainId, accountId, accountAddress, customAssetsOnly) {
180
- const assets = __classPrivateFieldGet(this, _BalanceFetcher_instances, "m", _BalanceFetcher_getAssetsToFetch).call(this, chainId, accountId, customAssetsOnly);
188
+ async function _BalanceFetcher_fetchBalances(chainId, accountId, accountAddress, assetIds, customAssetsOnly = false) {
189
+ const assets = __classPrivateFieldGet(this, _BalanceFetcher_instances, "m", _BalanceFetcher_getAssetsToFetch).call(this, chainId, accountId, assetIds, customAssetsOnly);
181
190
  return this.fetchBalancesForAssets(chainId, accountId, accountAddress, assets);
182
191
  }, _BalanceFetcher_processBalanceResponses = function _BalanceFetcher_processBalanceResponses(responses, accumulator, chainId, accountId, timestamp, entryByAddress) {
183
192
  const { balances, failedAddresses } = accumulator;
@@ -1 +1 @@
1
- {"version":3,"file":"BalanceFetcher.mjs","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/services/BalanceFetcher.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,mCAAmC,EAAE,qCAAqC;AACnF,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AAErD,OAAO,EAAE,YAAY,EAAE,qCAAoC;AAc3D,OAAO,EAAE,uBAAuB,EAAE,2BAA0B;AAE5D,MAAM,wBAAwB,GAAG,KAAM,CAAC,CAAC,aAAa;AA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AAM,aAAa,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;QACzC,MAAM,OAAO,GAAG,MAAM,CAAC,EAAE,IAAI,QAAQ,CAAC,CAAC;QAEvC,MAAM,WAAW,GAAG,aAAa,GAAG,OAAO,CAAC;QAC5C,MAAM,SAAS,GAAG,aAAa,GAAG,OAAO,CAAC;QAC1C,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;QACnE,MAAM,iBAAiB,GAAG,aAAa,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QAE5D,IAAI,iBAAiB,KAAK,EAAE,EAAE,CAAC;YAC7B,OAAO,WAAW,CAAC,QAAQ,EAAE,CAAC;QAChC,CAAC;QAED,OAAO,GAAG,WAAW,IAAI,iBAAiB,EAAE,CAAC;IAC/C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,UAAU,CAAC;IACpB,CAAC;AACH,CAAC","sourcesContent":["import { StaticIntervalPollingControllerOnly } from '@metamask/polling-controller';\nimport { parseCaipAssetType } from '@metamask/utils';\n\nimport { ZERO_ADDRESS } from '../../../utils/constants.js';\nimport type { MulticallClient } from '../clients/index.js';\nimport type {\n AccountId,\n Address,\n AssetBalance,\n AssetFetchEntry,\n AssetsBalanceState,\n BalanceFetchResult,\n BalanceOfRequest,\n BalanceOfResponse,\n CaipAssetType,\n ChainId,\n} from '../types/index.js';\nimport { reduceInBatchesSerially } from '../utils/index.js';\n\nconst DEFAULT_BALANCE_INTERVAL = 30_000; // 30 seconds\n\n/**\n * Minimal messenger interface for BalanceFetcher.\n */\nexport type BalanceFetcherMessenger = {\n call: (action: 'AssetsController:getState') => AssetsBalanceState;\n};\n\nexport type BalanceFetcherConfig = {\n defaultBatchSize?: number;\n defaultTimeoutMs?: number;\n /** Polling interval in ms (default: 30s) */\n pollingInterval?: number;\n /** Determines whether a CAIP-19 asset ID represents a native asset. */\n isNativeAsset: (assetId: CaipAssetType) => boolean;\n};\n\n/**\n * Polling input for BalanceFetcher - identifies what to poll for.\n */\nexport type BalancePollingInput = {\n /** Chain ID (hex format) */\n chainId: ChainId;\n /** Account ID */\n accountId: AccountId;\n /** Account address */\n accountAddress: Address;\n /**\n * When true, only fetch balances for entries in `state.customAssets`,\n * skipping `state.assetsBalance`. Used by the supplemental RPC\n * subscription on chains that another data source is already covering\n * for regular balance refreshes.\n */\n customAssetsOnly?: boolean;\n};\n\n/**\n * Callback type for balance updates.\n */\nexport type OnBalanceUpdateCallback = (\n result: BalanceFetchResult,\n) => void | Promise<void>;\n\n/**\n * BalanceFetcher - Fetches token balances via multicall.\n * Extends StaticIntervalPollingControllerOnly for built-in polling support.\n *\n * Callers provide CAIP-19 asset IDs; the fetcher extracts on-chain addresses\n * (or uses the zero address for native assets) and maps multicall responses\n * back to the original asset IDs. This ensures the returned balance entries\n * always carry the correct identifier regardless of chain.\n */\nexport class BalanceFetcher extends StaticIntervalPollingControllerOnly<BalancePollingInput>() {\n readonly #multicallClient: MulticallClient;\n\n readonly #messenger: BalanceFetcherMessenger;\n\n readonly #config: Required<\n Omit<BalanceFetcherConfig, 'pollingInterval' | 'isNativeAsset'>\n >;\n\n readonly #isNativeAsset: (assetId: CaipAssetType) => boolean;\n\n #onBalanceUpdate: OnBalanceUpdateCallback | undefined;\n\n constructor(\n multicallClient: MulticallClient,\n messenger: BalanceFetcherMessenger,\n config: BalanceFetcherConfig,\n ) {\n super();\n this.#multicallClient = multicallClient;\n this.#messenger = messenger;\n this.#config = {\n defaultBatchSize: config.defaultBatchSize ?? 300,\n defaultTimeoutMs: config.defaultTimeoutMs ?? 30000,\n };\n this.#isNativeAsset = config.isNativeAsset;\n\n // Set the polling interval\n this.setIntervalLength(config?.pollingInterval ?? DEFAULT_BALANCE_INTERVAL);\n }\n\n /**\n * Set the callback to receive balance updates during polling.\n *\n * @param callback - Function to call with balance results.\n */\n setOnBalanceUpdate(callback: OnBalanceUpdateCallback): void {\n this.#onBalanceUpdate = callback;\n }\n\n /**\n * Execute a poll cycle (required by base class).\n * Fetches balances and calls the update callback.\n *\n * @param input - The polling input.\n */\n async _executePoll(input: BalancePollingInput): Promise<void> {\n const result = await this.#fetchBalances(\n input.chainId,\n input.accountId,\n input.accountAddress,\n input.customAssetsOnly === true,\n );\n\n if (this.#onBalanceUpdate && result.balances.length > 0) {\n await this.#onBalanceUpdate(result);\n }\n }\n\n /**\n * Return asset fetch entries tracked in state for the given account and\n * chain. Both native (`slip44:`) and ERC-20 (`erc20:`) entries are included.\n *\n * @param chainId - Hex chain ID (e.g. \"0x1\").\n * @param accountId - Account UUID.\n * @param customAssetsOnly - When true, skip `assetsBalance` and only include `customAssets`.\n * @returns Array of asset fetch entries from state for the requested chain.\n */\n #getAssetsToFetch(\n chainId: ChainId,\n accountId: AccountId,\n customAssetsOnly: boolean,\n ): AssetFetchEntry[] {\n const state = this.#messenger.call('AssetsController:getState');\n\n // Convert hex chainId to decimal for CAIP-2 matching\n // This is safe because we are filtring with an accountId that is for evm balances only\n const chainIdDecimal = parseInt(chainId, 16).toString();\n\n const assetsToFetch = new Map<string, AssetFetchEntry>();\n\n const collect = (assetId: CaipAssetType): void => {\n const parsed = parseCaipAssetType(assetId);\n\n if (parsed.chain.reference !== chainIdDecimal) {\n return;\n }\n\n const normalizedAssetId = assetId.toLowerCase();\n\n if (assetsToFetch.has(normalizedAssetId)) {\n return;\n }\n\n const isNative = this.#isNativeAsset(assetId);\n\n assetsToFetch.set(normalizedAssetId, {\n assetId,\n address: isNative\n ? ZERO_ADDRESS\n : (parsed.assetReference.toLowerCase() as Address),\n });\n };\n\n // 1. Assets already tracked with a balance entry — only when not in\n // \"customAssetsOnly\" mode (otherwise another data source is already\n // refreshing them and we'd double-poll).\n if (!customAssetsOnly) {\n const accountBalances = state?.assetsBalance?.[accountId];\n if (accountBalances) {\n for (const assetId of Object.keys(accountBalances) as CaipAssetType[]) {\n collect(assetId);\n }\n }\n }\n\n // 2. User-added custom assets — RPC is the sole balance fetcher for\n // these, so they must be polled even if they have no balance entry\n // yet (e.g. zero balance, first fetch failed, or state was hydrated\n // from disk before any successful fetch).\n const customAssets = state?.customAssets?.[accountId];\n if (customAssets) {\n for (const assetId of customAssets as CaipAssetType[]) {\n collect(assetId);\n }\n }\n\n return Array.from(assetsToFetch.values());\n }\n\n /**\n * Fetch balances for assets already tracked in state for the given\n * account and chain.\n *\n * @param chainId - Hex chain ID.\n * @param accountId - Account UUID.\n * @param accountAddress - On-chain address of the account.\n * @param customAssetsOnly - When true, skip `assetsBalance` and only include `customAssets`.\n * @returns Balance fetch result.\n */\n async #fetchBalances(\n chainId: ChainId,\n accountId: AccountId,\n accountAddress: Address,\n customAssetsOnly: boolean,\n ): Promise<BalanceFetchResult> {\n const assets = this.#getAssetsToFetch(chainId, accountId, customAssetsOnly);\n\n return this.fetchBalancesForAssets(\n chainId,\n accountId,\n accountAddress,\n assets,\n );\n }\n\n /**\n * Fetch balances for the given assets via multicall.\n *\n * Each entry bundles a CAIP-19 asset ID with its on-chain address and\n * optional decimals.\n *\n * @param chainId - Hex chain ID.\n * @param accountId - Account UUID.\n * @param accountAddress - On-chain address of the account.\n * @param assets - Asset fetch entries to fetch balances for.\n * @returns Balance fetch result.\n */\n async fetchBalancesForAssets(\n chainId: ChainId,\n accountId: AccountId,\n accountAddress: Address,\n assets: AssetFetchEntry[],\n ): Promise<BalanceFetchResult> {\n const timestamp = Date.now();\n\n // Build a single map keyed by lowercase address that holds all info\n // needed to match multicall responses back to their original entries.\n const balanceRequests: BalanceOfRequest[] = [];\n const entryByAddress = new Map<string, AssetFetchEntry>();\n\n for (const entry of assets) {\n const lowerAddress = entry.address.toLowerCase();\n if (entryByAddress.has(lowerAddress)) {\n continue; // deduplicate\n }\n\n entryByAddress.set(lowerAddress, entry);\n balanceRequests.push({ tokenAddress: entry.address, accountAddress });\n }\n\n if (balanceRequests.length === 0) {\n return {\n chainId,\n accountId,\n accountAddress,\n balances: [],\n failedAddresses: [],\n timestamp,\n };\n }\n\n type FetchAccumulator = {\n balances: AssetBalance[];\n failedAddresses: Address[];\n };\n\n const result = await reduceInBatchesSerially<\n BalanceOfRequest,\n FetchAccumulator\n >({\n values: balanceRequests,\n batchSize: this.#config.defaultBatchSize,\n initialResult: {\n balances: [],\n failedAddresses: [],\n },\n eachBatch: async (workingResult, batch) => {\n const responses = await this.#multicallClient.batchBalanceOf(\n chainId,\n batch,\n { fallbackToSingleCalls: true },\n );\n\n return this.#processBalanceResponses(\n responses,\n workingResult as FetchAccumulator,\n chainId,\n accountId,\n timestamp,\n entryByAddress,\n );\n },\n });\n\n return {\n chainId,\n accountId,\n accountAddress,\n ...result,\n timestamp,\n };\n }\n\n #processBalanceResponses(\n responses: BalanceOfResponse[],\n accumulator: {\n balances: AssetBalance[];\n failedAddresses: Address[];\n },\n chainId: ChainId,\n accountId: AccountId,\n timestamp: number,\n entryByAddress: Map<string, AssetFetchEntry>,\n ): {\n balances: AssetBalance[];\n failedAddresses: Address[];\n } {\n const { balances, failedAddresses } = accumulator;\n\n for (const response of responses) {\n if (!response.success) {\n failedAddresses.push(response.tokenAddress);\n continue;\n }\n\n const lowerAddress = response.tokenAddress.toLowerCase();\n const entry = entryByAddress.get(lowerAddress);\n if (!entry) {\n continue;\n }\n\n const balance = response.balance ?? '0';\n const isNative = lowerAddress === ZERO_ADDRESS.toLowerCase();\n\n let decimals: number | undefined;\n let formattedBalance: string;\n if (isNative) {\n decimals = 18;\n formattedBalance = this.#formatBalance(balance, decimals);\n } else if (entry.decimals === undefined) {\n formattedBalance = balance;\n } else {\n decimals = entry.decimals;\n formattedBalance = this.#formatBalance(balance, decimals);\n }\n\n const balanceEntry: AssetBalance = {\n assetId: entry.assetId,\n accountId,\n chainId,\n balance,\n formattedBalance,\n timestamp,\n };\n if (typeof decimals === 'number') {\n balanceEntry.decimals = decimals;\n }\n balances.push(balanceEntry);\n }\n\n return { balances, failedAddresses };\n }\n\n #formatBalance(rawBalance: string, decimals: number): string {\n if (rawBalance === '0') {\n return '0';\n }\n\n try {\n const balanceBigInt = BigInt(rawBalance);\n const divisor = BigInt(10 ** decimals);\n\n const integerPart = balanceBigInt / divisor;\n const remainder = balanceBigInt % divisor;\n const fractionalStr = remainder.toString().padStart(decimals, '0');\n const trimmedFractional = fractionalStr.replace(/0+$/u, '');\n\n if (trimmedFractional === '') {\n return integerPart.toString();\n }\n\n return `${integerPart}.${trimmedFractional}`;\n } catch {\n return rawBalance;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"BalanceFetcher.mjs","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/services/BalanceFetcher.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,mCAAmC,EAAE,qCAAqC;AACnF,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AAErD,OAAO,EAAE,YAAY,EAAE,qCAAoC;AAc3D,OAAO,EAAE,uBAAuB,EAAE,2BAA0B;AAE5D,MAAM,wBAAwB,GAAG,KAAM,CAAC,CAAC,aAAa;AAiDtD;;;;;;;;GAQG;AACH,MAAM,OAAO,cAAe,SAAQ,mCAAmC,EAAuB;IAa5F,YACE,eAAgC,EAChC,SAAkC,EAClC,MAA4B;QAE5B,KAAK,EAAE,CAAC;;QAjBD,kDAAkC;QAElC,4CAAoC;QAEpC,yCAEP;QAEO,gDAAoD;QAE7D,kDAAsD;QAQpD,uBAAA,IAAI,mCAAoB,eAAe,MAAA,CAAC;QACxC,uBAAA,IAAI,6BAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,IAAI,0BAAW;YACb,gBAAgB,EAAE,MAAM,CAAC,gBAAgB,IAAI,GAAG;YAChD,gBAAgB,EAAE,MAAM,CAAC,gBAAgB,IAAI,KAAK;SACnD,MAAA,CAAC;QACF,uBAAA,IAAI,iCAAkB,MAAM,CAAC,aAAa,MAAA,CAAC;QAE3C,2BAA2B;QAC3B,IAAI,CAAC,iBAAiB,CAAC,MAAM,EAAE,eAAe,IAAI,wBAAwB,CAA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,EAAE,GAAG,CAAC,CAAC;QACnE,MAAM,iBAAiB,GAAG,aAAa,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QAE5D,IAAI,iBAAiB,KAAK,EAAE,EAAE,CAAC;YAC7B,OAAO,WAAW,CAAC,QAAQ,EAAE,CAAC;QAChC,CAAC;QAED,OAAO,GAAG,WAAW,IAAI,iBAAiB,EAAE,CAAC;IAC/C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,UAAU,CAAC;IACpB,CAAC;AACH,CAAC","sourcesContent":["import { StaticIntervalPollingControllerOnly } from '@metamask/polling-controller';\nimport { parseCaipAssetType } from '@metamask/utils';\n\nimport { ZERO_ADDRESS } from '../../../utils/constants.js';\nimport type { MulticallClient } from '../clients/index.js';\nimport type {\n AccountId,\n Address,\n AssetBalance,\n AssetFetchEntry,\n AssetsBalanceState,\n BalanceFetchResult,\n BalanceOfRequest,\n BalanceOfResponse,\n CaipAssetType,\n ChainId,\n} from '../types/index.js';\nimport { reduceInBatchesSerially } from '../utils/index.js';\n\nconst DEFAULT_BALANCE_INTERVAL = 30_000; // 30 seconds\n\n/**\n * Minimal messenger interface for BalanceFetcher.\n */\nexport type BalanceFetcherMessenger = {\n call: (action: 'AssetsController:getState') => AssetsBalanceState;\n};\n\nexport type BalanceFetcherConfig = {\n defaultBatchSize?: number;\n defaultTimeoutMs?: number;\n /** Polling interval in ms (default: 30s) */\n pollingInterval?: number;\n /** Determines whether a CAIP-19 asset ID represents a native asset. */\n isNativeAsset: (assetId: CaipAssetType) => boolean;\n};\n\n/**\n * Polling input for BalanceFetcher - identifies what to poll for.\n */\nexport type BalancePollingInput = {\n /** Chain ID (hex format) */\n chainId: ChainId;\n /** Account ID */\n accountId: AccountId;\n /** Account address */\n accountAddress: Address;\n /**\n * When present, fetch exactly these assets instead of the tracked\n * `assetsBalance` entries (Accounts API v6 asset-scoped RPC poll). Must be\n * deterministically ordered — the polling input is the dedupe key.\n */\n assetIds?: CaipAssetType[];\n /**\n * When true, only fetch balances for entries in `state.customAssets`,\n * skipping `state.assetsBalance`. Used by the supplemental RPC\n * subscription on the Accounts API v5 path.\n */\n customAssetsOnly?: boolean;\n};\n\n/**\n * Callback type for balance updates.\n */\nexport type OnBalanceUpdateCallback = (\n result: BalanceFetchResult,\n) => void | Promise<void>;\n\n/**\n * BalanceFetcher - Fetches token balances via multicall.\n * Extends StaticIntervalPollingControllerOnly for built-in polling support.\n *\n * Callers provide CAIP-19 asset IDs; the fetcher extracts on-chain addresses\n * (or uses the zero address for native assets) and maps multicall responses\n * back to the original asset IDs. This ensures the returned balance entries\n * always carry the correct identifier regardless of chain.\n */\nexport class BalanceFetcher extends StaticIntervalPollingControllerOnly<BalancePollingInput>() {\n readonly #multicallClient: MulticallClient;\n\n readonly #messenger: BalanceFetcherMessenger;\n\n readonly #config: Required<\n Omit<BalanceFetcherConfig, 'pollingInterval' | 'isNativeAsset'>\n >;\n\n readonly #isNativeAsset: (assetId: CaipAssetType) => boolean;\n\n #onBalanceUpdate: OnBalanceUpdateCallback | undefined;\n\n constructor(\n multicallClient: MulticallClient,\n messenger: BalanceFetcherMessenger,\n config: BalanceFetcherConfig,\n ) {\n super();\n this.#multicallClient = multicallClient;\n this.#messenger = messenger;\n this.#config = {\n defaultBatchSize: config.defaultBatchSize ?? 300,\n defaultTimeoutMs: config.defaultTimeoutMs ?? 30000,\n };\n this.#isNativeAsset = config.isNativeAsset;\n\n // Set the polling interval\n this.setIntervalLength(config?.pollingInterval ?? DEFAULT_BALANCE_INTERVAL);\n }\n\n /**\n * Set the callback to receive balance updates during polling.\n *\n * @param callback - Function to call with balance results.\n */\n setOnBalanceUpdate(callback: OnBalanceUpdateCallback): void {\n this.#onBalanceUpdate = callback;\n }\n\n /**\n * Execute a poll cycle (required by base class).\n * Fetches balances and calls the update callback.\n *\n * @param input - The polling input.\n */\n async _executePoll(input: BalancePollingInput): Promise<void> {\n const result = await this.#fetchBalances(\n input.chainId,\n input.accountId,\n input.accountAddress,\n input.assetIds,\n input.customAssetsOnly === true,\n );\n\n if (this.#onBalanceUpdate && result.balances.length > 0) {\n await this.#onBalanceUpdate(result);\n }\n }\n\n /**\n * Return asset fetch entries tracked in state for the given account and\n * chain. Both native (`slip44:`) and ERC-20 (`erc20:`) entries are included.\n *\n * @param chainId - Hex chain ID (e.g. \"0x1\").\n * @param accountId - Account UUID.\n * @param assetIds - When present, fetch exactly these assets instead of the\n * tracked `assetsBalance` entries.\n * @param customAssetsOnly - When true, skip `assetsBalance` and only include `customAssets`.\n * @returns Array of asset fetch entries from state for the requested chain.\n */\n #getAssetsToFetch(\n chainId: ChainId,\n accountId: AccountId,\n assetIds?: CaipAssetType[],\n customAssetsOnly = false,\n ): AssetFetchEntry[] {\n // Convert hex chainId to decimal for CAIP-2 matching\n // This is safe because we are filtring with an accountId that is for evm balances only\n const chainIdDecimal = parseInt(chainId, 16).toString();\n\n const assetsToFetch = new Map<string, AssetFetchEntry>();\n\n const collect = (assetId: CaipAssetType): void => {\n const parsed = parseCaipAssetType(assetId);\n\n if (parsed.chain.reference !== chainIdDecimal) {\n return;\n }\n\n const normalizedAssetId = assetId.toLowerCase();\n\n if (assetsToFetch.has(normalizedAssetId)) {\n return;\n }\n\n const isNative = this.#isNativeAsset(assetId);\n\n assetsToFetch.set(normalizedAssetId, {\n assetId,\n address: isNative\n ? ZERO_ADDRESS\n : (parsed.assetReference.toLowerCase() as Address),\n });\n };\n\n // Asset-scoped poll: fetch only the input's assets; tracked balances on\n // this chain are another source's responsibility.\n if (assetIds) {\n for (const assetId of assetIds) {\n collect(assetId);\n }\n return Array.from(assetsToFetch.values());\n }\n\n const state = this.#messenger.call('AssetsController:getState');\n\n // Assets tracked with a balance entry — only when not in\n // \"customAssetsOnly\" mode (otherwise another data source is already\n // refreshing them and we'd double-poll).\n if (!customAssetsOnly) {\n const accountBalances = state?.assetsBalance?.[accountId];\n if (accountBalances) {\n for (const assetId of Object.keys(accountBalances) as CaipAssetType[]) {\n collect(assetId);\n }\n }\n }\n\n // User-added custom assets — on the v5 path RPC is the sole balance\n // fetcher for these, so they must be polled even if they have no balance\n // entry yet. On the v6 path they are usually already in `assetsBalance`.\n const customAssets = state?.customAssets?.[accountId];\n if (customAssets) {\n for (const assetId of customAssets as CaipAssetType[]) {\n collect(assetId);\n }\n }\n\n return Array.from(assetsToFetch.values());\n }\n\n /**\n * Fetch balances for assets already tracked in state for the given\n * account and chain.\n *\n * @param chainId - Hex chain ID.\n * @param accountId - Account UUID.\n * @param accountAddress - On-chain address of the account.\n * @param assetIds - When present, fetch exactly these assets instead of the\n * tracked `assetsBalance` entries.\n * @param customAssetsOnly - When true, skip `assetsBalance` and only include `customAssets`.\n * @returns Balance fetch result.\n */\n async #fetchBalances(\n chainId: ChainId,\n accountId: AccountId,\n accountAddress: Address,\n assetIds?: CaipAssetType[],\n customAssetsOnly = false,\n ): Promise<BalanceFetchResult> {\n const assets = this.#getAssetsToFetch(\n chainId,\n accountId,\n assetIds,\n customAssetsOnly,\n );\n\n return this.fetchBalancesForAssets(\n chainId,\n accountId,\n accountAddress,\n assets,\n );\n }\n\n /**\n * Fetch balances for the given assets via multicall.\n *\n * Each entry bundles a CAIP-19 asset ID with its on-chain address and\n * optional decimals.\n *\n * @param chainId - Hex chain ID.\n * @param accountId - Account UUID.\n * @param accountAddress - On-chain address of the account.\n * @param assets - Asset fetch entries to fetch balances for.\n * @returns Balance fetch result.\n */\n async fetchBalancesForAssets(\n chainId: ChainId,\n accountId: AccountId,\n accountAddress: Address,\n assets: AssetFetchEntry[],\n ): Promise<BalanceFetchResult> {\n const timestamp = Date.now();\n\n // Build a single map keyed by lowercase address that holds all info\n // needed to match multicall responses back to their original entries.\n const balanceRequests: BalanceOfRequest[] = [];\n const entryByAddress = new Map<string, AssetFetchEntry>();\n\n for (const entry of assets) {\n const lowerAddress = entry.address.toLowerCase();\n if (entryByAddress.has(lowerAddress)) {\n continue; // deduplicate\n }\n\n entryByAddress.set(lowerAddress, entry);\n balanceRequests.push({ tokenAddress: entry.address, accountAddress });\n }\n\n if (balanceRequests.length === 0) {\n return {\n chainId,\n accountId,\n accountAddress,\n balances: [],\n failedAddresses: [],\n timestamp,\n };\n }\n\n type FetchAccumulator = {\n balances: AssetBalance[];\n failedAddresses: Address[];\n };\n\n const result = await reduceInBatchesSerially<\n BalanceOfRequest,\n FetchAccumulator\n >({\n values: balanceRequests,\n batchSize: this.#config.defaultBatchSize,\n initialResult: {\n balances: [],\n failedAddresses: [],\n },\n eachBatch: async (workingResult, batch) => {\n const responses = await this.#multicallClient.batchBalanceOf(\n chainId,\n batch,\n { fallbackToSingleCalls: true },\n );\n\n return this.#processBalanceResponses(\n responses,\n workingResult as FetchAccumulator,\n chainId,\n accountId,\n timestamp,\n entryByAddress,\n );\n },\n });\n\n return {\n chainId,\n accountId,\n accountAddress,\n ...result,\n timestamp,\n };\n }\n\n #processBalanceResponses(\n responses: BalanceOfResponse[],\n accumulator: {\n balances: AssetBalance[];\n failedAddresses: Address[];\n },\n chainId: ChainId,\n accountId: AccountId,\n timestamp: number,\n entryByAddress: Map<string, AssetFetchEntry>,\n ): {\n balances: AssetBalance[];\n failedAddresses: Address[];\n } {\n const { balances, failedAddresses } = accumulator;\n\n for (const response of responses) {\n if (!response.success) {\n failedAddresses.push(response.tokenAddress);\n continue;\n }\n\n const lowerAddress = response.tokenAddress.toLowerCase();\n const entry = entryByAddress.get(lowerAddress);\n if (!entry) {\n continue;\n }\n\n const balance = response.balance ?? '0';\n const isNative = lowerAddress === ZERO_ADDRESS.toLowerCase();\n\n let decimals: number | undefined;\n let formattedBalance: string;\n if (isNative) {\n decimals = 18;\n formattedBalance = this.#formatBalance(balance, decimals);\n } else if (entry.decimals === undefined) {\n formattedBalance = balance;\n } else {\n decimals = entry.decimals;\n formattedBalance = this.#formatBalance(balance, decimals);\n }\n\n const balanceEntry: AssetBalance = {\n assetId: entry.assetId,\n accountId,\n chainId,\n balance,\n formattedBalance,\n timestamp,\n };\n if (typeof decimals === 'number') {\n balanceEntry.decimals = decimals;\n }\n balances.push(balanceEntry);\n }\n\n return { balances, failedAddresses };\n }\n\n #formatBalance(rawBalance: string, decimals: number): string {\n if (rawBalance === '0') {\n return '0';\n }\n\n try {\n const balanceBigInt = BigInt(rawBalance);\n const divisor = BigInt(10 ** decimals);\n\n const integerPart = balanceBigInt / divisor;\n const remainder = balanceBigInt % divisor;\n const fractionalStr = remainder.toString().padStart(decimals, '0');\n const trimmedFractional = fractionalStr.replace(/0+$/u, '');\n\n if (trimmedFractional === '') {\n return integerPart.toString();\n }\n\n return `${integerPart}.${trimmedFractional}`;\n } catch {\n return rawBalance;\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"state.cjs","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/types/state.ts"],"names":[],"mappings":"","sourcesContent":["import type { ChainId } from './core.js';\n\n/**\n * Single token entry from token list.\n */\nexport type TokenListEntry = {\n /** Contract address */\n address: string;\n /** Token symbol */\n symbol: string;\n /** Token name */\n name: string;\n /** Token decimals */\n decimals: number;\n /** Logo URL */\n iconUrl?: string;\n /** Aggregator sources */\n aggregators?: string[];\n /** Occurrence count in lists */\n occurrences?: number;\n};\n\n/**\n * Cache entry for a chain's token list.\n */\nexport type TokenChainsCacheEntry = {\n /** Timestamp when the cache was last updated */\n timestamp: number;\n /** Token list data: address -> TokenListEntry */\n data: Record<string, TokenListEntry>;\n};\n\n/**\n * Token list state shape (from TokenListController).\n */\nexport type TokenListState = {\n /** Map of chain ID to token list cache entry */\n tokensChainsCache: Record<ChainId, TokenChainsCacheEntry>;\n};\n\n/**\n * Single asset balance entry.\n */\nexport type AssetBalanceEntry = {\n /** Human-readable balance amount */\n amount: string;\n};\n\n/**\n * Assets balance state shape (from AssetsController).\n * Maps accountId -> assetId (CAIP-19) -> balance entry.\n */\nexport type AssetsBalanceState = {\n /** Balance data per account: accountId -> assetId -> balance */\n assetsBalance: Record<string, Record<string, AssetBalanceEntry>>;\n /**\n * User-added custom assets per account: accountId -> CAIP-19 asset IDs.\n * Used to ensure RPC polling refreshes custom assets even when they have\n * no entry in `assetsBalance` yet (e.g. zero balance, first fetch failed).\n */\n customAssets?: Record<string, string[]>;\n};\n"]}
1
+ {"version":3,"file":"state.cjs","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/types/state.ts"],"names":[],"mappings":"","sourcesContent":["import type { ChainId } from './core.js';\n\n/**\n * Single token entry from token list.\n */\nexport type TokenListEntry = {\n /** Contract address */\n address: string;\n /** Token symbol */\n symbol: string;\n /** Token name */\n name: string;\n /** Token decimals */\n decimals: number;\n /** Logo URL */\n iconUrl?: string;\n /** Aggregator sources */\n aggregators?: string[];\n /** Occurrence count in lists */\n occurrences?: number;\n};\n\n/**\n * Cache entry for a chain's token list.\n */\nexport type TokenChainsCacheEntry = {\n /** Timestamp when the cache was last updated */\n timestamp: number;\n /** Token list data: address -> TokenListEntry */\n data: Record<string, TokenListEntry>;\n};\n\n/**\n * Token list state shape (from TokenListController).\n */\nexport type TokenListState = {\n /** Map of chain ID to token list cache entry */\n tokensChainsCache: Record<ChainId, TokenChainsCacheEntry>;\n};\n\n/**\n * Single asset balance entry.\n */\nexport type AssetBalanceEntry = {\n /** Human-readable balance amount */\n amount: string;\n};\n\n/**\n * Assets balance state shape (from AssetsController).\n * Maps accountId -> assetId (CAIP-19) -> balance entry.\n */\nexport type AssetsBalanceState = {\n /** Balance data per account: accountId -> assetId -> balance */\n assetsBalance: Record<string, Record<string, AssetBalanceEntry>>;\n /**\n * User-added custom assets per account: accountId -> CAIP-19 asset IDs.\n * Not read by asset-scoped polls (`BalancePollingInput.assetIds`). Regular\n * polls still include these so v5 supplemental/`customAssetsOnly` refreshes\n * pins that have no `assetsBalance` row yet.\n */\n customAssets?: Record<string, string[]>;\n};\n"]}
@@ -50,8 +50,9 @@ export type AssetsBalanceState = {
50
50
  assetsBalance: Record<string, Record<string, AssetBalanceEntry>>;
51
51
  /**
52
52
  * User-added custom assets per account: accountId -> CAIP-19 asset IDs.
53
- * Used to ensure RPC polling refreshes custom assets even when they have
54
- * no entry in `assetsBalance` yet (e.g. zero balance, first fetch failed).
53
+ * Not read by asset-scoped polls (`BalancePollingInput.assetIds`). Regular
54
+ * polls still include these so v5 supplemental/`customAssetsOnly` refreshes
55
+ * pins that have no `assetsBalance` row yet.
55
56
  */
56
57
  customAssets?: Record<string, string[]>;
57
58
  };
@@ -1 +1 @@
1
- {"version":3,"file":"state.d.cts","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/types/state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,mBAAkB;AAEzC;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,uBAAuB;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,mBAAmB;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,iBAAiB;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,qBAAqB;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yBAAyB;IACzB,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;IACvB,gCAAgC;IAChC,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,gDAAgD;IAChD,SAAS,EAAE,MAAM,CAAC;IAClB,iDAAiD;IACjD,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;CACtC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,gDAAgD;IAChD,iBAAiB,EAAE,MAAM,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;CAC3D,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,oCAAoC;IACpC,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,gEAAgE;IAChE,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC;IACjE;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;CACzC,CAAC"}
1
+ {"version":3,"file":"state.d.cts","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/types/state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,mBAAkB;AAEzC;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,uBAAuB;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,mBAAmB;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,iBAAiB;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,qBAAqB;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yBAAyB;IACzB,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;IACvB,gCAAgC;IAChC,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,gDAAgD;IAChD,SAAS,EAAE,MAAM,CAAC;IAClB,iDAAiD;IACjD,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;CACtC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,gDAAgD;IAChD,iBAAiB,EAAE,MAAM,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;CAC3D,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,oCAAoC;IACpC,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,gEAAgE;IAChE,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC;IACjE;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;CACzC,CAAC"}
@@ -50,8 +50,9 @@ export type AssetsBalanceState = {
50
50
  assetsBalance: Record<string, Record<string, AssetBalanceEntry>>;
51
51
  /**
52
52
  * User-added custom assets per account: accountId -> CAIP-19 asset IDs.
53
- * Used to ensure RPC polling refreshes custom assets even when they have
54
- * no entry in `assetsBalance` yet (e.g. zero balance, first fetch failed).
53
+ * Not read by asset-scoped polls (`BalancePollingInput.assetIds`). Regular
54
+ * polls still include these so v5 supplemental/`customAssetsOnly` refreshes
55
+ * pins that have no `assetsBalance` row yet.
55
56
  */
56
57
  customAssets?: Record<string, string[]>;
57
58
  };
@@ -1 +1 @@
1
- {"version":3,"file":"state.d.mts","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/types/state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,mBAAkB;AAEzC;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,uBAAuB;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,mBAAmB;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,iBAAiB;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,qBAAqB;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yBAAyB;IACzB,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;IACvB,gCAAgC;IAChC,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,gDAAgD;IAChD,SAAS,EAAE,MAAM,CAAC;IAClB,iDAAiD;IACjD,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;CACtC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,gDAAgD;IAChD,iBAAiB,EAAE,MAAM,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;CAC3D,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,oCAAoC;IACpC,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,gEAAgE;IAChE,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC;IACjE;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;CACzC,CAAC"}
1
+ {"version":3,"file":"state.d.mts","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/types/state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,mBAAkB;AAEzC;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,uBAAuB;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,mBAAmB;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,iBAAiB;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,qBAAqB;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yBAAyB;IACzB,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;IACvB,gCAAgC;IAChC,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,gDAAgD;IAChD,SAAS,EAAE,MAAM,CAAC;IAClB,iDAAiD;IACjD,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;CACtC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,gDAAgD;IAChD,iBAAiB,EAAE,MAAM,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;CAC3D,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,oCAAoC;IACpC,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,gEAAgE;IAChE,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC;IACjE;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;CACzC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"state.mjs","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/types/state.ts"],"names":[],"mappings":"","sourcesContent":["import type { ChainId } from './core.js';\n\n/**\n * Single token entry from token list.\n */\nexport type TokenListEntry = {\n /** Contract address */\n address: string;\n /** Token symbol */\n symbol: string;\n /** Token name */\n name: string;\n /** Token decimals */\n decimals: number;\n /** Logo URL */\n iconUrl?: string;\n /** Aggregator sources */\n aggregators?: string[];\n /** Occurrence count in lists */\n occurrences?: number;\n};\n\n/**\n * Cache entry for a chain's token list.\n */\nexport type TokenChainsCacheEntry = {\n /** Timestamp when the cache was last updated */\n timestamp: number;\n /** Token list data: address -> TokenListEntry */\n data: Record<string, TokenListEntry>;\n};\n\n/**\n * Token list state shape (from TokenListController).\n */\nexport type TokenListState = {\n /** Map of chain ID to token list cache entry */\n tokensChainsCache: Record<ChainId, TokenChainsCacheEntry>;\n};\n\n/**\n * Single asset balance entry.\n */\nexport type AssetBalanceEntry = {\n /** Human-readable balance amount */\n amount: string;\n};\n\n/**\n * Assets balance state shape (from AssetsController).\n * Maps accountId -> assetId (CAIP-19) -> balance entry.\n */\nexport type AssetsBalanceState = {\n /** Balance data per account: accountId -> assetId -> balance */\n assetsBalance: Record<string, Record<string, AssetBalanceEntry>>;\n /**\n * User-added custom assets per account: accountId -> CAIP-19 asset IDs.\n * Used to ensure RPC polling refreshes custom assets even when they have\n * no entry in `assetsBalance` yet (e.g. zero balance, first fetch failed).\n */\n customAssets?: Record<string, string[]>;\n};\n"]}
1
+ {"version":3,"file":"state.mjs","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/types/state.ts"],"names":[],"mappings":"","sourcesContent":["import type { ChainId } from './core.js';\n\n/**\n * Single token entry from token list.\n */\nexport type TokenListEntry = {\n /** Contract address */\n address: string;\n /** Token symbol */\n symbol: string;\n /** Token name */\n name: string;\n /** Token decimals */\n decimals: number;\n /** Logo URL */\n iconUrl?: string;\n /** Aggregator sources */\n aggregators?: string[];\n /** Occurrence count in lists */\n occurrences?: number;\n};\n\n/**\n * Cache entry for a chain's token list.\n */\nexport type TokenChainsCacheEntry = {\n /** Timestamp when the cache was last updated */\n timestamp: number;\n /** Token list data: address -> TokenListEntry */\n data: Record<string, TokenListEntry>;\n};\n\n/**\n * Token list state shape (from TokenListController).\n */\nexport type TokenListState = {\n /** Map of chain ID to token list cache entry */\n tokensChainsCache: Record<ChainId, TokenChainsCacheEntry>;\n};\n\n/**\n * Single asset balance entry.\n */\nexport type AssetBalanceEntry = {\n /** Human-readable balance amount */\n amount: string;\n};\n\n/**\n * Assets balance state shape (from AssetsController).\n * Maps accountId -> assetId (CAIP-19) -> balance entry.\n */\nexport type AssetsBalanceState = {\n /** Balance data per account: accountId -> assetId -> balance */\n assetsBalance: Record<string, Record<string, AssetBalanceEntry>>;\n /**\n * User-added custom assets per account: accountId -> CAIP-19 asset IDs.\n * Not read by asset-scoped polls (`BalancePollingInput.assetIds`). Regular\n * polls still include these so v5 supplemental/`customAssetsOnly` refreshes\n * pins that have no `assetsBalance` row yet.\n */\n customAssets?: Record<string, string[]>;\n};\n"]}
@@ -45,6 +45,15 @@ function mergeDataResponses(responses) {
45
45
  ...response.errors,
46
46
  };
47
47
  }
48
+ if (response.unprocessedCustomAssets &&
49
+ response.unprocessedCustomAssets.length > 0) {
50
+ merged.unprocessedCustomAssets = [
51
+ ...new Set([
52
+ ...(merged.unprocessedCustomAssets ?? []),
53
+ ...response.unprocessedCustomAssets,
54
+ ]),
55
+ ];
56
+ }
48
57
  if (response.detectedAssets) {
49
58
  merged.detectedAssets = {
50
59
  ...(merged.detectedAssets ?? {}),
@@ -1 +1 @@
1
- {"version":3,"file":"ParallelMiddleware.cjs","sourceRoot":"","sources":["../../src/middlewares/ParallelMiddleware.ts"],"names":[],"mappings":";;;;;;AAAA,+DAA6B;AAW7B,+EAA+E;AAC/E,eAAe;AACf,+EAA+E;AAE/E;;;;;;GAMG;AACH,SAAgB,kBAAkB,CAAC,SAAyB;IAC1D,MAAM,MAAM,GAAiB,EAAE,CAAC;IAEhC,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;QACjC,IAAI,QAAQ,CAAC,aAAa,EAAE,CAAC;YAC3B,MAAM,CAAC,aAAa,KAApB,MAAM,CAAC,aAAa,GAAK,EAAE,EAAC;YAC5B,KAAK,MAAM,CAAC,SAAS,EAAE,eAAe,CAAC,IAAI,MAAM,CAAC,OAAO,CACvD,QAAQ,CAAC,aAAa,CACvB,EAAE,CAAC;gBACF,MAAM,CAAC,aAAa,CAAC,SAAS,CAAC,GAAG;oBAChC,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC;oBAC1C,GAAG,eAAe;iBACnB,CAAC;YACJ,CAAC;QACH,CAAC;QACD,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC;YACxB,MAAM,CAAC,UAAU,GAAG;gBAClB,GAAG,CAAC,MAAM,CAAC,UAAU,IAAI,EAAE,CAAC;gBAC5B,GAAG,QAAQ,CAAC,UAAU;aACvB,CAAC;QACJ,CAAC;QACD,IAAI,QAAQ,CAAC,WAAW,EAAE,CAAC;YACzB,MAAM,CAAC,WAAW,GAAG;gBACn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,CACT,CAAC;gBACF,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC;gBACtC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,OAAO,EAAE,EAAE,UAAU,EAAE,CAAC;YAC9D,CAAC,CAAC,CACH,CACF,CAAC;YAEF,MAAM,OAAO,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YAC1D,MAAM,cAAc,GAAG,kBAAkB,CACvC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,CACzC,CAAC;YAEF,MAAM,oBAAoB,GAA2B;gBACnD,GAAG,OAAO,CAAC,oBAAoB;aAChC,CAAC;YACF,KAAK,MAAM,EAAE,UAAU,EAAE,UAAU,EAAE,IAAI,YAAY,EAAE,CAAC;gBACtD,oBAAoB,CAAC,GAAG,wBAAwB,IAAI,UAAU,EAAE,CAAC;oBAC/D,UAAU,CAAC;YACf,CAAC;YAED,OAAO,IAAI,CAAC;gBACV,GAAG,OAAO;gBACV,QAAQ,EAAE,kBAAkB,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;gBAChE,oBAAoB;aACrB,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC;AAxDD,4DAwDC","sourcesContent":["import pLimit from 'p-limit';\n\nimport type {\n ChainId,\n Context,\n DataRequest,\n DataResponse,\n Middleware,\n AssetsDataSource,\n} from '../types.js';\n\n// ============================================================================\n// MERGE HELPER\n// ============================================================================\n\n/**\n * Deep-merge multiple DataResponses into one.\n * Used when running balance data sources in parallel.\n *\n * @param responses - Array of DataResponse from each source.\n * @returns Single merged DataResponse.\n */\nexport function mergeDataResponses(responses: DataResponse[]): DataResponse {\n const merged: DataResponse = {};\n\n for (const response of responses) {\n if (response.assetsBalance) {\n merged.assetsBalance ??= {};\n for (const [accountId, accountBalances] of Object.entries(\n response.assetsBalance,\n )) {\n merged.assetsBalance[accountId] = {\n ...(merged.assetsBalance[accountId] ?? {}),\n ...accountBalances,\n };\n }\n }\n if (response.assetsInfo) {\n merged.assetsInfo = {\n ...(merged.assetsInfo ?? {}),\n ...response.assetsInfo,\n };\n }\n if (response.assetsPrice) {\n merged.assetsPrice = {\n ...(merged.assetsPrice ?? {}),\n ...response.assetsPrice,\n };\n }\n if (response.errors) {\n merged.errors = {\n ...(merged.errors ?? {}),\n ...response.errors,\n };\n }\n if (response.detectedAssets) {\n merged.detectedAssets = {\n ...(merged.detectedAssets ?? {}),\n ...response.detectedAssets,\n };\n }\n if (response.updateMode === 'full') {\n merged.updateMode = 'full';\n } else if (\n response.updateMode === 'merge' &&\n merged.updateMode !== 'full'\n ) {\n merged.updateMode = 'merge';\n }\n if (response.replaceCoveredChainBalances) {\n merged.replaceCoveredChainBalances = true;\n }\n }\n merged.updateMode ??= 'merge';\n\n return merged;\n}\n\n// ============================================================================\n// PARALLEL BALANCE MIDDLEWARE\n// ============================================================================\n\nconst PARALLEL_BALANCE_MIDDLEWARE_NAME = 'ParallelBalanceMiddleware';\n\n/** Max concurrent balance source calls (round 1 and fallback). */\nconst BALANCE_CONCURRENCY = 3;\n\nexport type BalanceSource = {\n getName(): string;\n /** Chains this source can fetch (e.g. from getActiveChainsSync()). Used to partition chains with no overlap. */\n getActiveChainsSync(): ChainId[];\n assetsMiddleware: Middleware;\n};\n\n/**\n * Partition request.chainIds so each chain is assigned to exactly one source\n * (by source order: first source that supports the chain gets it). Ensures no\n * chain overlap across data source calls.\n *\n * @param request - The data request with chainIds to partition.\n * @param sources - Balance sources in priority order (e.g. AccountsAPI, Snap, Rpc).\n * @returns Array of requests, one per source, each with only that source's assigned chainIds.\n */\nfunction partitionChainsBySource(\n request: DataRequest,\n sources: BalanceSource[],\n): DataRequest[] {\n const { chainIds } = request;\n const assigned = new Set<ChainId>();\n\n return sources.map((source) => {\n const supported = new Set(source.getActiveChainsSync());\n const chainsForSource = chainIds.filter(\n (id) => supported.has(id) && !assigned.has(id),\n );\n chainsForSource.forEach((id) => assigned.add(id));\n\n return {\n ...request,\n chainIds: chainsForSource,\n };\n });\n}\n\n/**\n * Collect chain IDs that failed in the first round (present in response.errors).\n * Used to run a fallback round with remaining sources.\n *\n * @param requests - Partitioned requests, one per source (same order as results).\n * @param results - Results from each source; chain IDs in requests[i] that have errors in results[i].response.errors are considered failed.\n * @returns Set of chain IDs that had errors in the first round.\n */\nfunction getFailedChainIds(\n requests: DataRequest[],\n results: { response: DataResponse }[],\n): Set<ChainId> {\n const failed = new Set<ChainId>();\n for (let i = 0; i < results.length; i++) {\n const errors = results[i].response.errors ?? {};\n for (const chainId of requests[i].chainIds) {\n if (errors[chainId]) {\n failed.add(chainId);\n }\n }\n }\n return failed;\n}\n\n/**\n * Middleware that runs multiple balance data source middlewares in parallel,\n * with no chain overlap. Chains that fail (response.errors) are re-partitioned\n * and fetched again in a fallback round so lower-priority sources can try them.\n *\n * @param sources - Array of balance sources in priority order (each with getName(), getActiveChainsSync(), assetsMiddleware).\n * @returns A single middleware that runs all sources in parallel and merges responses.\n */\nexport function createParallelBalanceMiddleware(sources: BalanceSource[]): {\n getName(): string;\n assetsMiddleware: Middleware;\n} {\n return {\n getName(): string {\n return PARALLEL_BALANCE_MIDDLEWARE_NAME;\n },\n\n assetsMiddleware: async (context, next): Promise<Context> => {\n if (sources.length === 0) {\n return next(context);\n }\n\n const noopNext = async (ctx: typeof context): Promise<typeof context> =>\n ctx;\n const limit = pLimit(BALANCE_CONCURRENCY);\n\n // Round 1: partition chains (no overlap), run with limited concurrency\n const requests = partitionChainsBySource(context.request, sources);\n const round1Timed = await Promise.all(\n sources.map((source, i) =>\n limit(async () => {\n const start = Date.now();\n const result = await source.assetsMiddleware(\n {\n request: requests[i],\n response: {},\n getAssetsState: context.getAssetsState,\n },\n noopNext,\n );\n const durationMs = Date.now() - start;\n return { result, sourceName: source.getName(), durationMs };\n }),\n ),\n );\n const results = round1Timed.map((entry) => entry.result);\n\n const durationByDataSource: Record<string, number> = {\n ...context.durationByDataSource,\n };\n for (const { sourceName, durationMs } of round1Timed) {\n const key = `${PARALLEL_BALANCE_MIDDLEWARE_NAME}.${sourceName}`;\n durationByDataSource[key] =\n (durationByDataSource[key] ?? 0) + durationMs;\n }\n\n let mergedResponse = mergeDataResponses(\n results.map((result) => result.response),\n );\n\n // Fallback: chains that failed (in errors) get re-partitioned and tried again\n const failedChainIds = getFailedChainIds(requests, results);\n if (failedChainIds.size > 0) {\n const fallbackRequest: DataRequest = {\n ...context.request,\n chainIds: [...failedChainIds],\n };\n const fallbackRequests = partitionChainsBySource(\n fallbackRequest,\n sources,\n );\n const fallbackTimed = await Promise.all(\n sources.map((source, i) =>\n limit(async () => {\n const start = Date.now();\n const result = await source.assetsMiddleware(\n {\n request: fallbackRequests[i],\n response: {},\n getAssetsState: context.getAssetsState,\n },\n noopNext,\n );\n const durationMs = Date.now() - start;\n return { result, sourceName: source.getName(), durationMs };\n }),\n ),\n );\n const fallbackResults = fallbackTimed.map((entry) => entry.result);\n for (const { sourceName, durationMs } of fallbackTimed) {\n const key = `${PARALLEL_BALANCE_MIDDLEWARE_NAME}.${sourceName}`;\n durationByDataSource[key] =\n (durationByDataSource[key] ?? 0) + durationMs;\n }\n const fallbackMerged = mergeDataResponses(\n fallbackResults.map((result) => result.response),\n );\n mergedResponse = mergeDataResponses([mergedResponse, fallbackMerged]);\n // Remove errors for chains we successfully got balance for in fallback\n if (mergedResponse.errors && mergedResponse.assetsBalance) {\n const chainsWithBalance = new Set<ChainId>();\n for (const accountBalances of Object.values(\n mergedResponse.assetsBalance,\n )) {\n for (const assetId of Object.keys(accountBalances)) {\n const chainId = assetId.split('/')[0] as ChainId;\n chainsWithBalance.add(chainId);\n }\n }\n for (const chainId of failedChainIds) {\n if (chainsWithBalance.has(chainId)) {\n delete mergedResponse.errors[chainId];\n }\n }\n }\n }\n\n return next({\n ...context,\n response: mergeDataResponses([context.response, mergedResponse]),\n durationByDataSource,\n });\n },\n };\n}\n\n// ============================================================================\n// PARALLEL TOKEN/PRICE MIDDLEWARE\n// ============================================================================\n\nconst PARALLEL_MIDDLEWARE_NAME = 'ParallelMiddleware';\n\n/** Max concurrent token/price source calls. */\nconst CONCURRENCY = 2;\n\n/**\n * Middleware that runs multiple data source middlewares (e.g. TokenDataSource,\n * PriceDataSource) in parallel with the same request. Responses are merged so\n * that assetsInfo (token metadata) and assetsPrice are combined. Use this to\n * fetch token and price data concurrently instead of sequentially.\n *\n * @param sources - Array of named middleware sources (getName + assetsMiddleware).\n * @returns A single middleware that runs all sources in parallel and merges responses.\n */\nexport function createParallelMiddleware(sources: AssetsDataSource[]): {\n getName(): string;\n assetsMiddleware: Middleware;\n} {\n return {\n getName(): string {\n return PARALLEL_MIDDLEWARE_NAME;\n },\n\n assetsMiddleware: async (context, next): Promise<Context> => {\n if (sources.length === 0) {\n return next(context);\n }\n\n const noopNext = async (ctx: typeof context): Promise<typeof context> =>\n ctx;\n const limit = pLimit(CONCURRENCY);\n\n const timedResults = await Promise.all(\n sources.map((source) =>\n limit(async () => {\n const start = Date.now();\n const result = await source.assetsMiddleware(\n {\n request: context.request,\n response: { ...context.response },\n getAssetsState: context.getAssetsState,\n },\n noopNext,\n );\n const durationMs = Date.now() - start;\n return { result, sourceName: source.getName(), durationMs };\n }),\n ),\n );\n\n const results = timedResults.map((entry) => entry.result);\n const mergedResponse = mergeDataResponses(\n results.map((result) => result.response),\n );\n\n const durationByDataSource: Record<string, number> = {\n ...context.durationByDataSource,\n };\n for (const { sourceName, durationMs } of timedResults) {\n durationByDataSource[`${PARALLEL_MIDDLEWARE_NAME}.${sourceName}`] =\n durationMs;\n }\n\n return next({\n ...context,\n response: mergeDataResponses([context.response, mergedResponse]),\n durationByDataSource,\n });\n },\n };\n}\n"]}
1
+ {"version":3,"file":"ParallelMiddleware.cjs","sourceRoot":"","sources":["../../src/middlewares/ParallelMiddleware.ts"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,GAAG,KAAK,CAAC;gBACtC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,OAAO,EAAE,EAAE,UAAU,EAAE,CAAC;YAC9D,CAAC,CAAC,CACH,CACF,CAAC;YAEF,MAAM,OAAO,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YAC1D,MAAM,cAAc,GAAG,kBAAkB,CACvC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,CACzC,CAAC;YAEF,MAAM,oBAAoB,GAA2B;gBACnD,GAAG,OAAO,CAAC,oBAAoB;aAChC,CAAC;YACF,KAAK,MAAM,EAAE,UAAU,EAAE,UAAU,EAAE,IAAI,YAAY,EAAE,CAAC;gBACtD,oBAAoB,CAAC,GAAG,wBAAwB,IAAI,UAAU,EAAE,CAAC;oBAC/D,UAAU,CAAC;YACf,CAAC;YAED,OAAO,IAAI,CAAC;gBACV,GAAG,OAAO;gBACV,QAAQ,EAAE,kBAAkB,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;gBAChE,oBAAoB;aACrB,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC;AAxDD,4DAwDC","sourcesContent":["import pLimit from 'p-limit';\n\nimport type {\n ChainId,\n Context,\n DataRequest,\n DataResponse,\n Middleware,\n AssetsDataSource,\n} from '../types.js';\n\n// ============================================================================\n// MERGE HELPER\n// ============================================================================\n\n/**\n * Deep-merge multiple DataResponses into one.\n * Used when running balance data sources in parallel.\n *\n * @param responses - Array of DataResponse from each source.\n * @returns Single merged DataResponse.\n */\nexport function mergeDataResponses(responses: DataResponse[]): DataResponse {\n const merged: DataResponse = {};\n\n for (const response of responses) {\n if (response.assetsBalance) {\n merged.assetsBalance ??= {};\n for (const [accountId, accountBalances] of Object.entries(\n response.assetsBalance,\n )) {\n merged.assetsBalance[accountId] = {\n ...(merged.assetsBalance[accountId] ?? {}),\n ...accountBalances,\n };\n }\n }\n if (response.assetsInfo) {\n merged.assetsInfo = {\n ...(merged.assetsInfo ?? {}),\n ...response.assetsInfo,\n };\n }\n if (response.assetsPrice) {\n merged.assetsPrice = {\n ...(merged.assetsPrice ?? {}),\n ...response.assetsPrice,\n };\n }\n if (response.errors) {\n merged.errors = {\n ...(merged.errors ?? {}),\n ...response.errors,\n };\n }\n if (\n response.unprocessedCustomAssets &&\n response.unprocessedCustomAssets.length > 0\n ) {\n merged.unprocessedCustomAssets = [\n ...new Set([\n ...(merged.unprocessedCustomAssets ?? []),\n ...response.unprocessedCustomAssets,\n ]),\n ];\n }\n if (response.detectedAssets) {\n merged.detectedAssets = {\n ...(merged.detectedAssets ?? {}),\n ...response.detectedAssets,\n };\n }\n if (response.updateMode === 'full') {\n merged.updateMode = 'full';\n } else if (\n response.updateMode === 'merge' &&\n merged.updateMode !== 'full'\n ) {\n merged.updateMode = 'merge';\n }\n if (response.replaceCoveredChainBalances) {\n merged.replaceCoveredChainBalances = true;\n }\n }\n merged.updateMode ??= 'merge';\n\n return merged;\n}\n\n// ============================================================================\n// PARALLEL BALANCE MIDDLEWARE\n// ============================================================================\n\nconst PARALLEL_BALANCE_MIDDLEWARE_NAME = 'ParallelBalanceMiddleware';\n\n/** Max concurrent balance source calls (round 1 and fallback). */\nconst BALANCE_CONCURRENCY = 3;\n\nexport type BalanceSource = {\n getName(): string;\n /** Chains this source can fetch (e.g. from getActiveChainsSync()). Used to partition chains with no overlap. */\n getActiveChainsSync(): ChainId[];\n assetsMiddleware: Middleware;\n};\n\n/**\n * Partition request.chainIds so each chain is assigned to exactly one source\n * (by source order: first source that supports the chain gets it). Ensures no\n * chain overlap across data source calls.\n *\n * @param request - The data request with chainIds to partition.\n * @param sources - Balance sources in priority order (e.g. AccountsAPI, Snap, Rpc).\n * @returns Array of requests, one per source, each with only that source's assigned chainIds.\n */\nfunction partitionChainsBySource(\n request: DataRequest,\n sources: BalanceSource[],\n): DataRequest[] {\n const { chainIds } = request;\n const assigned = new Set<ChainId>();\n\n return sources.map((source) => {\n const supported = new Set(source.getActiveChainsSync());\n const chainsForSource = chainIds.filter(\n (id) => supported.has(id) && !assigned.has(id),\n );\n chainsForSource.forEach((id) => assigned.add(id));\n\n return {\n ...request,\n chainIds: chainsForSource,\n };\n });\n}\n\n/**\n * Collect chain IDs that failed in the first round (present in response.errors).\n * Used to run a fallback round with remaining sources.\n *\n * @param requests - Partitioned requests, one per source (same order as results).\n * @param results - Results from each source; chain IDs in requests[i] that have errors in results[i].response.errors are considered failed.\n * @returns Set of chain IDs that had errors in the first round.\n */\nfunction getFailedChainIds(\n requests: DataRequest[],\n results: { response: DataResponse }[],\n): Set<ChainId> {\n const failed = new Set<ChainId>();\n for (let i = 0; i < results.length; i++) {\n const errors = results[i].response.errors ?? {};\n for (const chainId of requests[i].chainIds) {\n if (errors[chainId]) {\n failed.add(chainId);\n }\n }\n }\n return failed;\n}\n\n/**\n * Middleware that runs multiple balance data source middlewares in parallel,\n * with no chain overlap. Chains that fail (response.errors) are re-partitioned\n * and fetched again in a fallback round so lower-priority sources can try them.\n *\n * @param sources - Array of balance sources in priority order (each with getName(), getActiveChainsSync(), assetsMiddleware).\n * @returns A single middleware that runs all sources in parallel and merges responses.\n */\nexport function createParallelBalanceMiddleware(sources: BalanceSource[]): {\n getName(): string;\n assetsMiddleware: Middleware;\n} {\n return {\n getName(): string {\n return PARALLEL_BALANCE_MIDDLEWARE_NAME;\n },\n\n assetsMiddleware: async (context, next): Promise<Context> => {\n if (sources.length === 0) {\n return next(context);\n }\n\n const noopNext = async (ctx: typeof context): Promise<typeof context> =>\n ctx;\n const limit = pLimit(BALANCE_CONCURRENCY);\n\n // Round 1: partition chains (no overlap), run with limited concurrency\n const requests = partitionChainsBySource(context.request, sources);\n const round1Timed = await Promise.all(\n sources.map((source, i) =>\n limit(async () => {\n const start = Date.now();\n const result = await source.assetsMiddleware(\n {\n request: requests[i],\n response: {},\n getAssetsState: context.getAssetsState,\n },\n noopNext,\n );\n const durationMs = Date.now() - start;\n return { result, sourceName: source.getName(), durationMs };\n }),\n ),\n );\n const results = round1Timed.map((entry) => entry.result);\n\n const durationByDataSource: Record<string, number> = {\n ...context.durationByDataSource,\n };\n for (const { sourceName, durationMs } of round1Timed) {\n const key = `${PARALLEL_BALANCE_MIDDLEWARE_NAME}.${sourceName}`;\n durationByDataSource[key] =\n (durationByDataSource[key] ?? 0) + durationMs;\n }\n\n let mergedResponse = mergeDataResponses(\n results.map((result) => result.response),\n );\n\n // Fallback: chains that failed (in errors) get re-partitioned and tried again\n const failedChainIds = getFailedChainIds(requests, results);\n if (failedChainIds.size > 0) {\n const fallbackRequest: DataRequest = {\n ...context.request,\n chainIds: [...failedChainIds],\n };\n const fallbackRequests = partitionChainsBySource(\n fallbackRequest,\n sources,\n );\n const fallbackTimed = await Promise.all(\n sources.map((source, i) =>\n limit(async () => {\n const start = Date.now();\n const result = await source.assetsMiddleware(\n {\n request: fallbackRequests[i],\n response: {},\n getAssetsState: context.getAssetsState,\n },\n noopNext,\n );\n const durationMs = Date.now() - start;\n return { result, sourceName: source.getName(), durationMs };\n }),\n ),\n );\n const fallbackResults = fallbackTimed.map((entry) => entry.result);\n for (const { sourceName, durationMs } of fallbackTimed) {\n const key = `${PARALLEL_BALANCE_MIDDLEWARE_NAME}.${sourceName}`;\n durationByDataSource[key] =\n (durationByDataSource[key] ?? 0) + durationMs;\n }\n const fallbackMerged = mergeDataResponses(\n fallbackResults.map((result) => result.response),\n );\n mergedResponse = mergeDataResponses([mergedResponse, fallbackMerged]);\n // Remove errors for chains we successfully got balance for in fallback\n if (mergedResponse.errors && mergedResponse.assetsBalance) {\n const chainsWithBalance = new Set<ChainId>();\n for (const accountBalances of Object.values(\n mergedResponse.assetsBalance,\n )) {\n for (const assetId of Object.keys(accountBalances)) {\n const chainId = assetId.split('/')[0] as ChainId;\n chainsWithBalance.add(chainId);\n }\n }\n for (const chainId of failedChainIds) {\n if (chainsWithBalance.has(chainId)) {\n delete mergedResponse.errors[chainId];\n }\n }\n }\n }\n\n return next({\n ...context,\n response: mergeDataResponses([context.response, mergedResponse]),\n durationByDataSource,\n });\n },\n };\n}\n\n// ============================================================================\n// PARALLEL TOKEN/PRICE MIDDLEWARE\n// ============================================================================\n\nconst PARALLEL_MIDDLEWARE_NAME = 'ParallelMiddleware';\n\n/** Max concurrent token/price source calls. */\nconst CONCURRENCY = 2;\n\n/**\n * Middleware that runs multiple data source middlewares (e.g. TokenDataSource,\n * PriceDataSource) in parallel with the same request. Responses are merged so\n * that assetsInfo (token metadata) and assetsPrice are combined. Use this to\n * fetch token and price data concurrently instead of sequentially.\n *\n * @param sources - Array of named middleware sources (getName + assetsMiddleware).\n * @returns A single middleware that runs all sources in parallel and merges responses.\n */\nexport function createParallelMiddleware(sources: AssetsDataSource[]): {\n getName(): string;\n assetsMiddleware: Middleware;\n} {\n return {\n getName(): string {\n return PARALLEL_MIDDLEWARE_NAME;\n },\n\n assetsMiddleware: async (context, next): Promise<Context> => {\n if (sources.length === 0) {\n return next(context);\n }\n\n const noopNext = async (ctx: typeof context): Promise<typeof context> =>\n ctx;\n const limit = pLimit(CONCURRENCY);\n\n const timedResults = await Promise.all(\n sources.map((source) =>\n limit(async () => {\n const start = Date.now();\n const result = await source.assetsMiddleware(\n {\n request: context.request,\n response: { ...context.response },\n getAssetsState: context.getAssetsState,\n },\n noopNext,\n );\n const durationMs = Date.now() - start;\n return { result, sourceName: source.getName(), durationMs };\n }),\n ),\n );\n\n const results = timedResults.map((entry) => entry.result);\n const mergedResponse = mergeDataResponses(\n results.map((result) => result.response),\n );\n\n const durationByDataSource: Record<string, number> = {\n ...context.durationByDataSource,\n };\n for (const { sourceName, durationMs } of timedResults) {\n durationByDataSource[`${PARALLEL_MIDDLEWARE_NAME}.${sourceName}`] =\n durationMs;\n }\n\n return next({\n ...context,\n response: mergeDataResponses([context.response, mergedResponse]),\n durationByDataSource,\n });\n },\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ParallelMiddleware.d.cts","sourceRoot":"","sources":["../../src/middlewares/ParallelMiddleware.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,OAAO,EAGP,YAAY,EACZ,UAAU,EACV,gBAAgB,EACjB,qBAAoB;AAMrB;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,YAAY,EAAE,GAAG,YAAY,CAsD1E;AAWD,MAAM,MAAM,aAAa,GAAG;IAC1B,OAAO,IAAI,MAAM,CAAC;IAClB,gHAAgH;IAChH,mBAAmB,IAAI,OAAO,EAAE,CAAC;IACjC,gBAAgB,EAAE,UAAU,CAAC;CAC9B,CAAC;AAwDF;;;;;;;GAOG;AACH,wBAAgB,+BAA+B,CAAC,OAAO,EAAE,aAAa,EAAE,GAAG;IACzE,OAAO,IAAI,MAAM,CAAC;IAClB,gBAAgB,EAAE,UAAU,CAAC;CAC9B,CAiHA;AAWD;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,gBAAgB,EAAE,GAAG;IACrE,OAAO,IAAI,MAAM,CAAC;IAClB,gBAAgB,EAAE,UAAU,CAAC;CAC9B,CAqDA"}
1
+ {"version":3,"file":"ParallelMiddleware.d.cts","sourceRoot":"","sources":["../../src/middlewares/ParallelMiddleware.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,OAAO,EAGP,YAAY,EACZ,UAAU,EACV,gBAAgB,EACjB,qBAAoB;AAMrB;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,YAAY,EAAE,GAAG,YAAY,CAiE1E;AAWD,MAAM,MAAM,aAAa,GAAG;IAC1B,OAAO,IAAI,MAAM,CAAC;IAClB,gHAAgH;IAChH,mBAAmB,IAAI,OAAO,EAAE,CAAC;IACjC,gBAAgB,EAAE,UAAU,CAAC;CAC9B,CAAC;AAwDF;;;;;;;GAOG;AACH,wBAAgB,+BAA+B,CAAC,OAAO,EAAE,aAAa,EAAE,GAAG;IACzE,OAAO,IAAI,MAAM,CAAC;IAClB,gBAAgB,EAAE,UAAU,CAAC;CAC9B,CAiHA;AAWD;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,gBAAgB,EAAE,GAAG;IACrE,OAAO,IAAI,MAAM,CAAC;IAClB,gBAAgB,EAAE,UAAU,CAAC;CAC9B,CAqDA"}
@@ -1 +1 @@
1
- {"version":3,"file":"ParallelMiddleware.d.mts","sourceRoot":"","sources":["../../src/middlewares/ParallelMiddleware.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,OAAO,EAGP,YAAY,EACZ,UAAU,EACV,gBAAgB,EACjB,qBAAoB;AAMrB;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,YAAY,EAAE,GAAG,YAAY,CAsD1E;AAWD,MAAM,MAAM,aAAa,GAAG;IAC1B,OAAO,IAAI,MAAM,CAAC;IAClB,gHAAgH;IAChH,mBAAmB,IAAI,OAAO,EAAE,CAAC;IACjC,gBAAgB,EAAE,UAAU,CAAC;CAC9B,CAAC;AAwDF;;;;;;;GAOG;AACH,wBAAgB,+BAA+B,CAAC,OAAO,EAAE,aAAa,EAAE,GAAG;IACzE,OAAO,IAAI,MAAM,CAAC;IAClB,gBAAgB,EAAE,UAAU,CAAC;CAC9B,CAiHA;AAWD;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,gBAAgB,EAAE,GAAG;IACrE,OAAO,IAAI,MAAM,CAAC;IAClB,gBAAgB,EAAE,UAAU,CAAC;CAC9B,CAqDA"}
1
+ {"version":3,"file":"ParallelMiddleware.d.mts","sourceRoot":"","sources":["../../src/middlewares/ParallelMiddleware.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,OAAO,EAGP,YAAY,EACZ,UAAU,EACV,gBAAgB,EACjB,qBAAoB;AAMrB;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,YAAY,EAAE,GAAG,YAAY,CAiE1E;AAWD,MAAM,MAAM,aAAa,GAAG;IAC1B,OAAO,IAAI,MAAM,CAAC;IAClB,gHAAgH;IAChH,mBAAmB,IAAI,OAAO,EAAE,CAAC;IACjC,gBAAgB,EAAE,UAAU,CAAC;CAC9B,CAAC;AAwDF;;;;;;;GAOG;AACH,wBAAgB,+BAA+B,CAAC,OAAO,EAAE,aAAa,EAAE,GAAG;IACzE,OAAO,IAAI,MAAM,CAAC;IAClB,gBAAgB,EAAE,UAAU,CAAC;CAC9B,CAiHA;AAWD;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,gBAAgB,EAAE,GAAG;IACrE,OAAO,IAAI,MAAM,CAAC;IAClB,gBAAgB,EAAE,UAAU,CAAC;CAC9B,CAqDA"}
@@ -46,6 +46,15 @@ export function mergeDataResponses(responses) {
46
46
  ...response.errors,
47
47
  };
48
48
  }
49
+ if (response.unprocessedCustomAssets &&
50
+ response.unprocessedCustomAssets.length > 0) {
51
+ merged.unprocessedCustomAssets = [
52
+ ...new Set([
53
+ ...(merged.unprocessedCustomAssets ?? []),
54
+ ...response.unprocessedCustomAssets,
55
+ ]),
56
+ ];
57
+ }
49
58
  if (response.detectedAssets) {
50
59
  merged.detectedAssets = {
51
60
  ...(merged.detectedAssets ?? {}),
@@ -1 +1 @@
1
- {"version":3,"file":"ParallelMiddleware.mjs","sourceRoot":"","sources":["../../src/middlewares/ParallelMiddleware.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,OAAM,yBAAgB;;AAW7B,+EAA+E;AAC/E,eAAe;AACf,+EAA+E;AAE/E;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAAC,SAAyB;IAC1D,MAAM,MAAM,GAAiB,EAAE,CAAC;IAEhC,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;QACjC,IAAI,QAAQ,CAAC,aAAa,EAAE,CAAC;YAC3B,M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AC/D,UAAU,CAAC;YACf,CAAC;YAED,OAAO,IAAI,CAAC;gBACV,GAAG,OAAO;gBACV,QAAQ,EAAE,kBAAkB,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;gBAChE,oBAAoB;aACrB,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import pLimit from 'p-limit';\n\nimport type {\n ChainId,\n Context,\n DataRequest,\n DataResponse,\n Middleware,\n AssetsDataSource,\n} from '../types.js';\n\n// ============================================================================\n// MERGE HELPER\n// ============================================================================\n\n/**\n * Deep-merge multiple DataResponses into one.\n * Used when running balance data sources in parallel.\n *\n * @param responses - Array of DataResponse from each source.\n * @returns Single merged DataResponse.\n */\nexport function mergeDataResponses(responses: DataResponse[]): DataResponse {\n const merged: DataResponse = {};\n\n for (const response of responses) {\n if (response.assetsBalance) {\n merged.assetsBalance ??= {};\n for (const [accountId, accountBalances] of Object.entries(\n response.assetsBalance,\n )) {\n merged.assetsBalance[accountId] = {\n ...(merged.assetsBalance[accountId] ?? {}),\n ...accountBalances,\n };\n }\n }\n if (response.assetsInfo) {\n merged.assetsInfo = {\n ...(merged.assetsInfo ?? {}),\n ...response.assetsInfo,\n };\n }\n if (response.assetsPrice) {\n merged.assetsPrice = {\n ...(merged.assetsPrice ?? {}),\n ...response.assetsPrice,\n };\n }\n if (response.errors) {\n merged.errors = {\n ...(merged.errors ?? {}),\n ...response.errors,\n };\n }\n if (response.detectedAssets) {\n merged.detectedAssets = {\n ...(merged.detectedAssets ?? {}),\n ...response.detectedAssets,\n };\n }\n if (response.updateMode === 'full') {\n merged.updateMode = 'full';\n } else if (\n response.updateMode === 'merge' &&\n merged.updateMode !== 'full'\n ) {\n merged.updateMode = 'merge';\n }\n if (response.replaceCoveredChainBalances) {\n merged.replaceCoveredChainBalances = true;\n }\n }\n merged.updateMode ??= 'merge';\n\n return merged;\n}\n\n// ============================================================================\n// PARALLEL BALANCE MIDDLEWARE\n// ============================================================================\n\nconst PARALLEL_BALANCE_MIDDLEWARE_NAME = 'ParallelBalanceMiddleware';\n\n/** Max concurrent balance source calls (round 1 and fallback). */\nconst BALANCE_CONCURRENCY = 3;\n\nexport type BalanceSource = {\n getName(): string;\n /** Chains this source can fetch (e.g. from getActiveChainsSync()). Used to partition chains with no overlap. */\n getActiveChainsSync(): ChainId[];\n assetsMiddleware: Middleware;\n};\n\n/**\n * Partition request.chainIds so each chain is assigned to exactly one source\n * (by source order: first source that supports the chain gets it). Ensures no\n * chain overlap across data source calls.\n *\n * @param request - The data request with chainIds to partition.\n * @param sources - Balance sources in priority order (e.g. AccountsAPI, Snap, Rpc).\n * @returns Array of requests, one per source, each with only that source's assigned chainIds.\n */\nfunction partitionChainsBySource(\n request: DataRequest,\n sources: BalanceSource[],\n): DataRequest[] {\n const { chainIds } = request;\n const assigned = new Set<ChainId>();\n\n return sources.map((source) => {\n const supported = new Set(source.getActiveChainsSync());\n const chainsForSource = chainIds.filter(\n (id) => supported.has(id) && !assigned.has(id),\n );\n chainsForSource.forEach((id) => assigned.add(id));\n\n return {\n ...request,\n chainIds: chainsForSource,\n };\n });\n}\n\n/**\n * Collect chain IDs that failed in the first round (present in response.errors).\n * Used to run a fallback round with remaining sources.\n *\n * @param requests - Partitioned requests, one per source (same order as results).\n * @param results - Results from each source; chain IDs in requests[i] that have errors in results[i].response.errors are considered failed.\n * @returns Set of chain IDs that had errors in the first round.\n */\nfunction getFailedChainIds(\n requests: DataRequest[],\n results: { response: DataResponse }[],\n): Set<ChainId> {\n const failed = new Set<ChainId>();\n for (let i = 0; i < results.length; i++) {\n const errors = results[i].response.errors ?? {};\n for (const chainId of requests[i].chainIds) {\n if (errors[chainId]) {\n failed.add(chainId);\n }\n }\n }\n return failed;\n}\n\n/**\n * Middleware that runs multiple balance data source middlewares in parallel,\n * with no chain overlap. Chains that fail (response.errors) are re-partitioned\n * and fetched again in a fallback round so lower-priority sources can try them.\n *\n * @param sources - Array of balance sources in priority order (each with getName(), getActiveChainsSync(), assetsMiddleware).\n * @returns A single middleware that runs all sources in parallel and merges responses.\n */\nexport function createParallelBalanceMiddleware(sources: BalanceSource[]): {\n getName(): string;\n assetsMiddleware: Middleware;\n} {\n return {\n getName(): string {\n return PARALLEL_BALANCE_MIDDLEWARE_NAME;\n },\n\n assetsMiddleware: async (context, next): Promise<Context> => {\n if (sources.length === 0) {\n return next(context);\n }\n\n const noopNext = async (ctx: typeof context): Promise<typeof context> =>\n ctx;\n const limit = pLimit(BALANCE_CONCURRENCY);\n\n // Round 1: partition chains (no overlap), run with limited concurrency\n const requests = partitionChainsBySource(context.request, sources);\n const round1Timed = await Promise.all(\n sources.map((source, i) =>\n limit(async () => {\n const start = Date.now();\n const result = await source.assetsMiddleware(\n {\n request: requests[i],\n response: {},\n getAssetsState: context.getAssetsState,\n },\n noopNext,\n );\n const durationMs = Date.now() - start;\n return { result, sourceName: source.getName(), durationMs };\n }),\n ),\n );\n const results = round1Timed.map((entry) => entry.result);\n\n const durationByDataSource: Record<string, number> = {\n ...context.durationByDataSource,\n };\n for (const { sourceName, durationMs } of round1Timed) {\n const key = `${PARALLEL_BALANCE_MIDDLEWARE_NAME}.${sourceName}`;\n durationByDataSource[key] =\n (durationByDataSource[key] ?? 0) + durationMs;\n }\n\n let mergedResponse = mergeDataResponses(\n results.map((result) => result.response),\n );\n\n // Fallback: chains that failed (in errors) get re-partitioned and tried again\n const failedChainIds = getFailedChainIds(requests, results);\n if (failedChainIds.size > 0) {\n const fallbackRequest: DataRequest = {\n ...context.request,\n chainIds: [...failedChainIds],\n };\n const fallbackRequests = partitionChainsBySource(\n fallbackRequest,\n sources,\n );\n const fallbackTimed = await Promise.all(\n sources.map((source, i) =>\n limit(async () => {\n const start = Date.now();\n const result = await source.assetsMiddleware(\n {\n request: fallbackRequests[i],\n response: {},\n getAssetsState: context.getAssetsState,\n },\n noopNext,\n );\n const durationMs = Date.now() - start;\n return { result, sourceName: source.getName(), durationMs };\n }),\n ),\n );\n const fallbackResults = fallbackTimed.map((entry) => entry.result);\n for (const { sourceName, durationMs } of fallbackTimed) {\n const key = `${PARALLEL_BALANCE_MIDDLEWARE_NAME}.${sourceName}`;\n durationByDataSource[key] =\n (durationByDataSource[key] ?? 0) + durationMs;\n }\n const fallbackMerged = mergeDataResponses(\n fallbackResults.map((result) => result.response),\n );\n mergedResponse = mergeDataResponses([mergedResponse, fallbackMerged]);\n // Remove errors for chains we successfully got balance for in fallback\n if (mergedResponse.errors && mergedResponse.assetsBalance) {\n const chainsWithBalance = new Set<ChainId>();\n for (const accountBalances of Object.values(\n mergedResponse.assetsBalance,\n )) {\n for (const assetId of Object.keys(accountBalances)) {\n const chainId = assetId.split('/')[0] as ChainId;\n chainsWithBalance.add(chainId);\n }\n }\n for (const chainId of failedChainIds) {\n if (chainsWithBalance.has(chainId)) {\n delete mergedResponse.errors[chainId];\n }\n }\n }\n }\n\n return next({\n ...context,\n response: mergeDataResponses([context.response, mergedResponse]),\n durationByDataSource,\n });\n },\n };\n}\n\n// ============================================================================\n// PARALLEL TOKEN/PRICE MIDDLEWARE\n// ============================================================================\n\nconst PARALLEL_MIDDLEWARE_NAME = 'ParallelMiddleware';\n\n/** Max concurrent token/price source calls. */\nconst CONCURRENCY = 2;\n\n/**\n * Middleware that runs multiple data source middlewares (e.g. TokenDataSource,\n * PriceDataSource) in parallel with the same request. Responses are merged so\n * that assetsInfo (token metadata) and assetsPrice are combined. Use this to\n * fetch token and price data concurrently instead of sequentially.\n *\n * @param sources - Array of named middleware sources (getName + assetsMiddleware).\n * @returns A single middleware that runs all sources in parallel and merges responses.\n */\nexport function createParallelMiddleware(sources: AssetsDataSource[]): {\n getName(): string;\n assetsMiddleware: Middleware;\n} {\n return {\n getName(): string {\n return PARALLEL_MIDDLEWARE_NAME;\n },\n\n assetsMiddleware: async (context, next): Promise<Context> => {\n if (sources.length === 0) {\n return next(context);\n }\n\n const noopNext = async (ctx: typeof context): Promise<typeof context> =>\n ctx;\n const limit = pLimit(CONCURRENCY);\n\n const timedResults = await Promise.all(\n sources.map((source) =>\n limit(async () => {\n const start = Date.now();\n const result = await source.assetsMiddleware(\n {\n request: context.request,\n response: { ...context.response },\n getAssetsState: context.getAssetsState,\n },\n noopNext,\n );\n const durationMs = Date.now() - start;\n return { result, sourceName: source.getName(), durationMs };\n }),\n ),\n );\n\n const results = timedResults.map((entry) => entry.result);\n const mergedResponse = mergeDataResponses(\n results.map((result) => result.response),\n );\n\n const durationByDataSource: Record<string, number> = {\n ...context.durationByDataSource,\n };\n for (const { sourceName, durationMs } of timedResults) {\n durationByDataSource[`${PARALLEL_MIDDLEWARE_NAME}.${sourceName}`] =\n durationMs;\n }\n\n return next({\n ...context,\n response: mergeDataResponses([context.response, mergedResponse]),\n durationByDataSource,\n });\n },\n };\n}\n"]}
1
+ {"version":3,"file":"ParallelMiddleware.mjs","sourceRoot":"","sources":["../../src/middlewares/ParallelMiddleware.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,OAAM,yBAAgB;;AAW7B,+EAA+E;AAC/E,eAAe;AACf,+EAA+E;AAE/E;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAAC,SAAyB;IAC1D,MAAM,MAAM,GAAiB,EAAE,CAAC;IAEhC,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;QACjC,IAAI,QAAQ,CAAC,aAAa,EAAE,CAAC;YAC3B,MAAM,CAAC,aAAa,KAApB,MAAM,CAAC,aAAa,GAAK,EAAE,EAAC;YAC5B,KAAK,MAAM,CAAC,SAAS,EAAE,eAAe,CAAC,IAAI,MAAM,CAAC,OAAO,CACvD,QAAQ,CAAC,aAAa,CACvB,EAAE,CAAC;gBACF,MAAM,CAAC,aAAa,CAAC,SAAS,CAAC,GAAG;oBAChC,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC;oBAC1C,GAAG,eAAe;iBACnB,CAAC;YACJ,CAAC;QACH,CAAC;QACD,IAAI,QAAQ,CAAC,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BAAkB,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;gBAChE,oBAAoB;aACrB,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import pLimit from 'p-limit';\n\nimport type {\n ChainId,\n Context,\n DataRequest,\n DataResponse,\n Middleware,\n AssetsDataSource,\n} from '../types.js';\n\n// ============================================================================\n// MERGE HELPER\n// ============================================================================\n\n/**\n * Deep-merge multiple DataResponses into one.\n * Used when running balance data sources in parallel.\n *\n * @param responses - Array of DataResponse from each source.\n * @returns Single merged DataResponse.\n */\nexport function mergeDataResponses(responses: DataResponse[]): DataResponse {\n const merged: DataResponse = {};\n\n for (const response of responses) {\n if (response.assetsBalance) {\n merged.assetsBalance ??= {};\n for (const [accountId, accountBalances] of Object.entries(\n response.assetsBalance,\n )) {\n merged.assetsBalance[accountId] = {\n ...(merged.assetsBalance[accountId] ?? {}),\n ...accountBalances,\n };\n }\n }\n if (response.assetsInfo) {\n merged.assetsInfo = {\n ...(merged.assetsInfo ?? {}),\n ...response.assetsInfo,\n };\n }\n if (response.assetsPrice) {\n merged.assetsPrice = {\n ...(merged.assetsPrice ?? {}),\n ...response.assetsPrice,\n };\n }\n if (response.errors) {\n merged.errors = {\n ...(merged.errors ?? {}),\n ...response.errors,\n };\n }\n if (\n response.unprocessedCustomAssets &&\n response.unprocessedCustomAssets.length > 0\n ) {\n merged.unprocessedCustomAssets = [\n ...new Set([\n ...(merged.unprocessedCustomAssets ?? []),\n ...response.unprocessedCustomAssets,\n ]),\n ];\n }\n if (response.detectedAssets) {\n merged.detectedAssets = {\n ...(merged.detectedAssets ?? {}),\n ...response.detectedAssets,\n };\n }\n if (response.updateMode === 'full') {\n merged.updateMode = 'full';\n } else if (\n response.updateMode === 'merge' &&\n merged.updateMode !== 'full'\n ) {\n merged.updateMode = 'merge';\n }\n if (response.replaceCoveredChainBalances) {\n merged.replaceCoveredChainBalances = true;\n }\n }\n merged.updateMode ??= 'merge';\n\n return merged;\n}\n\n// ============================================================================\n// PARALLEL BALANCE MIDDLEWARE\n// ============================================================================\n\nconst PARALLEL_BALANCE_MIDDLEWARE_NAME = 'ParallelBalanceMiddleware';\n\n/** Max concurrent balance source calls (round 1 and fallback). */\nconst BALANCE_CONCURRENCY = 3;\n\nexport type BalanceSource = {\n getName(): string;\n /** Chains this source can fetch (e.g. from getActiveChainsSync()). Used to partition chains with no overlap. */\n getActiveChainsSync(): ChainId[];\n assetsMiddleware: Middleware;\n};\n\n/**\n * Partition request.chainIds so each chain is assigned to exactly one source\n * (by source order: first source that supports the chain gets it). Ensures no\n * chain overlap across data source calls.\n *\n * @param request - The data request with chainIds to partition.\n * @param sources - Balance sources in priority order (e.g. AccountsAPI, Snap, Rpc).\n * @returns Array of requests, one per source, each with only that source's assigned chainIds.\n */\nfunction partitionChainsBySource(\n request: DataRequest,\n sources: BalanceSource[],\n): DataRequest[] {\n const { chainIds } = request;\n const assigned = new Set<ChainId>();\n\n return sources.map((source) => {\n const supported = new Set(source.getActiveChainsSync());\n const chainsForSource = chainIds.filter(\n (id) => supported.has(id) && !assigned.has(id),\n );\n chainsForSource.forEach((id) => assigned.add(id));\n\n return {\n ...request,\n chainIds: chainsForSource,\n };\n });\n}\n\n/**\n * Collect chain IDs that failed in the first round (present in response.errors).\n * Used to run a fallback round with remaining sources.\n *\n * @param requests - Partitioned requests, one per source (same order as results).\n * @param results - Results from each source; chain IDs in requests[i] that have errors in results[i].response.errors are considered failed.\n * @returns Set of chain IDs that had errors in the first round.\n */\nfunction getFailedChainIds(\n requests: DataRequest[],\n results: { response: DataResponse }[],\n): Set<ChainId> {\n const failed = new Set<ChainId>();\n for (let i = 0; i < results.length; i++) {\n const errors = results[i].response.errors ?? {};\n for (const chainId of requests[i].chainIds) {\n if (errors[chainId]) {\n failed.add(chainId);\n }\n }\n }\n return failed;\n}\n\n/**\n * Middleware that runs multiple balance data source middlewares in parallel,\n * with no chain overlap. Chains that fail (response.errors) are re-partitioned\n * and fetched again in a fallback round so lower-priority sources can try them.\n *\n * @param sources - Array of balance sources in priority order (each with getName(), getActiveChainsSync(), assetsMiddleware).\n * @returns A single middleware that runs all sources in parallel and merges responses.\n */\nexport function createParallelBalanceMiddleware(sources: BalanceSource[]): {\n getName(): string;\n assetsMiddleware: Middleware;\n} {\n return {\n getName(): string {\n return PARALLEL_BALANCE_MIDDLEWARE_NAME;\n },\n\n assetsMiddleware: async (context, next): Promise<Context> => {\n if (sources.length === 0) {\n return next(context);\n }\n\n const noopNext = async (ctx: typeof context): Promise<typeof context> =>\n ctx;\n const limit = pLimit(BALANCE_CONCURRENCY);\n\n // Round 1: partition chains (no overlap), run with limited concurrency\n const requests = partitionChainsBySource(context.request, sources);\n const round1Timed = await Promise.all(\n sources.map((source, i) =>\n limit(async () => {\n const start = Date.now();\n const result = await source.assetsMiddleware(\n {\n request: requests[i],\n response: {},\n getAssetsState: context.getAssetsState,\n },\n noopNext,\n );\n const durationMs = Date.now() - start;\n return { result, sourceName: source.getName(), durationMs };\n }),\n ),\n );\n const results = round1Timed.map((entry) => entry.result);\n\n const durationByDataSource: Record<string, number> = {\n ...context.durationByDataSource,\n };\n for (const { sourceName, durationMs } of round1Timed) {\n const key = `${PARALLEL_BALANCE_MIDDLEWARE_NAME}.${sourceName}`;\n durationByDataSource[key] =\n (durationByDataSource[key] ?? 0) + durationMs;\n }\n\n let mergedResponse = mergeDataResponses(\n results.map((result) => result.response),\n );\n\n // Fallback: chains that failed (in errors) get re-partitioned and tried again\n const failedChainIds = getFailedChainIds(requests, results);\n if (failedChainIds.size > 0) {\n const fallbackRequest: DataRequest = {\n ...context.request,\n chainIds: [...failedChainIds],\n };\n const fallbackRequests = partitionChainsBySource(\n fallbackRequest,\n sources,\n );\n const fallbackTimed = await Promise.all(\n sources.map((source, i) =>\n limit(async () => {\n const start = Date.now();\n const result = await source.assetsMiddleware(\n {\n request: fallbackRequests[i],\n response: {},\n getAssetsState: context.getAssetsState,\n },\n noopNext,\n );\n const durationMs = Date.now() - start;\n return { result, sourceName: source.getName(), durationMs };\n }),\n ),\n );\n const fallbackResults = fallbackTimed.map((entry) => entry.result);\n for (const { sourceName, durationMs } of fallbackTimed) {\n const key = `${PARALLEL_BALANCE_MIDDLEWARE_NAME}.${sourceName}`;\n durationByDataSource[key] =\n (durationByDataSource[key] ?? 0) + durationMs;\n }\n const fallbackMerged = mergeDataResponses(\n fallbackResults.map((result) => result.response),\n );\n mergedResponse = mergeDataResponses([mergedResponse, fallbackMerged]);\n // Remove errors for chains we successfully got balance for in fallback\n if (mergedResponse.errors && mergedResponse.assetsBalance) {\n const chainsWithBalance = new Set<ChainId>();\n for (const accountBalances of Object.values(\n mergedResponse.assetsBalance,\n )) {\n for (const assetId of Object.keys(accountBalances)) {\n const chainId = assetId.split('/')[0] as ChainId;\n chainsWithBalance.add(chainId);\n }\n }\n for (const chainId of failedChainIds) {\n if (chainsWithBalance.has(chainId)) {\n delete mergedResponse.errors[chainId];\n }\n }\n }\n }\n\n return next({\n ...context,\n response: mergeDataResponses([context.response, mergedResponse]),\n durationByDataSource,\n });\n },\n };\n}\n\n// ============================================================================\n// PARALLEL TOKEN/PRICE MIDDLEWARE\n// ============================================================================\n\nconst PARALLEL_MIDDLEWARE_NAME = 'ParallelMiddleware';\n\n/** Max concurrent token/price source calls. */\nconst CONCURRENCY = 2;\n\n/**\n * Middleware that runs multiple data source middlewares (e.g. TokenDataSource,\n * PriceDataSource) in parallel with the same request. Responses are merged so\n * that assetsInfo (token metadata) and assetsPrice are combined. Use this to\n * fetch token and price data concurrently instead of sequentially.\n *\n * @param sources - Array of named middleware sources (getName + assetsMiddleware).\n * @returns A single middleware that runs all sources in parallel and merges responses.\n */\nexport function createParallelMiddleware(sources: AssetsDataSource[]): {\n getName(): string;\n assetsMiddleware: Middleware;\n} {\n return {\n getName(): string {\n return PARALLEL_MIDDLEWARE_NAME;\n },\n\n assetsMiddleware: async (context, next): Promise<Context> => {\n if (sources.length === 0) {\n return next(context);\n }\n\n const noopNext = async (ctx: typeof context): Promise<typeof context> =>\n ctx;\n const limit = pLimit(CONCURRENCY);\n\n const timedResults = await Promise.all(\n sources.map((source) =>\n limit(async () => {\n const start = Date.now();\n const result = await source.assetsMiddleware(\n {\n request: context.request,\n response: { ...context.response },\n getAssetsState: context.getAssetsState,\n },\n noopNext,\n );\n const durationMs = Date.now() - start;\n return { result, sourceName: source.getName(), durationMs };\n }),\n ),\n );\n\n const results = timedResults.map((entry) => entry.result);\n const mergedResponse = mergeDataResponses(\n results.map((result) => result.response),\n );\n\n const durationByDataSource: Record<string, number> = {\n ...context.durationByDataSource,\n };\n for (const { sourceName, durationMs } of timedResults) {\n durationByDataSource[`${PARALLEL_MIDDLEWARE_NAME}.${sourceName}`] =\n durationMs;\n }\n\n return next({\n ...context,\n response: mergeDataResponses([context.response, mergedResponse]),\n durationByDataSource,\n });\n },\n };\n}\n"]}