@metamask/assets-controller 6.0.0 → 6.2.0
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.
- package/CHANGELOG.md +50 -4
- package/dist/AssetsController.cjs +205 -29
- package/dist/AssetsController.cjs.map +1 -1
- package/dist/AssetsController.d.cts +8 -1
- package/dist/AssetsController.d.cts.map +1 -1
- package/dist/AssetsController.d.mts +8 -1
- package/dist/AssetsController.d.mts.map +1 -1
- package/dist/AssetsController.mjs +206 -30
- package/dist/AssetsController.mjs.map +1 -1
- package/dist/data-sources/AccountsApiDataSource.cjs +6 -3
- package/dist/data-sources/AccountsApiDataSource.cjs.map +1 -1
- package/dist/data-sources/AccountsApiDataSource.d.cts +6 -0
- package/dist/data-sources/AccountsApiDataSource.d.cts.map +1 -1
- package/dist/data-sources/AccountsApiDataSource.d.mts +6 -0
- package/dist/data-sources/AccountsApiDataSource.d.mts.map +1 -1
- package/dist/data-sources/AccountsApiDataSource.mjs +7 -4
- package/dist/data-sources/AccountsApiDataSource.mjs.map +1 -1
- package/dist/data-sources/BackendWebsocketDataSource.cjs +5 -3
- package/dist/data-sources/BackendWebsocketDataSource.cjs.map +1 -1
- package/dist/data-sources/BackendWebsocketDataSource.d.cts +3 -1
- package/dist/data-sources/BackendWebsocketDataSource.d.cts.map +1 -1
- package/dist/data-sources/BackendWebsocketDataSource.d.mts +3 -1
- package/dist/data-sources/BackendWebsocketDataSource.d.mts.map +1 -1
- package/dist/data-sources/BackendWebsocketDataSource.mjs +5 -3
- package/dist/data-sources/BackendWebsocketDataSource.mjs.map +1 -1
- package/dist/data-sources/PriceDataSource.cjs +12 -8
- package/dist/data-sources/PriceDataSource.cjs.map +1 -1
- package/dist/data-sources/PriceDataSource.d.cts +5 -0
- package/dist/data-sources/PriceDataSource.d.cts.map +1 -1
- package/dist/data-sources/PriceDataSource.d.mts +5 -0
- package/dist/data-sources/PriceDataSource.d.mts.map +1 -1
- package/dist/data-sources/PriceDataSource.mjs +12 -8
- package/dist/data-sources/PriceDataSource.mjs.map +1 -1
- package/dist/data-sources/RpcDataSource.cjs +25 -10
- package/dist/data-sources/RpcDataSource.cjs.map +1 -1
- package/dist/data-sources/RpcDataSource.d.cts +4 -3
- package/dist/data-sources/RpcDataSource.d.cts.map +1 -1
- package/dist/data-sources/RpcDataSource.d.mts +4 -3
- package/dist/data-sources/RpcDataSource.d.mts.map +1 -1
- package/dist/data-sources/RpcDataSource.mjs +25 -10
- package/dist/data-sources/RpcDataSource.mjs.map +1 -1
- package/dist/data-sources/TokenDataSource.cjs +24 -14
- package/dist/data-sources/TokenDataSource.cjs.map +1 -1
- package/dist/data-sources/TokenDataSource.d.cts +5 -0
- package/dist/data-sources/TokenDataSource.d.cts.map +1 -1
- package/dist/data-sources/TokenDataSource.d.mts +5 -0
- package/dist/data-sources/TokenDataSource.d.mts.map +1 -1
- package/dist/data-sources/TokenDataSource.mjs +24 -14
- package/dist/data-sources/TokenDataSource.mjs.map +1 -1
- package/dist/data-sources/evm-rpc-services/clients/MulticallClient.cjs +8 -0
- package/dist/data-sources/evm-rpc-services/clients/MulticallClient.cjs.map +1 -1
- package/dist/data-sources/evm-rpc-services/clients/MulticallClient.d.cts.map +1 -1
- package/dist/data-sources/evm-rpc-services/clients/MulticallClient.d.mts.map +1 -1
- package/dist/data-sources/evm-rpc-services/clients/MulticallClient.mjs +8 -0
- package/dist/data-sources/evm-rpc-services/clients/MulticallClient.mjs.map +1 -1
- package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.cjs +45 -25
- package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.cjs.map +1 -1
- package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.d.cts +11 -2
- package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.d.cts.map +1 -1
- package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.d.mts +11 -2
- package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.d.mts.map +1 -1
- package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.mjs +45 -25
- package/dist/data-sources/evm-rpc-services/services/BalanceFetcher.mjs.map +1 -1
- package/dist/data-sources/evm-rpc-services/types/state.cjs.map +1 -1
- package/dist/data-sources/evm-rpc-services/types/state.d.cts +6 -0
- package/dist/data-sources/evm-rpc-services/types/state.d.cts.map +1 -1
- package/dist/data-sources/evm-rpc-services/types/state.d.mts +6 -0
- package/dist/data-sources/evm-rpc-services/types/state.d.mts.map +1 -1
- package/dist/data-sources/evm-rpc-services/types/state.mjs.map +1 -1
- package/dist/errors.cjs +25 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.cts +25 -0
- package/dist/errors.d.cts.map +1 -0
- package/dist/errors.d.mts +25 -0
- package/dist/errors.d.mts.map +1 -0
- package/dist/errors.mjs +21 -0
- package/dist/errors.mjs.map +1 -0
- package/dist/index.cjs +5 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +3 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -1
- package/dist/index.mjs.map +1 -1
- package/dist/middlewares/CustomAssetGraduationMiddleware.cjs +121 -0
- package/dist/middlewares/CustomAssetGraduationMiddleware.cjs.map +1 -0
- package/dist/middlewares/CustomAssetGraduationMiddleware.d.cts +25 -0
- package/dist/middlewares/CustomAssetGraduationMiddleware.d.cts.map +1 -0
- package/dist/middlewares/CustomAssetGraduationMiddleware.d.mts +25 -0
- package/dist/middlewares/CustomAssetGraduationMiddleware.d.mts.map +1 -0
- package/dist/middlewares/CustomAssetGraduationMiddleware.mjs +117 -0
- package/dist/middlewares/CustomAssetGraduationMiddleware.mjs.map +1 -0
- package/dist/middlewares/RpcFallbackMiddleware.cjs +90 -0
- package/dist/middlewares/RpcFallbackMiddleware.cjs.map +1 -0
- package/dist/middlewares/RpcFallbackMiddleware.d.cts +23 -0
- package/dist/middlewares/RpcFallbackMiddleware.d.cts.map +1 -0
- package/dist/middlewares/RpcFallbackMiddleware.d.mts +23 -0
- package/dist/middlewares/RpcFallbackMiddleware.d.mts.map +1 -0
- package/dist/middlewares/RpcFallbackMiddleware.mjs +86 -0
- package/dist/middlewares/RpcFallbackMiddleware.mjs.map +1 -0
- package/dist/middlewares/index.cjs +5 -1
- package/dist/middlewares/index.cjs.map +1 -1
- package/dist/middlewares/index.d.cts +4 -0
- package/dist/middlewares/index.d.cts.map +1 -1
- package/dist/middlewares/index.d.mts +4 -0
- package/dist/middlewares/index.d.mts.map +1 -1
- package/dist/middlewares/index.mjs +2 -0
- package/dist/middlewares/index.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +7 -0
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +7 -0
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/fetchWithTimeout.cjs +30 -0
- package/dist/utils/fetchWithTimeout.cjs.map +1 -0
- package/dist/utils/fetchWithTimeout.d.cts +11 -0
- package/dist/utils/fetchWithTimeout.d.cts.map +1 -0
- package/dist/utils/fetchWithTimeout.d.mts +11 -0
- package/dist/utils/fetchWithTimeout.d.mts.map +1 -0
- package/dist/utils/fetchWithTimeout.mjs +26 -0
- package/dist/utils/fetchWithTimeout.mjs.map +1 -0
- package/dist/utils/formatExchangeRatesForBridge.cjs +10 -8
- package/dist/utils/formatExchangeRatesForBridge.cjs.map +1 -1
- package/dist/utils/formatExchangeRatesForBridge.d.cts +5 -3
- package/dist/utils/formatExchangeRatesForBridge.d.cts.map +1 -1
- package/dist/utils/formatExchangeRatesForBridge.d.mts +5 -3
- package/dist/utils/formatExchangeRatesForBridge.d.mts.map +1 -1
- package/dist/utils/formatExchangeRatesForBridge.mjs +11 -9
- package/dist/utils/formatExchangeRatesForBridge.mjs.map +1 -1
- package/dist/utils/formatStateForTransactionPay.cjs +8 -6
- package/dist/utils/formatStateForTransactionPay.cjs.map +1 -1
- package/dist/utils/formatStateForTransactionPay.d.cts +2 -2
- package/dist/utils/formatStateForTransactionPay.d.cts.map +1 -1
- package/dist/utils/formatStateForTransactionPay.d.mts +2 -2
- package/dist/utils/formatStateForTransactionPay.d.mts.map +1 -1
- package/dist/utils/formatStateForTransactionPay.mjs +8 -6
- package/dist/utils/formatStateForTransactionPay.mjs.map +1 -1
- package/dist/utils/index.cjs +6 -1
- package/dist/utils/index.cjs.map +1 -1
- package/dist/utils/index.d.cts +2 -0
- package/dist/utils/index.d.cts.map +1 -1
- package/dist/utils/index.d.mts +2 -0
- package/dist/utils/index.d.mts.map +1 -1
- package/dist/utils/index.mjs +2 -0
- package/dist/utils/index.mjs.map +1 -1
- package/dist/utils/native-assets.cjs +63 -0
- package/dist/utils/native-assets.cjs.map +1 -0
- package/dist/utils/native-assets.d.cts +19 -0
- package/dist/utils/native-assets.d.cts.map +1 -0
- package/dist/utils/native-assets.d.mts +19 -0
- package/dist/utils/native-assets.d.mts.map +1 -0
- package/dist/utils/native-assets.mjs +58 -0
- package/dist/utils/native-assets.mjs.map +1 -0
- package/package.json +8 -8
|
@@ -10,7 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
10
10
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
11
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
12
|
};
|
|
13
|
-
var _BalanceFetcher_instances, _BalanceFetcher_multicallClient, _BalanceFetcher_messenger, _BalanceFetcher_config, _BalanceFetcher_onBalanceUpdate, _BalanceFetcher_getAssetsToFetch, _BalanceFetcher_fetchBalances, _BalanceFetcher_processBalanceResponses, _BalanceFetcher_formatBalance;
|
|
13
|
+
var _BalanceFetcher_instances, _BalanceFetcher_multicallClient, _BalanceFetcher_messenger, _BalanceFetcher_config, _BalanceFetcher_isNativeAsset, _BalanceFetcher_onBalanceUpdate, _BalanceFetcher_getAssetsToFetch, _BalanceFetcher_fetchBalances, _BalanceFetcher_processBalanceResponses, _BalanceFetcher_formatBalance;
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
exports.BalanceFetcher = void 0;
|
|
16
16
|
const polling_controller_1 = require("@metamask/polling-controller");
|
|
@@ -34,13 +34,15 @@ class BalanceFetcher extends (0, polling_controller_1.StaticIntervalPollingContr
|
|
|
34
34
|
_BalanceFetcher_multicallClient.set(this, void 0);
|
|
35
35
|
_BalanceFetcher_messenger.set(this, void 0);
|
|
36
36
|
_BalanceFetcher_config.set(this, void 0);
|
|
37
|
+
_BalanceFetcher_isNativeAsset.set(this, void 0);
|
|
37
38
|
_BalanceFetcher_onBalanceUpdate.set(this, void 0);
|
|
38
39
|
__classPrivateFieldSet(this, _BalanceFetcher_multicallClient, multicallClient, "f");
|
|
39
40
|
__classPrivateFieldSet(this, _BalanceFetcher_messenger, messenger, "f");
|
|
40
41
|
__classPrivateFieldSet(this, _BalanceFetcher_config, {
|
|
41
|
-
defaultBatchSize: config
|
|
42
|
-
defaultTimeoutMs: config
|
|
42
|
+
defaultBatchSize: config.defaultBatchSize ?? 300,
|
|
43
|
+
defaultTimeoutMs: config.defaultTimeoutMs ?? 30000,
|
|
43
44
|
}, "f");
|
|
45
|
+
__classPrivateFieldSet(this, _BalanceFetcher_isNativeAsset, config.isNativeAsset, "f");
|
|
44
46
|
// Set the polling interval
|
|
45
47
|
this.setIntervalLength(config?.pollingInterval ?? DEFAULT_BALANCE_INTERVAL);
|
|
46
48
|
}
|
|
@@ -59,7 +61,7 @@ class BalanceFetcher extends (0, polling_controller_1.StaticIntervalPollingContr
|
|
|
59
61
|
* @param input - The polling input.
|
|
60
62
|
*/
|
|
61
63
|
async _executePoll(input) {
|
|
62
|
-
const result = await __classPrivateFieldGet(this, _BalanceFetcher_instances, "m", _BalanceFetcher_fetchBalances).call(this, input.chainId, input.accountId, input.accountAddress);
|
|
64
|
+
const result = await __classPrivateFieldGet(this, _BalanceFetcher_instances, "m", _BalanceFetcher_fetchBalances).call(this, input.chainId, input.accountId, input.accountAddress, input.customAssetsOnly === true);
|
|
63
65
|
if (__classPrivateFieldGet(this, _BalanceFetcher_onBalanceUpdate, "f") && result.balances.length > 0) {
|
|
64
66
|
await __classPrivateFieldGet(this, _BalanceFetcher_onBalanceUpdate, "f").call(this, result);
|
|
65
67
|
}
|
|
@@ -122,31 +124,48 @@ class BalanceFetcher extends (0, polling_controller_1.StaticIntervalPollingContr
|
|
|
122
124
|
}
|
|
123
125
|
}
|
|
124
126
|
exports.BalanceFetcher = BalanceFetcher;
|
|
125
|
-
_BalanceFetcher_multicallClient = new WeakMap(), _BalanceFetcher_messenger = new WeakMap(), _BalanceFetcher_config = new WeakMap(), _BalanceFetcher_onBalanceUpdate = new WeakMap(), _BalanceFetcher_instances = new WeakSet(), _BalanceFetcher_getAssetsToFetch = function _BalanceFetcher_getAssetsToFetch(chainId, accountId) {
|
|
127
|
+
_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) {
|
|
126
128
|
const state = __classPrivateFieldGet(this, _BalanceFetcher_messenger, "f").call('AssetsController:getState');
|
|
127
|
-
const accountBalances = state?.assetsBalance?.[accountId];
|
|
128
|
-
if (!accountBalances) {
|
|
129
|
-
return [];
|
|
130
|
-
}
|
|
131
129
|
// Convert hex chainId to decimal for CAIP-2 matching
|
|
132
130
|
// This is safe because we are filtring with an accountId that is for evm balances only
|
|
133
131
|
const chainIdDecimal = parseInt(chainId, 16).toString();
|
|
134
132
|
const assetsToFetch = new Map();
|
|
135
|
-
|
|
136
|
-
const
|
|
137
|
-
if (
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
133
|
+
const collect = (assetId) => {
|
|
134
|
+
const parsed = (0, utils_1.parseCaipAssetType)(assetId);
|
|
135
|
+
if (parsed.chain.reference !== chainIdDecimal) {
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const normalizedAssetId = assetId.toLowerCase();
|
|
139
|
+
if (assetsToFetch.has(normalizedAssetId)) {
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
const isNative = __classPrivateFieldGet(this, _BalanceFetcher_isNativeAsset, "f").call(this, assetId);
|
|
143
|
+
assetsToFetch.set(normalizedAssetId, {
|
|
144
|
+
assetId,
|
|
145
|
+
address: isNative
|
|
144
146
|
? constants_1.ZERO_ADDRESS
|
|
145
|
-
: assetReference.toLowerCase()
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
147
|
+
: parsed.assetReference.toLowerCase(),
|
|
148
|
+
});
|
|
149
|
+
};
|
|
150
|
+
// 1. Assets already tracked with a balance entry — only when not in
|
|
151
|
+
// "customAssetsOnly" mode (otherwise another data source is already
|
|
152
|
+
// refreshing them and we'd double-poll).
|
|
153
|
+
if (!customAssetsOnly) {
|
|
154
|
+
const accountBalances = state?.assetsBalance?.[accountId];
|
|
155
|
+
if (accountBalances) {
|
|
156
|
+
for (const assetId of Object.keys(accountBalances)) {
|
|
157
|
+
collect(assetId);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
// 2. User-added custom assets — RPC is the sole balance fetcher for
|
|
162
|
+
// these, so they must be polled even if they have no balance entry
|
|
163
|
+
// yet (e.g. zero balance, first fetch failed, or state was hydrated
|
|
164
|
+
// from disk before any successful fetch).
|
|
165
|
+
const customAssets = state?.customAssets?.[accountId];
|
|
166
|
+
if (customAssets) {
|
|
167
|
+
for (const assetId of customAssets) {
|
|
168
|
+
collect(assetId);
|
|
150
169
|
}
|
|
151
170
|
}
|
|
152
171
|
return Array.from(assetsToFetch.values());
|
|
@@ -158,10 +177,11 @@ _BalanceFetcher_multicallClient = new WeakMap(), _BalanceFetcher_messenger = new
|
|
|
158
177
|
* @param chainId - Hex chain ID.
|
|
159
178
|
* @param accountId - Account UUID.
|
|
160
179
|
* @param accountAddress - On-chain address of the account.
|
|
180
|
+
* @param customAssetsOnly - When true, skip `assetsBalance` and only include `customAssets`.
|
|
161
181
|
* @returns Balance fetch result.
|
|
162
182
|
*/
|
|
163
|
-
async function _BalanceFetcher_fetchBalances(chainId, accountId, accountAddress) {
|
|
164
|
-
const assets = __classPrivateFieldGet(this, _BalanceFetcher_instances, "m", _BalanceFetcher_getAssetsToFetch).call(this, chainId, accountId);
|
|
183
|
+
async function _BalanceFetcher_fetchBalances(chainId, accountId, accountAddress, customAssetsOnly) {
|
|
184
|
+
const assets = __classPrivateFieldGet(this, _BalanceFetcher_instances, "m", _BalanceFetcher_getAssetsToFetch).call(this, chainId, accountId, customAssetsOnly);
|
|
165
185
|
return this.fetchBalancesForAssets(chainId, accountId, accountAddress, assets);
|
|
166
186
|
}, _BalanceFetcher_processBalanceResponses = function _BalanceFetcher_processBalanceResponses(responses, accumulator, chainId, accountId, timestamp, entryByAddress) {
|
|
167
187
|
const { balances, failedAddresses } = accumulator;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BalanceFetcher.cjs","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/services/BalanceFetcher.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,qEAAmF;AACnF,2CAAqD;AAErD,4DAAwD;AAcxD,8CAAmD;AAEnD,MAAM,wBAAwB,GAAG,KAAM,CAAC,CAAC,aAAa;AAmCtD;;;;;;;;GAQG;AACH,MAAa,cAAe,SAAQ,IAAA,wDAAmC,GAAuB;IAS5F,YACE,eAAgC,EAChC,SAAkC,EAClC,MAA6B;QAE7B,KAAK,EAAE,CAAC;;QAbD,kDAAkC;QAElC,4CAAoC;QAEpC,yCAAiE;QAE1E,kDAAsD;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;YACjC,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,SAAS;YACT,OAAO;YACP,OAAO;YACP,gBAAgB;YAChB,SAAS;SACV,CAAC;QACF,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE,CAAC;YACjC,YAAY,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACnC,CAAC;QACD,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAC9B,CAAC;IAED,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,CAAC;AACvC,CAAC,yEAEc,UAAkB,EAAE,QAAgB;IACjD,IAAI,UAAU,KAAK,GAAG,EAAE,CAAC;QACvB,OAAO,GAAG,CAAC;IACb,CAAC;IAED,IAAI,CAAC;QACH,MAAM,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';\nimport type { MulticallClient } from '../clients';\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';\nimport { reduceInBatchesSerially } from '../utils';\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};\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\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<Omit<BalanceFetcherConfig, 'pollingInterval'>>;\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\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 );\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 * @returns Array of asset fetch entries from state for the requested chain.\n */\n #getAssetsToFetch(chainId: ChainId, accountId: AccountId): AssetFetchEntry[] {\n const state = this.#messenger.call('AssetsController:getState');\n\n const accountBalances = state?.assetsBalance?.[accountId];\n if (!accountBalances) {\n return [];\n }\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 for (const assetId of Object.keys(accountBalances) as CaipAssetType[]) {\n const {\n chain: { reference: chainReference },\n assetNamespace,\n assetReference,\n } = parseCaipAssetType(assetId);\n\n if (chainReference === chainIdDecimal) {\n const assetIdLowerCase = assetId.toLowerCase();\n if (assetsToFetch.has(assetIdLowerCase)) {\n continue;\n }\n\n const isNative = assetNamespace === 'slip44';\n const tokenAddress = isNative\n ? ZERO_ADDRESS\n : (assetReference.toLowerCase() as Address);\n\n assetsToFetch.set(assetIdLowerCase, {\n assetId,\n address: tokenAddress,\n });\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 * @returns Balance fetch result.\n */\n async #fetchBalances(\n chainId: ChainId,\n accountId: AccountId,\n accountAddress: Address,\n ): Promise<BalanceFetchResult> {\n const assets = this.#getAssetsToFetch(chainId, accountId);\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 );\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.cjs","sourceRoot":"","sources":["../../../../src/data-sources/evm-rpc-services/services/BalanceFetcher.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,qEAAmF;AACnF,2CAAqD;AAErD,4DAAwD;AAcxD,8CAAmD;AAEnD,MAAM,wBAAwB,GAAG,KAAM,CAAC,CAAC,aAAa;AA4CtD;;;;;;;;GAQG;AACH,MAAa,cAAe,SAAQ,IAAA,wDAAmC,GAAuB;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,CAAC,CAAC;IAC9E,CAAC;IAED;;;;OAIG;IACH,kBAAkB,CAAC,QAAiC;QAClD,uBAAA,IAAI,mCAAoB,QAAQ,MAAA,CAAC;IACnC,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,YAAY,CAAC,KAA0B;QAC3C,MAAM,MAAM,GAAG,MAAM,uBAAA,IAAI,gEAAe,MAAnB,IAAI,EACvB,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,cAAc,EACpB,KAAK,CAAC,gBAAgB,KAAK,IAAI,CAChC,CAAC;QAEF,IAAI,uBAAA,IAAI,uCAAiB,IAAI,MAAM,CAA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YAAY,CAAC,CAAC;IAC9B,CAAC;IAED,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,CAAC;AACvC,CAAC,yEAEc,UAAkB,EAAE,QAAgB;IACjD,IAAI,UAAU,KAAK,GAAG,EAAE,CAAC;QACvB,OAAO,GAAG,CAAC;IACb,CAAC;IAED,IAAI,CAAC;QACH,MAAM,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';\nimport type { MulticallClient } from '../clients';\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';\nimport { reduceInBatchesSerially } from '../utils';\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 );\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,5 +1,5 @@
|
|
|
1
1
|
import type { MulticallClient } from "../clients/index.cjs";
|
|
2
|
-
import type { AccountId, Address, AssetFetchEntry, AssetsBalanceState, BalanceFetchResult, ChainId } from "../types/index.cjs";
|
|
2
|
+
import type { AccountId, Address, AssetFetchEntry, AssetsBalanceState, BalanceFetchResult, CaipAssetType, ChainId } from "../types/index.cjs";
|
|
3
3
|
/**
|
|
4
4
|
* Minimal messenger interface for BalanceFetcher.
|
|
5
5
|
*/
|
|
@@ -11,6 +11,8 @@ export type BalanceFetcherConfig = {
|
|
|
11
11
|
defaultTimeoutMs?: number;
|
|
12
12
|
/** Polling interval in ms (default: 30s) */
|
|
13
13
|
pollingInterval?: number;
|
|
14
|
+
/** Determines whether a CAIP-19 asset ID represents a native asset. */
|
|
15
|
+
isNativeAsset: (assetId: CaipAssetType) => boolean;
|
|
14
16
|
};
|
|
15
17
|
/**
|
|
16
18
|
* Polling input for BalanceFetcher - identifies what to poll for.
|
|
@@ -22,6 +24,13 @@ export type BalancePollingInput = {
|
|
|
22
24
|
accountId: AccountId;
|
|
23
25
|
/** Account address */
|
|
24
26
|
accountAddress: Address;
|
|
27
|
+
/**
|
|
28
|
+
* When true, only fetch balances for entries in `state.customAssets`,
|
|
29
|
+
* skipping `state.assetsBalance`. Used by the supplemental RPC
|
|
30
|
+
* subscription on chains that another data source is already covering
|
|
31
|
+
* for regular balance refreshes.
|
|
32
|
+
*/
|
|
33
|
+
customAssetsOnly?: boolean;
|
|
25
34
|
};
|
|
26
35
|
/**
|
|
27
36
|
* Callback type for balance updates.
|
|
@@ -55,7 +64,7 @@ declare const BalanceFetcher_base: (abstract new (...args: any[]) => {
|
|
|
55
64
|
*/
|
|
56
65
|
export declare class BalanceFetcher extends BalanceFetcher_base {
|
|
57
66
|
#private;
|
|
58
|
-
constructor(multicallClient: MulticallClient, messenger: BalanceFetcherMessenger, config
|
|
67
|
+
constructor(multicallClient: MulticallClient, messenger: BalanceFetcherMessenger, config: BalanceFetcherConfig);
|
|
59
68
|
/**
|
|
60
69
|
* Set the callback to receive balance updates during polling.
|
|
61
70
|
*
|
|
@@ -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,6BAAmB;AAClD,OAAO,KAAK,EACV,SAAS,EACT,OAAO,EAEP,eAAe,EACf,kBAAkB,EAClB,kBAAkB,
|
|
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,6BAAmB;AAClD,OAAO,KAAK,EACV,SAAS,EACT,OAAO,EAEP,eAAe,EACf,kBAAkB,EAClB,kBAAkB,EAGlB,aAAa,EACb,OAAO,EACR,2BAAiB;AAKlB;;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;CAyJ/B"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { MulticallClient } from "../clients/index.mjs";
|
|
2
|
-
import type { AccountId, Address, AssetFetchEntry, AssetsBalanceState, BalanceFetchResult, ChainId } from "../types/index.mjs";
|
|
2
|
+
import type { AccountId, Address, AssetFetchEntry, AssetsBalanceState, BalanceFetchResult, CaipAssetType, ChainId } from "../types/index.mjs";
|
|
3
3
|
/**
|
|
4
4
|
* Minimal messenger interface for BalanceFetcher.
|
|
5
5
|
*/
|
|
@@ -11,6 +11,8 @@ export type BalanceFetcherConfig = {
|
|
|
11
11
|
defaultTimeoutMs?: number;
|
|
12
12
|
/** Polling interval in ms (default: 30s) */
|
|
13
13
|
pollingInterval?: number;
|
|
14
|
+
/** Determines whether a CAIP-19 asset ID represents a native asset. */
|
|
15
|
+
isNativeAsset: (assetId: CaipAssetType) => boolean;
|
|
14
16
|
};
|
|
15
17
|
/**
|
|
16
18
|
* Polling input for BalanceFetcher - identifies what to poll for.
|
|
@@ -22,6 +24,13 @@ export type BalancePollingInput = {
|
|
|
22
24
|
accountId: AccountId;
|
|
23
25
|
/** Account address */
|
|
24
26
|
accountAddress: Address;
|
|
27
|
+
/**
|
|
28
|
+
* When true, only fetch balances for entries in `state.customAssets`,
|
|
29
|
+
* skipping `state.assetsBalance`. Used by the supplemental RPC
|
|
30
|
+
* subscription on chains that another data source is already covering
|
|
31
|
+
* for regular balance refreshes.
|
|
32
|
+
*/
|
|
33
|
+
customAssetsOnly?: boolean;
|
|
25
34
|
};
|
|
26
35
|
/**
|
|
27
36
|
* Callback type for balance updates.
|
|
@@ -55,7 +64,7 @@ declare const BalanceFetcher_base: (abstract new (...args: any[]) => {
|
|
|
55
64
|
*/
|
|
56
65
|
export declare class BalanceFetcher extends BalanceFetcher_base {
|
|
57
66
|
#private;
|
|
58
|
-
constructor(multicallClient: MulticallClient, messenger: BalanceFetcherMessenger, config
|
|
67
|
+
constructor(multicallClient: MulticallClient, messenger: BalanceFetcherMessenger, config: BalanceFetcherConfig);
|
|
59
68
|
/**
|
|
60
69
|
* Set the callback to receive balance updates during polling.
|
|
61
70
|
*
|
|
@@ -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,6BAAmB;AAClD,OAAO,KAAK,EACV,SAAS,EACT,OAAO,EAEP,eAAe,EACf,kBAAkB,EAClB,kBAAkB,
|
|
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,6BAAmB;AAClD,OAAO,KAAK,EACV,SAAS,EACT,OAAO,EAEP,eAAe,EACf,kBAAkB,EAClB,kBAAkB,EAGlB,aAAa,EACb,OAAO,EACR,2BAAiB;AAKlB;;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;CAyJ/B"}
|
|
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
|
-
var _BalanceFetcher_instances, _BalanceFetcher_multicallClient, _BalanceFetcher_messenger, _BalanceFetcher_config, _BalanceFetcher_onBalanceUpdate, _BalanceFetcher_getAssetsToFetch, _BalanceFetcher_fetchBalances, _BalanceFetcher_processBalanceResponses, _BalanceFetcher_formatBalance;
|
|
12
|
+
var _BalanceFetcher_instances, _BalanceFetcher_multicallClient, _BalanceFetcher_messenger, _BalanceFetcher_config, _BalanceFetcher_isNativeAsset, _BalanceFetcher_onBalanceUpdate, _BalanceFetcher_getAssetsToFetch, _BalanceFetcher_fetchBalances, _BalanceFetcher_processBalanceResponses, _BalanceFetcher_formatBalance;
|
|
13
13
|
import { StaticIntervalPollingControllerOnly } from "@metamask/polling-controller";
|
|
14
14
|
import { parseCaipAssetType } from "@metamask/utils";
|
|
15
15
|
import { ZERO_ADDRESS } from "../../../utils/constants.mjs";
|
|
@@ -31,13 +31,15 @@ export class BalanceFetcher extends StaticIntervalPollingControllerOnly() {
|
|
|
31
31
|
_BalanceFetcher_multicallClient.set(this, void 0);
|
|
32
32
|
_BalanceFetcher_messenger.set(this, void 0);
|
|
33
33
|
_BalanceFetcher_config.set(this, void 0);
|
|
34
|
+
_BalanceFetcher_isNativeAsset.set(this, void 0);
|
|
34
35
|
_BalanceFetcher_onBalanceUpdate.set(this, void 0);
|
|
35
36
|
__classPrivateFieldSet(this, _BalanceFetcher_multicallClient, multicallClient, "f");
|
|
36
37
|
__classPrivateFieldSet(this, _BalanceFetcher_messenger, messenger, "f");
|
|
37
38
|
__classPrivateFieldSet(this, _BalanceFetcher_config, {
|
|
38
|
-
defaultBatchSize: config
|
|
39
|
-
defaultTimeoutMs: config
|
|
39
|
+
defaultBatchSize: config.defaultBatchSize ?? 300,
|
|
40
|
+
defaultTimeoutMs: config.defaultTimeoutMs ?? 30000,
|
|
40
41
|
}, "f");
|
|
42
|
+
__classPrivateFieldSet(this, _BalanceFetcher_isNativeAsset, config.isNativeAsset, "f");
|
|
41
43
|
// Set the polling interval
|
|
42
44
|
this.setIntervalLength(config?.pollingInterval ?? DEFAULT_BALANCE_INTERVAL);
|
|
43
45
|
}
|
|
@@ -56,7 +58,7 @@ export class BalanceFetcher extends StaticIntervalPollingControllerOnly() {
|
|
|
56
58
|
* @param input - The polling input.
|
|
57
59
|
*/
|
|
58
60
|
async _executePoll(input) {
|
|
59
|
-
const result = await __classPrivateFieldGet(this, _BalanceFetcher_instances, "m", _BalanceFetcher_fetchBalances).call(this, input.chainId, input.accountId, input.accountAddress);
|
|
61
|
+
const result = await __classPrivateFieldGet(this, _BalanceFetcher_instances, "m", _BalanceFetcher_fetchBalances).call(this, input.chainId, input.accountId, input.accountAddress, input.customAssetsOnly === true);
|
|
60
62
|
if (__classPrivateFieldGet(this, _BalanceFetcher_onBalanceUpdate, "f") && result.balances.length > 0) {
|
|
61
63
|
await __classPrivateFieldGet(this, _BalanceFetcher_onBalanceUpdate, "f").call(this, result);
|
|
62
64
|
}
|
|
@@ -118,31 +120,48 @@ export class BalanceFetcher extends StaticIntervalPollingControllerOnly() {
|
|
|
118
120
|
};
|
|
119
121
|
}
|
|
120
122
|
}
|
|
121
|
-
_BalanceFetcher_multicallClient = new WeakMap(), _BalanceFetcher_messenger = new WeakMap(), _BalanceFetcher_config = new WeakMap(), _BalanceFetcher_onBalanceUpdate = new WeakMap(), _BalanceFetcher_instances = new WeakSet(), _BalanceFetcher_getAssetsToFetch = function _BalanceFetcher_getAssetsToFetch(chainId, accountId) {
|
|
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) {
|
|
122
124
|
const state = __classPrivateFieldGet(this, _BalanceFetcher_messenger, "f").call('AssetsController:getState');
|
|
123
|
-
const accountBalances = state?.assetsBalance?.[accountId];
|
|
124
|
-
if (!accountBalances) {
|
|
125
|
-
return [];
|
|
126
|
-
}
|
|
127
125
|
// Convert hex chainId to decimal for CAIP-2 matching
|
|
128
126
|
// This is safe because we are filtring with an accountId that is for evm balances only
|
|
129
127
|
const chainIdDecimal = parseInt(chainId, 16).toString();
|
|
130
128
|
const assetsToFetch = new Map();
|
|
131
|
-
|
|
132
|
-
const
|
|
133
|
-
if (
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
129
|
+
const collect = (assetId) => {
|
|
130
|
+
const parsed = parseCaipAssetType(assetId);
|
|
131
|
+
if (parsed.chain.reference !== chainIdDecimal) {
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
const normalizedAssetId = assetId.toLowerCase();
|
|
135
|
+
if (assetsToFetch.has(normalizedAssetId)) {
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const isNative = __classPrivateFieldGet(this, _BalanceFetcher_isNativeAsset, "f").call(this, assetId);
|
|
139
|
+
assetsToFetch.set(normalizedAssetId, {
|
|
140
|
+
assetId,
|
|
141
|
+
address: isNative
|
|
140
142
|
? ZERO_ADDRESS
|
|
141
|
-
: assetReference.toLowerCase()
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
143
|
+
: parsed.assetReference.toLowerCase(),
|
|
144
|
+
});
|
|
145
|
+
};
|
|
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).
|
|
149
|
+
if (!customAssetsOnly) {
|
|
150
|
+
const accountBalances = state?.assetsBalance?.[accountId];
|
|
151
|
+
if (accountBalances) {
|
|
152
|
+
for (const assetId of Object.keys(accountBalances)) {
|
|
153
|
+
collect(assetId);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
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).
|
|
161
|
+
const customAssets = state?.customAssets?.[accountId];
|
|
162
|
+
if (customAssets) {
|
|
163
|
+
for (const assetId of customAssets) {
|
|
164
|
+
collect(assetId);
|
|
146
165
|
}
|
|
147
166
|
}
|
|
148
167
|
return Array.from(assetsToFetch.values());
|
|
@@ -154,10 +173,11 @@ _BalanceFetcher_multicallClient = new WeakMap(), _BalanceFetcher_messenger = new
|
|
|
154
173
|
* @param chainId - Hex chain ID.
|
|
155
174
|
* @param accountId - Account UUID.
|
|
156
175
|
* @param accountAddress - On-chain address of the account.
|
|
176
|
+
* @param customAssetsOnly - When true, skip `assetsBalance` and only include `customAssets`.
|
|
157
177
|
* @returns Balance fetch result.
|
|
158
178
|
*/
|
|
159
|
-
async function _BalanceFetcher_fetchBalances(chainId, accountId, accountAddress) {
|
|
160
|
-
const assets = __classPrivateFieldGet(this, _BalanceFetcher_instances, "m", _BalanceFetcher_getAssetsToFetch).call(this, chainId, accountId);
|
|
179
|
+
async function _BalanceFetcher_fetchBalances(chainId, accountId, accountAddress, customAssetsOnly) {
|
|
180
|
+
const assets = __classPrivateFieldGet(this, _BalanceFetcher_instances, "m", _BalanceFetcher_getAssetsToFetch).call(this, chainId, accountId, customAssetsOnly);
|
|
161
181
|
return this.fetchBalancesForAssets(chainId, accountId, accountAddress, assets);
|
|
162
182
|
}, _BalanceFetcher_processBalanceResponses = function _BalanceFetcher_processBalanceResponses(responses, accumulator, chainId, accountId, timestamp, entryByAddress) {
|
|
163
183
|
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,qCAAiC;AAcxD,OAAO,EAAE,uBAAuB,EAAE,2BAAiB;AAEnD,MAAM,wBAAwB,GAAG,KAAM,CAAC,CAAC,aAAa;AAmCtD;;;;;;;;GAQG;AACH,MAAM,OAAO,cAAe,SAAQ,mCAAmC,EAAuB;IAS5F,YACE,eAAgC,EAChC,SAAkC,EAClC,MAA6B;QAE7B,KAAK,EAAE,CAAC;;QAbD,kDAAkC;QAElC,4CAAoC;QAEpC,yCAAiE;QAE1E,kDAAsD;QAQpD,uBAAA,IAAI,mCAAoB,eAAe,MAAA,CAAC;QACxC,uBAAA,IAAI,6BAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,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K,QAAQ,EAAE,CAAC;YACjC,YAAY,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACnC,CAAC;QACD,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAC9B,CAAC;IAED,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,CAAC;AACvC,CAAC,yEAEc,UAAkB,EAAE,QAAgB;IACjD,IAAI,UAAU,KAAK,GAAG,EAAE,CAAC;QACvB,OAAO,GAAG,CAAC;IACb,CAAC;IAED,IAAI,CAAC;QACH,MAAM,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';\nimport type { MulticallClient } from '../clients';\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';\nimport { reduceInBatchesSerially } from '../utils';\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};\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\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<Omit<BalanceFetcherConfig, 'pollingInterval'>>;\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\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 );\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 * @returns Array of asset fetch entries from state for the requested chain.\n */\n #getAssetsToFetch(chainId: ChainId, accountId: AccountId): AssetFetchEntry[] {\n const state = this.#messenger.call('AssetsController:getState');\n\n const accountBalances = state?.assetsBalance?.[accountId];\n if (!accountBalances) {\n return [];\n }\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 for (const assetId of Object.keys(accountBalances) as CaipAssetType[]) {\n const {\n chain: { reference: chainReference },\n assetNamespace,\n assetReference,\n } = parseCaipAssetType(assetId);\n\n if (chainReference === chainIdDecimal) {\n const assetIdLowerCase = assetId.toLowerCase();\n if (assetsToFetch.has(assetIdLowerCase)) {\n continue;\n }\n\n const isNative = assetNamespace === 'slip44';\n const tokenAddress = isNative\n ? ZERO_ADDRESS\n : (assetReference.toLowerCase() as Address);\n\n assetsToFetch.set(assetIdLowerCase, {\n assetId,\n address: tokenAddress,\n });\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 * @returns Balance fetch result.\n */\n async #fetchBalances(\n chainId: ChainId,\n accountId: AccountId,\n accountAddress: Address,\n ): Promise<BalanceFetchResult> {\n const assets = this.#getAssetsToFetch(chainId, accountId);\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 );\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,mCAAm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e,EAAE,CAAC;AACvC,CAAC,yEAEc,UAAkB,EAAE,QAAgB;IACjD,IAAI,UAAU,KAAK,GAAG,EAAE,CAAC;QACvB,OAAO,GAAG,CAAC;IACb,CAAC;IAED,IAAI,CAAC;QACH,MAAM,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';\nimport type { MulticallClient } from '../clients';\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';\nimport { reduceInBatchesSerially } from '../utils';\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 );\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';\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"]}
|
|
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';\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"]}
|
|
@@ -48,5 +48,11 @@ export type AssetBalanceEntry = {
|
|
|
48
48
|
export type AssetsBalanceState = {
|
|
49
49
|
/** Balance data per account: accountId -> assetId -> balance */
|
|
50
50
|
assetsBalance: Record<string, Record<string, AssetBalanceEntry>>;
|
|
51
|
+
/**
|
|
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).
|
|
55
|
+
*/
|
|
56
|
+
customAssets?: Record<string, string[]>;
|
|
51
57
|
};
|
|
52
58
|
//# sourceMappingURL=state.d.cts.map
|
|
@@ -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,mBAAe;AAEtC;;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;
|
|
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,mBAAe;AAEtC;;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"}
|
|
@@ -48,5 +48,11 @@ export type AssetBalanceEntry = {
|
|
|
48
48
|
export type AssetsBalanceState = {
|
|
49
49
|
/** Balance data per account: accountId -> assetId -> balance */
|
|
50
50
|
assetsBalance: Record<string, Record<string, AssetBalanceEntry>>;
|
|
51
|
+
/**
|
|
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).
|
|
55
|
+
*/
|
|
56
|
+
customAssets?: Record<string, string[]>;
|
|
51
57
|
};
|
|
52
58
|
//# sourceMappingURL=state.d.mts.map
|
|
@@ -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,mBAAe;AAEtC;;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;
|
|
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,mBAAe;AAEtC;;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 +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';\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"]}
|
|
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';\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"]}
|
package/dist/errors.cjs
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AssetsDataSourceError = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Thrown and/or passed to `captureException` when one or more assets data
|
|
6
|
+
* source middlewares fail during a fetch. Use Sentry's "error type" / title
|
|
7
|
+
* filter on `AssetsDataSourceError` to build issue alerts.
|
|
8
|
+
*/
|
|
9
|
+
class AssetsDataSourceError extends Error {
|
|
10
|
+
/**
|
|
11
|
+
* @param details - Which sources failed and request size hints.
|
|
12
|
+
* @param details.failedSources - Comma-separated data source names that failed.
|
|
13
|
+
* @param details.errorCount - Number of failed middlewares in the request.
|
|
14
|
+
* @param details.chainCount - Chains included in the request (for context).
|
|
15
|
+
*/
|
|
16
|
+
constructor(details) {
|
|
17
|
+
super(`Assets data source middleware failures (${details.errorCount}): ${details.failedSources}`);
|
|
18
|
+
this.name = 'AssetsDataSourceError';
|
|
19
|
+
this.failedSources = details.failedSources;
|
|
20
|
+
this.errorCount = details.errorCount;
|
|
21
|
+
this.chainCount = details.chainCount;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
exports.AssetsDataSourceError = AssetsDataSourceError;
|
|
25
|
+
//# sourceMappingURL=errors.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.cjs","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,MAAa,qBAAsB,SAAQ,KAAK;IAU9C;;;;;OAKG;IACH,YAAY,OAIX;QACC,KAAK,CACH,2CAA2C,OAAO,CAAC,UAAU,MAAM,OAAO,CAAC,aAAa,EAAE,CAC3F,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,uBAAuB,CAAC;QACpC,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;QAC3C,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;QACrC,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;IACvC,CAAC;CACF;AA7BD,sDA6BC","sourcesContent":["/**\n * Thrown and/or passed to `captureException` when one or more assets data\n * source middlewares fail during a fetch. Use Sentry's \"error type\" / title\n * filter on `AssetsDataSourceError` to build issue alerts.\n */\nexport class AssetsDataSourceError extends Error {\n /** Comma-separated data source names that failed. */\n readonly failedSources: string;\n\n /** Number of failed middlewares in the request. */\n readonly errorCount: number;\n\n /** Chains included in the request (for context). */\n readonly chainCount: number;\n\n /**\n * @param details - Which sources failed and request size hints.\n * @param details.failedSources - Comma-separated data source names that failed.\n * @param details.errorCount - Number of failed middlewares in the request.\n * @param details.chainCount - Chains included in the request (for context).\n */\n constructor(details: {\n failedSources: string;\n errorCount: number;\n chainCount: number;\n }) {\n super(\n `Assets data source middleware failures (${details.errorCount}): ${details.failedSources}`,\n );\n this.name = 'AssetsDataSourceError';\n this.failedSources = details.failedSources;\n this.errorCount = details.errorCount;\n this.chainCount = details.chainCount;\n }\n}\n"]}
|