@metamask-previews/assets-controllers 62.0.0-preview-780c8df → 62.0.0-preview-515e9b9c
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 +14 -0
- package/dist/TokenBalancesController.cjs +79 -10
- package/dist/TokenBalancesController.cjs.map +1 -1
- package/dist/TokenBalancesController.d.cts +4 -6
- package/dist/TokenBalancesController.d.cts.map +1 -1
- package/dist/TokenBalancesController.d.mts +4 -6
- package/dist/TokenBalancesController.d.mts.map +1 -1
- package/dist/TokenBalancesController.mjs +79 -10
- package/dist/TokenBalancesController.mjs.map +1 -1
- package/dist/TokensController.cjs +34 -2
- package/dist/TokensController.cjs.map +1 -1
- package/dist/TokensController.d.cts +3 -3
- package/dist/TokensController.d.cts.map +1 -1
- package/dist/TokensController.d.mts +3 -3
- package/dist/TokensController.d.mts.map +1 -1
- package/dist/TokensController.mjs +34 -2
- package/dist/TokensController.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
7
7
|
|
8
8
|
## [Unreleased]
|
9
9
|
|
10
|
+
### Added
|
11
|
+
|
12
|
+
- **BREAKING:** Add event listener for `AccountsController:accountRemoved` on `TokenBalancesController` to remove token balances for the removed account ([#5726](https://github.com/MetaMask/core/pull/5726))
|
13
|
+
|
14
|
+
- **BREAKING:** Add event listener for `AccountsController:accountRemoved` on `TokensController` to remove tokens for the removed account ([#5726](https://github.com/MetaMask/core/pull/5726))
|
15
|
+
|
16
|
+
- **BREAKING:** Add `listAccounts` action to `TokensController` ([#5726](https://github.com/MetaMask/core/pull/5726))
|
17
|
+
|
18
|
+
- **BREAKING:** Add `listAccounts` action to `TokenBalancesController` ([#5726](https://github.com/MetaMask/core/pull/5726))
|
19
|
+
|
20
|
+
### Changed
|
21
|
+
|
22
|
+
- TokenBalancesController will now check if balances has changed before updating the state ([#5726](https://github.com/MetaMask/core/pull/5726))
|
23
|
+
|
10
24
|
## [62.0.0]
|
11
25
|
|
12
26
|
### Added
|
@@ -10,7 +10,7 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
|
|
10
10
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
11
11
|
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
12
12
|
};
|
13
|
-
var _TokenBalancesController_instances, _TokenBalancesController_queryMultipleAccounts, _TokenBalancesController_allTokens, _TokenBalancesController_allDetectedTokens, _TokenBalancesController_calculateQueryMultipleAccounts, _TokenBalancesController_onPreferencesStateChange, _TokenBalancesController_onTokensStateChange, _TokenBalancesController_onNetworkStateChange, _TokenBalancesController_getChainIds, _TokenBalancesController_getNetworkClient;
|
13
|
+
var _TokenBalancesController_instances, _TokenBalancesController_queryMultipleAccounts, _TokenBalancesController_allTokens, _TokenBalancesController_allDetectedTokens, _TokenBalancesController_calculateQueryMultipleAccounts, _TokenBalancesController_onPreferencesStateChange, _TokenBalancesController_onTokensStateChange, _TokenBalancesController_onNetworkStateChange, _TokenBalancesController_handleOnAccountRemoved, _TokenBalancesController_getChainIds, _TokenBalancesController_handleTokensControllerStateChange, _TokenBalancesController_getNetworkClient;
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
15
15
|
exports.TokenBalancesController = exports.getDefaultTokenBalancesState = void 0;
|
16
16
|
const contracts_1 = require("@ethersproject/contracts");
|
@@ -103,7 +103,9 @@ class TokenBalancesController extends (0, polling_controller_1.StaticIntervalPol
|
|
103
103
|
!(0, lodash_1.isEqual)(__classPrivateFieldGet(this, _TokenBalancesController_allDetectedTokens, "f")[chainId], allDetectedTokens[chainId]));
|
104
104
|
__classPrivateFieldSet(this, _TokenBalancesController_allTokens, allTokens, "f");
|
105
105
|
__classPrivateFieldSet(this, _TokenBalancesController_allDetectedTokens, allDetectedTokens, "f");
|
106
|
-
this
|
106
|
+
__classPrivateFieldGet(this, _TokenBalancesController_instances, "m", _TokenBalancesController_handleTokensControllerStateChange).call(this, {
|
107
|
+
chainIds: chainIdsToUpdate,
|
108
|
+
}).catch(console.error);
|
107
109
|
});
|
108
110
|
/**
|
109
111
|
* Returns an array of chain ids that have tokens.
|
@@ -129,6 +131,8 @@ class TokenBalancesController extends (0, polling_controller_1.StaticIntervalPol
|
|
129
131
|
this.messagingSystem.subscribe('TokensController:stateChange', __classPrivateFieldGet(this, _TokenBalancesController_onTokensStateChange, "f").bind(this));
|
130
132
|
// Subscribe to network state changes
|
131
133
|
this.messagingSystem.subscribe('NetworkController:stateChange', __classPrivateFieldGet(this, _TokenBalancesController_instances, "m", _TokenBalancesController_onNetworkStateChange).bind(this));
|
134
|
+
// subscribe to account removed event to cleanup stale balances
|
135
|
+
this.messagingSystem.subscribe('AccountsController:accountRemoved', (accountId) => __classPrivateFieldGet(this, _TokenBalancesController_instances, "m", _TokenBalancesController_handleOnAccountRemoved).call(this, accountId));
|
132
136
|
}
|
133
137
|
/**
|
134
138
|
* Polls for erc20 token balances.
|
@@ -168,6 +172,7 @@ class TokenBalancesController extends (0, polling_controller_1.StaticIntervalPol
|
|
168
172
|
Object.entries(__classPrivateFieldGet(this, _TokenBalancesController_allTokens, "f")[chainId] ?? {}).forEach(addTokens);
|
169
173
|
Object.entries(__classPrivateFieldGet(this, _TokenBalancesController_allDetectedTokens, "f")[chainId] ?? {}).forEach(addTokens);
|
170
174
|
let results = [];
|
175
|
+
const currentTokenBalances = this.messagingSystem.call('TokenBalancesController:getState');
|
171
176
|
if (accountTokenPairs.length > 0) {
|
172
177
|
const provider = new providers_1.Web3Provider(__classPrivateFieldGet(this, _TokenBalancesController_instances, "m", _TokenBalancesController_getNetworkClient).call(this, chainId).provider);
|
173
178
|
const calls = accountTokenPairs.map(({ accountAddress, tokenAddress }) => ({
|
@@ -177,17 +182,26 @@ class TokenBalancesController extends (0, polling_controller_1.StaticIntervalPol
|
|
177
182
|
}));
|
178
183
|
results = await (0, multicall_1.multicallOrFallback)(calls, chainId, provider);
|
179
184
|
}
|
185
|
+
const updatedResults = results.map((res, i) => {
|
186
|
+
const { value } = res;
|
187
|
+
const { accountAddress, tokenAddress } = accountTokenPairs[i];
|
188
|
+
const currentTokenBalanceValueForAccount = currentTokenBalances.tokenBalances?.[accountAddress]?.[chainId]?.[tokenAddress];
|
189
|
+
const isTokenBalanceValueChanged = currentTokenBalanceValueForAccount !== (0, controller_utils_1.toHex)(value);
|
190
|
+
return {
|
191
|
+
...res,
|
192
|
+
isTokenBalanceValueChanged,
|
193
|
+
};
|
194
|
+
});
|
195
|
+
// if all values of isTokenBalanceValueChanged are false, return
|
196
|
+
if (updatedResults.every((result) => !result.isTokenBalanceValueChanged)) {
|
197
|
+
return;
|
198
|
+
}
|
180
199
|
this.update((state) => {
|
181
200
|
var _a, _b;
|
182
|
-
|
183
|
-
|
184
|
-
for (const accountAddress of Object.keys(state.tokenBalances)) {
|
185
|
-
state.tokenBalances[accountAddress][chainId] = {};
|
186
|
-
}
|
187
|
-
for (let i = 0; i < results.length; i++) {
|
188
|
-
const { success, value } = results[i];
|
201
|
+
for (let i = 0; i < updatedResults.length; i++) {
|
202
|
+
const { success, value, isTokenBalanceValueChanged } = updatedResults[i];
|
189
203
|
const { accountAddress, tokenAddress } = accountTokenPairs[i];
|
190
|
-
if (success) {
|
204
|
+
if (success && isTokenBalanceValueChanged) {
|
191
205
|
((_b = ((_a = state.tokenBalances)[accountAddress] ?? (_a[accountAddress] = {})))[chainId] ?? (_b[chainId] = {}))[tokenAddress] = (0, controller_utils_1.toHex)(value);
|
192
206
|
}
|
193
207
|
}
|
@@ -216,6 +230,61 @@ _TokenBalancesController_queryMultipleAccounts = new WeakMap(), _TokenBalancesCo
|
|
216
230
|
});
|
217
231
|
}
|
218
232
|
}
|
233
|
+
}, _TokenBalancesController_handleOnAccountRemoved = function _TokenBalancesController_handleOnAccountRemoved(accountId) {
|
234
|
+
const accounts = this.messagingSystem.call('AccountsController:listAccounts');
|
235
|
+
const accountAddress = accounts.find((account) => account.id === accountId)?.address;
|
236
|
+
if (!accountAddress) {
|
237
|
+
return;
|
238
|
+
}
|
239
|
+
this.update((state) => {
|
240
|
+
delete state.tokenBalances[accountAddress];
|
241
|
+
});
|
242
|
+
}, _TokenBalancesController_handleTokensControllerStateChange = async function _TokenBalancesController_handleTokensControllerStateChange({ chainIds, } = {}) {
|
243
|
+
const currentTokenBalancesState = this.messagingSystem.call('TokenBalancesController:getState');
|
244
|
+
const currentTokenBalances = currentTokenBalancesState.tokenBalances;
|
245
|
+
const currentAllTokens = __classPrivateFieldGet(this, _TokenBalancesController_allTokens, "f");
|
246
|
+
const chainIdsSet = new Set(chainIds);
|
247
|
+
// first we check if the state change was due to a token being removed
|
248
|
+
for (const currentAccount of Object.keys(currentTokenBalances)) {
|
249
|
+
const allChains = currentTokenBalances[currentAccount];
|
250
|
+
for (const currentChain of Object.keys(allChains)) {
|
251
|
+
if (chainIds?.length && !chainIdsSet.has(currentChain)) {
|
252
|
+
continue;
|
253
|
+
}
|
254
|
+
const tokensObject = allChains[currentChain];
|
255
|
+
const allCurrentTokens = Object.keys(tokensObject);
|
256
|
+
const existingTokensInState = currentAllTokens[currentChain]?.[currentAccount] || [];
|
257
|
+
const existingSet = new Set(existingTokensInState.map((elm) => elm.address));
|
258
|
+
for (const singleToken of allCurrentTokens) {
|
259
|
+
if (!existingSet.has(singleToken)) {
|
260
|
+
this.update((state) => {
|
261
|
+
delete state.tokenBalances[currentAccount][currentChain][singleToken];
|
262
|
+
});
|
263
|
+
}
|
264
|
+
}
|
265
|
+
}
|
266
|
+
}
|
267
|
+
// then we check if the state change was due to a token being added
|
268
|
+
let shouldUpdate = false;
|
269
|
+
for (const currentChain of Object.keys(currentAllTokens)) {
|
270
|
+
if (chainIds?.length && !chainIdsSet.has(currentChain)) {
|
271
|
+
continue;
|
272
|
+
}
|
273
|
+
const accountsPerChain = currentAllTokens[currentChain];
|
274
|
+
for (const currentAccount of Object.keys(accountsPerChain)) {
|
275
|
+
const tokensList = accountsPerChain[currentAccount];
|
276
|
+
const tokenBalancesObject = currentTokenBalances[currentAccount]?.[currentChain] || {};
|
277
|
+
for (const singleToken of tokensList) {
|
278
|
+
if (!tokenBalancesObject?.[singleToken.address]) {
|
279
|
+
shouldUpdate = true;
|
280
|
+
break;
|
281
|
+
}
|
282
|
+
}
|
283
|
+
}
|
284
|
+
}
|
285
|
+
if (shouldUpdate) {
|
286
|
+
await this.updateBalances({ chainIds }).catch(console.error);
|
287
|
+
}
|
219
288
|
}, _TokenBalancesController_getNetworkClient = function _TokenBalancesController_getNetworkClient(chainId) {
|
220
289
|
const { networkConfigurationsByChainId } = this.messagingSystem.call('NetworkController:getState');
|
221
290
|
const networkConfiguration = networkConfigurationsByChainId[chainId];
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"TokenBalancesController.cjs","sourceRoot":"","sources":["../src/TokenBalancesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,wDAAoD;AACpD,wDAAwD;AAOxD,iEAAyE;AACzE,mEAAuD;AAOvD,qEAA+E;AAS/E,mCAAiC;AAGjC,+CAAkD;AAQlD,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,MAAM,cAAc,GAAG,yBAAyB,CAAC;AAEjD,MAAM,QAAQ,GAAG;IACf,aAAa,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;CACnD,CAAC;AAgEF;;;;GAIG;AACH,SAAgB,4BAA4B;IAC1C,OAAO;QACL,aAAa,EAAE,EAAE;KAClB,CAAC;AACJ,CAAC;AAJD,oEAIC;AAOD;;;GAGG;AACH,MAAa,uBAAwB,SAAQ,IAAA,oDAA+B,GAI3E;IAOC;;;;;;;OAOG;IACH,YAAY,EACV,QAAQ,GAAG,gBAAgB,EAC3B,SAAS,EACT,KAAK,GAAG,EAAE,GACqB;;QAC/B,KAAK,CAAC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AAG,8BAA8B,CAAC,OAAO,CAAC,CAAC;IACrE,IAAI,CAAC,oBAAoB,EAAE;QACzB,MAAM,IAAI,KAAK,CACb,uEAAuE,OAAO,EAAE,CACjF,CAAC;KACH;IAED,MAAM,EAAE,eAAe,EAAE,GACvB,oBAAoB,CAAC,YAAY,CAC/B,oBAAoB,CAAC,uBAAuB,CAC7C,CAAC;IAEJ,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAC9B,wCAAwC,EACxC,eAAe,CAChB,CAAC;AACJ,CAAC;AAGH,kBAAe,uBAAuB,CAAC","sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport { Web3Provider } from '@ethersproject/providers';\nimport type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { toChecksumHexAddress, toHex } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type {\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n NetworkControllerStateChangeEvent,\n NetworkState,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n PreferencesState,\n} from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\nimport type BN from 'bn.js';\nimport type { Patch } from 'immer';\nimport { isEqual } from 'lodash';\n\nimport type { MulticallResult } from './multicall';\nimport { multicallOrFallback } from './multicall';\nimport type { Token } from './TokenRatesController';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerState,\n TokensControllerStateChangeEvent,\n} from './TokensController';\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst controllerName = 'TokenBalancesController';\n\nconst metadata = {\n tokenBalances: { persist: true, anonymous: false },\n};\n\n/**\n * Token balances controller options\n * @property interval - Polling interval used to fetch new token balances.\n * @property messenger - A messenger.\n * @property state - Initial state for the controller.\n */\ntype TokenBalancesControllerOptions = {\n interval?: number;\n messenger: TokenBalancesControllerMessenger;\n state?: Partial<TokenBalancesControllerState>;\n};\n\n/**\n * A mapping from account address to chain id to token address to balance.\n */\ntype TokenBalances = Record<Hex, Record<Hex, Record<Hex, Hex>>>;\n\n/**\n * Token balances controller state\n * @property tokenBalances - A mapping from account address to chain id to token address to balance.\n */\nexport type TokenBalancesControllerState = {\n tokenBalances: TokenBalances;\n};\n\nexport type TokenBalancesControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenBalancesControllerState\n>;\n\nexport type TokenBalancesControllerActions =\n TokenBalancesControllerGetStateAction;\n\nexport type AllowedActions =\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetStateAction\n | TokensControllerGetStateAction\n | PreferencesControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction;\n\nexport type TokenBalancesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n TokenBalancesControllerState\n >;\n\nexport type TokenBalancesControllerEvents =\n TokenBalancesControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | TokensControllerStateChangeEvent\n | PreferencesControllerStateChangeEvent\n | NetworkControllerStateChangeEvent;\n\nexport type TokenBalancesControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n TokenBalancesControllerActions | AllowedActions,\n TokenBalancesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Get the default TokenBalancesController state.\n *\n * @returns The default TokenBalancesController state.\n */\nexport function getDefaultTokenBalancesState(): TokenBalancesControllerState {\n return {\n tokenBalances: {},\n };\n}\n\n/** The input to start polling for the {@link TokenBalancesController} */\nexport type TokenBalancesPollingInput = {\n chainId: Hex;\n};\n\n/**\n * Controller that passively polls on a set interval token balances\n * for tokens stored in the TokensController\n */\nexport class TokenBalancesController extends StaticIntervalPollingController<TokenBalancesPollingInput>()<\n typeof controllerName,\n TokenBalancesControllerState,\n TokenBalancesControllerMessenger\n> {\n #queryMultipleAccounts: boolean;\n\n #allTokens: TokensControllerState['allTokens'];\n\n #allDetectedTokens: TokensControllerState['allDetectedTokens'];\n\n /**\n * Construct a Token Balances Controller.\n *\n * @param options - The controller options.\n * @param options.interval - Polling interval used to fetch new token balances.\n * @param options.state - Initial state to set on this controller.\n * @param options.messenger - The controller restricted messenger.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state = {},\n }: TokenBalancesControllerOptions) {\n super({\n name: controllerName,\n metadata,\n messenger,\n state: {\n ...getDefaultTokenBalancesState(),\n ...state,\n },\n });\n\n this.setIntervalLength(interval);\n\n // Set initial preference for querying multiple accounts, and subscribe to changes\n this.#queryMultipleAccounts = this.#calculateQueryMultipleAccounts(\n this.messagingSystem.call('PreferencesController:getState'),\n );\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n this.#onPreferencesStateChange.bind(this),\n );\n\n // Set initial tokens, and subscribe to changes\n ({\n allTokens: this.#allTokens,\n allDetectedTokens: this.#allDetectedTokens,\n } = this.messagingSystem.call('TokensController:getState'));\n\n this.messagingSystem.subscribe(\n 'TokensController:stateChange',\n this.#onTokensStateChange.bind(this),\n );\n\n // Subscribe to network state changes\n this.messagingSystem.subscribe(\n 'NetworkController:stateChange',\n this.#onNetworkStateChange.bind(this),\n );\n }\n\n /**\n * Determines whether to query all accounts, or just the selected account.\n * @param preferences - The preferences state.\n * @param preferences.isMultiAccountBalancesEnabled - whether to query all accounts (mobile).\n * @param preferences.useMultiAccountBalanceChecker - whether to query all accounts (extension).\n * @returns true if all accounts should be queried.\n */\n #calculateQueryMultipleAccounts = ({\n isMultiAccountBalancesEnabled,\n useMultiAccountBalanceChecker,\n }: PreferencesState & { useMultiAccountBalanceChecker?: boolean }) => {\n return Boolean(\n // Note: These settings have different names on extension vs mobile\n isMultiAccountBalancesEnabled || useMultiAccountBalanceChecker,\n );\n };\n\n /**\n * Handles the event for preferences state changes.\n * @param preferences - The preferences state.\n */\n #onPreferencesStateChange = (preferences: PreferencesState) => {\n // Update the user preference for whether to query multiple accounts.\n const queryMultipleAccounts =\n this.#calculateQueryMultipleAccounts(preferences);\n\n // Refresh when flipped off -> on\n const refresh = queryMultipleAccounts && !this.#queryMultipleAccounts;\n this.#queryMultipleAccounts = queryMultipleAccounts;\n\n if (refresh) {\n this.updateBalances().catch(console.error);\n }\n };\n\n /**\n * Handles the event for tokens state changes.\n * @param state - The token state.\n * @param state.allTokens - The state for imported tokens across all chains.\n * @param state.allDetectedTokens - The state for detected tokens across all chains.\n */\n #onTokensStateChange = ({\n allTokens,\n allDetectedTokens,\n }: TokensControllerState) => {\n // Refresh token balances on chains whose tokens have changed.\n const chainIds = this.#getChainIds(allTokens, allDetectedTokens);\n const chainIdsToUpdate = chainIds.filter(\n (chainId) =>\n !isEqual(this.#allTokens[chainId], allTokens[chainId]) ||\n !isEqual(this.#allDetectedTokens[chainId], allDetectedTokens[chainId]),\n );\n\n this.#allTokens = allTokens;\n this.#allDetectedTokens = allDetectedTokens;\n\n this.updateBalances({ chainIds: chainIdsToUpdate }).catch(console.error);\n };\n\n /**\n * Handles the event for network state changes.\n * @param _ - The network state.\n * @param patches - An array of patch operations performed on the network state.\n */\n #onNetworkStateChange(_: NetworkState, patches: Patch[]) {\n // Remove state for deleted networks\n for (const patch of patches) {\n if (\n patch.op === 'remove' &&\n patch.path[0] === 'networkConfigurationsByChainId'\n ) {\n const removedChainId = patch.path[1] as Hex;\n\n this.update((state) => {\n for (const accountAddress of Object.keys(state.tokenBalances)) {\n delete state.tokenBalances[accountAddress as Hex][removedChainId];\n }\n });\n }\n }\n }\n\n /**\n * Returns an array of chain ids that have tokens.\n * @param allTokens - The state for imported tokens across all chains.\n * @param allDetectedTokens - The state for detected tokens across all chains.\n * @returns An array of chain ids that have tokens.\n */\n #getChainIds = (\n allTokens: TokensControllerState['allTokens'],\n allDetectedTokens: TokensControllerState['allDetectedTokens'],\n ) =>\n [\n ...new Set([\n ...Object.keys(allTokens),\n ...Object.keys(allDetectedTokens),\n ]),\n ] as Hex[];\n\n /**\n * Polls for erc20 token balances.\n * @param input - The input for the poll.\n * @param input.chainId - The chain id to poll token balances on.\n */\n async _executePoll({ chainId }: TokenBalancesPollingInput) {\n await this.updateBalancesByChainId({ chainId });\n }\n\n /**\n * Updates the token balances for the given chain ids.\n * @param input - The input for the update.\n * @param input.chainIds - The chain ids to update token balances for.\n * Or omitted to update all chains that contain tokens.\n */\n async updateBalances({ chainIds }: { chainIds?: Hex[] } = {}) {\n chainIds ??= this.#getChainIds(this.#allTokens, this.#allDetectedTokens);\n\n await Promise.allSettled(\n chainIds.map((chainId) => this.updateBalancesByChainId({ chainId })),\n );\n }\n\n /**\n * Updates token balances for the given chain id.\n * @param input - The input for the update.\n * @param input.chainId - The chain id to update token balances on.\n */\n async updateBalancesByChainId({ chainId }: { chainId: Hex }) {\n const { address: selectedAccountAddress } = this.messagingSystem.call(\n 'AccountsController:getSelectedAccount',\n );\n\n const isSelectedAccount = (accountAddress: string) =>\n toChecksumHexAddress(accountAddress) ===\n toChecksumHexAddress(selectedAccountAddress);\n\n const accountTokenPairs: { accountAddress: Hex; tokenAddress: Hex }[] = [];\n\n const addTokens = ([accountAddress, tokens]: [string, Token[]]) =>\n this.#queryMultipleAccounts || isSelectedAccount(accountAddress)\n ? tokens.forEach((t) =>\n accountTokenPairs.push({\n accountAddress: accountAddress as Hex,\n tokenAddress: t.address as Hex,\n }),\n )\n : undefined;\n\n // Balances will be updated for both imported and detected tokens\n Object.entries(this.#allTokens[chainId] ?? {}).forEach(addTokens);\n Object.entries(this.#allDetectedTokens[chainId] ?? {}).forEach(addTokens);\n\n let results: MulticallResult[] = [];\n\n if (accountTokenPairs.length > 0) {\n const provider = new Web3Provider(\n this.#getNetworkClient(chainId).provider,\n );\n\n const calls = accountTokenPairs.map(\n ({ accountAddress, tokenAddress }) => ({\n contract: new Contract(tokenAddress, abiERC20, provider),\n functionSignature: 'balanceOf(address)',\n arguments: [accountAddress],\n }),\n );\n\n results = await multicallOrFallback(calls, chainId, provider);\n }\n\n this.update((state) => {\n // Reset so that when accounts or tokens are removed,\n // their balances are removed rather than left stale.\n for (const accountAddress of Object.keys(state.tokenBalances)) {\n state.tokenBalances[accountAddress as Hex][chainId] = {};\n }\n\n for (let i = 0; i < results.length; i++) {\n const { success, value } = results[i];\n const { accountAddress, tokenAddress } = accountTokenPairs[i];\n\n if (success) {\n ((state.tokenBalances[accountAddress] ??= {})[chainId] ??= {})[\n tokenAddress\n ] = toHex(value as BN);\n }\n }\n });\n }\n\n /**\n * Reset the controller state to the default state.\n */\n resetState() {\n this.update(() => {\n return getDefaultTokenBalancesState();\n });\n }\n\n /**\n * Returns the network client for a given chain id\n * @param chainId - The chain id to get the network client for.\n * @returns The network client for the given chain id.\n */\n #getNetworkClient(chainId: Hex) {\n const { networkConfigurationsByChainId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n\n const networkConfiguration = networkConfigurationsByChainId[chainId];\n if (!networkConfiguration) {\n throw new Error(\n `TokenBalancesController: No network configuration found for chainId ${chainId}`,\n );\n }\n\n const { networkClientId } =\n networkConfiguration.rpcEndpoints[\n networkConfiguration.defaultRpcEndpointIndex\n ];\n\n return this.messagingSystem.call(\n `NetworkController:getNetworkClientById`,\n networkClientId,\n );\n }\n}\n\nexport default TokenBalancesController;\n"]}
|
1
|
+
{"version":3,"file":"TokenBalancesController.cjs","sourceRoot":"","sources":["../src/TokenBalancesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,wDAAoD;AACpD,wDAAwD;AAWxD,iEAAyE;AACzE,mEAAuD;AAOvD,qEAA+E;AAS/E,mCAAiC;AAGjC,+CAAkD;AAQlD,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,MAAM,cAAc,GAAG,yBAAyB,CAAC;AAEjD,MAAM,QAAQ,GAAG;IACf,aAAa,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;CACnD,CAAC;AAkEF;;;;GA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F,CAAC;KACH;IAED,MAAM,EAAE,eAAe,EAAE,GACvB,oBAAoB,CAAC,YAAY,CAC/B,oBAAoB,CAAC,uBAAuB,CAC7C,CAAC;IAEJ,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAC9B,wCAAwC,EACxC,eAAe,CAChB,CAAC;AACJ,CAAC;AAGH,kBAAe,uBAAuB,CAAC","sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport { Web3Provider } from '@ethersproject/providers';\nimport type {\n AccountsControllerAccountRemovedEvent,\n AccountsControllerGetSelectedAccountAction,\n AccountsControllerListAccountsAction,\n} from '@metamask/accounts-controller';\nimport type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { toChecksumHexAddress, toHex } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type {\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n NetworkControllerStateChangeEvent,\n NetworkState,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n PreferencesState,\n} from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\nimport type BN from 'bn.js';\nimport type { Patch } from 'immer';\nimport { isEqual } from 'lodash';\n\nimport type { MulticallResult } from './multicall';\nimport { multicallOrFallback } from './multicall';\nimport type { Token } from './TokenRatesController';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerState,\n TokensControllerStateChangeEvent,\n} from './TokensController';\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst controllerName = 'TokenBalancesController';\n\nconst metadata = {\n tokenBalances: { persist: true, anonymous: false },\n};\n\n/**\n * Token balances controller options\n * @property interval - Polling interval used to fetch new token balances.\n * @property messenger - A messenger.\n * @property state - Initial state for the controller.\n */\ntype TokenBalancesControllerOptions = {\n interval?: number;\n messenger: TokenBalancesControllerMessenger;\n state?: Partial<TokenBalancesControllerState>;\n};\n\n/**\n * A mapping from account address to chain id to token address to balance.\n */\ntype TokenBalances = Record<Hex, Record<Hex, Record<Hex, Hex>>>;\n\n/**\n * Token balances controller state\n * @property tokenBalances - A mapping from account address to chain id to token address to balance.\n */\nexport type TokenBalancesControllerState = {\n tokenBalances: TokenBalances;\n};\n\nexport type TokenBalancesControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenBalancesControllerState\n>;\n\nexport type TokenBalancesControllerActions =\n TokenBalancesControllerGetStateAction;\n\nexport type AllowedActions =\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetStateAction\n | TokensControllerGetStateAction\n | PreferencesControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction\n | AccountsControllerListAccountsAction;\n\nexport type TokenBalancesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n TokenBalancesControllerState\n >;\n\nexport type TokenBalancesControllerEvents =\n TokenBalancesControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | TokensControllerStateChangeEvent\n | PreferencesControllerStateChangeEvent\n | NetworkControllerStateChangeEvent\n | AccountsControllerAccountRemovedEvent;\n\nexport type TokenBalancesControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n TokenBalancesControllerActions | AllowedActions,\n TokenBalancesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Get the default TokenBalancesController state.\n *\n * @returns The default TokenBalancesController state.\n */\nexport function getDefaultTokenBalancesState(): TokenBalancesControllerState {\n return {\n tokenBalances: {},\n };\n}\n\n/** The input to start polling for the {@link TokenBalancesController} */\nexport type TokenBalancesPollingInput = {\n chainId: Hex;\n};\n\n/**\n * Controller that passively polls on a set interval token balances\n * for tokens stored in the TokensController\n */\nexport class TokenBalancesController extends StaticIntervalPollingController<TokenBalancesPollingInput>()<\n typeof controllerName,\n TokenBalancesControllerState,\n TokenBalancesControllerMessenger\n> {\n #queryMultipleAccounts: boolean;\n\n #allTokens: TokensControllerState['allTokens'];\n\n #allDetectedTokens: TokensControllerState['allDetectedTokens'];\n\n /**\n * Construct a Token Balances Controller.\n *\n * @param options - The controller options.\n * @param options.interval - Polling interval used to fetch new token balances.\n * @param options.state - Initial state to set on this controller.\n * @param options.messenger - The controller restricted messenger.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state = {},\n }: TokenBalancesControllerOptions) {\n super({\n name: controllerName,\n metadata,\n messenger,\n state: {\n ...getDefaultTokenBalancesState(),\n ...state,\n },\n });\n\n this.setIntervalLength(interval);\n\n // Set initial preference for querying multiple accounts, and subscribe to changes\n this.#queryMultipleAccounts = this.#calculateQueryMultipleAccounts(\n this.messagingSystem.call('PreferencesController:getState'),\n );\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n this.#onPreferencesStateChange.bind(this),\n );\n\n // Set initial tokens, and subscribe to changes\n ({\n allTokens: this.#allTokens,\n allDetectedTokens: this.#allDetectedTokens,\n } = this.messagingSystem.call('TokensController:getState'));\n\n this.messagingSystem.subscribe(\n 'TokensController:stateChange',\n this.#onTokensStateChange.bind(this),\n );\n\n // Subscribe to network state changes\n this.messagingSystem.subscribe(\n 'NetworkController:stateChange',\n this.#onNetworkStateChange.bind(this),\n );\n\n // subscribe to account removed event to cleanup stale balances\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountRemoved',\n (accountId: string) => this.#handleOnAccountRemoved(accountId),\n );\n }\n\n /**\n * Determines whether to query all accounts, or just the selected account.\n * @param preferences - The preferences state.\n * @param preferences.isMultiAccountBalancesEnabled - whether to query all accounts (mobile).\n * @param preferences.useMultiAccountBalanceChecker - whether to query all accounts (extension).\n * @returns true if all accounts should be queried.\n */\n #calculateQueryMultipleAccounts = ({\n isMultiAccountBalancesEnabled,\n useMultiAccountBalanceChecker,\n }: PreferencesState & { useMultiAccountBalanceChecker?: boolean }) => {\n return Boolean(\n // Note: These settings have different names on extension vs mobile\n isMultiAccountBalancesEnabled || useMultiAccountBalanceChecker,\n );\n };\n\n /**\n * Handles the event for preferences state changes.\n * @param preferences - The preferences state.\n */\n #onPreferencesStateChange = (preferences: PreferencesState) => {\n // Update the user preference for whether to query multiple accounts.\n const queryMultipleAccounts =\n this.#calculateQueryMultipleAccounts(preferences);\n\n // Refresh when flipped off -> on\n const refresh = queryMultipleAccounts && !this.#queryMultipleAccounts;\n this.#queryMultipleAccounts = queryMultipleAccounts;\n\n if (refresh) {\n this.updateBalances().catch(console.error);\n }\n };\n\n /**\n * Handles the event for tokens state changes.\n * @param state - The token state.\n * @param state.allTokens - The state for imported tokens across all chains.\n * @param state.allDetectedTokens - The state for detected tokens across all chains.\n */\n #onTokensStateChange = ({\n allTokens,\n allDetectedTokens,\n }: TokensControllerState) => {\n // Refresh token balances on chains whose tokens have changed.\n const chainIds = this.#getChainIds(allTokens, allDetectedTokens);\n const chainIdsToUpdate = chainIds.filter(\n (chainId) =>\n !isEqual(this.#allTokens[chainId], allTokens[chainId]) ||\n !isEqual(this.#allDetectedTokens[chainId], allDetectedTokens[chainId]),\n );\n\n this.#allTokens = allTokens;\n this.#allDetectedTokens = allDetectedTokens;\n this.#handleTokensControllerStateChange({\n chainIds: chainIdsToUpdate,\n }).catch(console.error);\n };\n\n /**\n * Handles the event for network state changes.\n * @param _ - The network state.\n * @param patches - An array of patch operations performed on the network state.\n */\n #onNetworkStateChange(_: NetworkState, patches: Patch[]) {\n // Remove state for deleted networks\n for (const patch of patches) {\n if (\n patch.op === 'remove' &&\n patch.path[0] === 'networkConfigurationsByChainId'\n ) {\n const removedChainId = patch.path[1] as Hex;\n\n this.update((state) => {\n for (const accountAddress of Object.keys(state.tokenBalances)) {\n delete state.tokenBalances[accountAddress as Hex][removedChainId];\n }\n });\n }\n }\n }\n\n /**\n * Handles changes when an account has been removed.\n *\n * @param accountId - The account id being removed.\n */\n #handleOnAccountRemoved(accountId: string) {\n const accounts = this.messagingSystem.call(\n 'AccountsController:listAccounts',\n );\n const accountAddress = accounts.find(\n (account) => account.id === accountId,\n )?.address;\n if (!accountAddress) {\n return;\n }\n\n this.update((state) => {\n delete state.tokenBalances[accountAddress as `0x${string}`];\n });\n }\n\n /**\n * Returns an array of chain ids that have tokens.\n * @param allTokens - The state for imported tokens across all chains.\n * @param allDetectedTokens - The state for detected tokens across all chains.\n * @returns An array of chain ids that have tokens.\n */\n #getChainIds = (\n allTokens: TokensControllerState['allTokens'],\n allDetectedTokens: TokensControllerState['allDetectedTokens'],\n ) =>\n [\n ...new Set([\n ...Object.keys(allTokens),\n ...Object.keys(allDetectedTokens),\n ]),\n ] as Hex[];\n\n /**\n * Polls for erc20 token balances.\n * @param input - The input for the poll.\n * @param input.chainId - The chain id to poll token balances on.\n */\n async _executePoll({ chainId }: TokenBalancesPollingInput) {\n await this.updateBalancesByChainId({ chainId });\n }\n\n /**\n * Updates the token balances for the given chain ids.\n * @param input - The input for the update.\n * @param input.chainIds - The chain ids to update token balances for.\n * Or omitted to update all chains that contain tokens.\n */\n async updateBalances({ chainIds }: { chainIds?: Hex[] } = {}) {\n chainIds ??= this.#getChainIds(this.#allTokens, this.#allDetectedTokens);\n\n await Promise.allSettled(\n chainIds.map((chainId) => this.updateBalancesByChainId({ chainId })),\n );\n }\n\n async #handleTokensControllerStateChange({\n chainIds,\n }: { chainIds?: Hex[] } = {}) {\n const currentTokenBalancesState = this.messagingSystem.call(\n 'TokenBalancesController:getState',\n );\n const currentTokenBalances = currentTokenBalancesState.tokenBalances;\n const currentAllTokens = this.#allTokens;\n const chainIdsSet = new Set(chainIds);\n\n // first we check if the state change was due to a token being removed\n for (const currentAccount of Object.keys(currentTokenBalances)) {\n const allChains = currentTokenBalances[currentAccount as `0x${string}`];\n for (const currentChain of Object.keys(allChains)) {\n if (chainIds?.length && !chainIdsSet.has(currentChain as Hex)) {\n continue;\n }\n const tokensObject = allChains[currentChain as Hex];\n const allCurrentTokens = Object.keys(tokensObject);\n const existingTokensInState =\n currentAllTokens[currentChain as Hex]?.[\n currentAccount as `0x${string}`\n ] || [];\n const existingSet = new Set(\n existingTokensInState.map((elm) => elm.address),\n );\n\n for (const singleToken of allCurrentTokens) {\n if (!existingSet.has(singleToken)) {\n this.update((state) => {\n delete state.tokenBalances[currentAccount as Hex][\n currentChain as Hex\n ][singleToken as `0x${string}`];\n });\n }\n }\n }\n }\n\n // then we check if the state change was due to a token being added\n let shouldUpdate = false;\n for (const currentChain of Object.keys(currentAllTokens)) {\n if (chainIds?.length && !chainIdsSet.has(currentChain as Hex)) {\n continue;\n }\n const accountsPerChain = currentAllTokens[currentChain as Hex];\n\n for (const currentAccount of Object.keys(accountsPerChain)) {\n const tokensList = accountsPerChain[currentAccount as `0x${string}`];\n const tokenBalancesObject =\n currentTokenBalances[currentAccount as `0x${string}`]?.[\n currentChain as Hex\n ] || {};\n for (const singleToken of tokensList) {\n if (!tokenBalancesObject?.[singleToken.address as `0x${string}`]) {\n shouldUpdate = true;\n break;\n }\n }\n }\n }\n if (shouldUpdate) {\n await this.updateBalances({ chainIds }).catch(console.error);\n }\n }\n\n /**\n * Updates token balances for the given chain id.\n * @param input - The input for the update.\n * @param input.chainId - The chain id to update token balances on.\n */\n async updateBalancesByChainId({ chainId }: { chainId: Hex }) {\n const { address: selectedAccountAddress } = this.messagingSystem.call(\n 'AccountsController:getSelectedAccount',\n );\n\n const isSelectedAccount = (accountAddress: string) =>\n toChecksumHexAddress(accountAddress) ===\n toChecksumHexAddress(selectedAccountAddress);\n\n const accountTokenPairs: { accountAddress: Hex; tokenAddress: Hex }[] = [];\n\n const addTokens = ([accountAddress, tokens]: [string, Token[]]) =>\n this.#queryMultipleAccounts || isSelectedAccount(accountAddress)\n ? tokens.forEach((t) =>\n accountTokenPairs.push({\n accountAddress: accountAddress as Hex,\n tokenAddress: t.address as Hex,\n }),\n )\n : undefined;\n\n // Balances will be updated for both imported and detected tokens\n Object.entries(this.#allTokens[chainId] ?? {}).forEach(addTokens);\n Object.entries(this.#allDetectedTokens[chainId] ?? {}).forEach(addTokens);\n\n let results: MulticallResult[] = [];\n\n const currentTokenBalances = this.messagingSystem.call(\n 'TokenBalancesController:getState',\n );\n\n if (accountTokenPairs.length > 0) {\n const provider = new Web3Provider(\n this.#getNetworkClient(chainId).provider,\n );\n\n const calls = accountTokenPairs.map(\n ({ accountAddress, tokenAddress }) => ({\n contract: new Contract(tokenAddress, abiERC20, provider),\n functionSignature: 'balanceOf(address)',\n arguments: [accountAddress],\n }),\n );\n\n results = await multicallOrFallback(calls, chainId, provider);\n }\n\n const updatedResults: (MulticallResult & {\n isTokenBalanceValueChanged?: boolean;\n })[] = results.map((res, i) => {\n const { value } = res;\n const { accountAddress, tokenAddress } = accountTokenPairs[i];\n const currentTokenBalanceValueForAccount =\n currentTokenBalances.tokenBalances?.[accountAddress]?.[chainId]?.[\n tokenAddress\n ];\n const isTokenBalanceValueChanged =\n currentTokenBalanceValueForAccount !== toHex(value as BN);\n return {\n ...res,\n isTokenBalanceValueChanged,\n };\n });\n\n // if all values of isTokenBalanceValueChanged are false, return\n if (updatedResults.every((result) => !result.isTokenBalanceValueChanged)) {\n return;\n }\n\n this.update((state) => {\n for (let i = 0; i < updatedResults.length; i++) {\n const { success, value, isTokenBalanceValueChanged } =\n updatedResults[i];\n const { accountAddress, tokenAddress } = accountTokenPairs[i];\n if (success && isTokenBalanceValueChanged) {\n ((state.tokenBalances[accountAddress] ??= {})[chainId] ??= {})[\n tokenAddress\n ] = toHex(value as BN);\n }\n }\n });\n }\n\n /**\n * Reset the controller state to the default state.\n */\n resetState() {\n this.update(() => {\n return getDefaultTokenBalancesState();\n });\n }\n\n /**\n * Returns the network client for a given chain id\n * @param chainId - The chain id to get the network client for.\n * @returns The network client for the given chain id.\n */\n #getNetworkClient(chainId: Hex) {\n const { networkConfigurationsByChainId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n\n const networkConfiguration = networkConfigurationsByChainId[chainId];\n if (!networkConfiguration) {\n throw new Error(\n `TokenBalancesController: No network configuration found for chainId ${chainId}`,\n );\n }\n\n const { networkClientId } =\n networkConfiguration.rpcEndpoints[\n networkConfiguration.defaultRpcEndpointIndex\n ];\n\n return this.messagingSystem.call(\n `NetworkController:getNetworkClientById`,\n networkClientId,\n );\n }\n}\n\nexport default TokenBalancesController;\n"]}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import type { AccountsControllerGetSelectedAccountAction } from "@metamask/accounts-controller";
|
1
|
+
import type { AccountsControllerAccountRemovedEvent, AccountsControllerGetSelectedAccountAction, AccountsControllerListAccountsAction } from "@metamask/accounts-controller";
|
2
2
|
import type { RestrictedMessenger, ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
|
3
3
|
import type { NetworkControllerGetNetworkClientByIdAction, NetworkControllerGetStateAction, NetworkControllerStateChangeEvent } from "@metamask/network-controller";
|
4
4
|
import type { PreferencesControllerGetStateAction, PreferencesControllerStateChangeEvent } from "@metamask/preferences-controller";
|
@@ -29,10 +29,10 @@ export type TokenBalancesControllerState = {
|
|
29
29
|
};
|
30
30
|
export type TokenBalancesControllerGetStateAction = ControllerGetStateAction<typeof controllerName, TokenBalancesControllerState>;
|
31
31
|
export type TokenBalancesControllerActions = TokenBalancesControllerGetStateAction;
|
32
|
-
export type AllowedActions = NetworkControllerGetNetworkClientByIdAction | NetworkControllerGetStateAction | TokensControllerGetStateAction | PreferencesControllerGetStateAction | AccountsControllerGetSelectedAccountAction;
|
32
|
+
export type AllowedActions = NetworkControllerGetNetworkClientByIdAction | NetworkControllerGetStateAction | TokensControllerGetStateAction | PreferencesControllerGetStateAction | AccountsControllerGetSelectedAccountAction | AccountsControllerListAccountsAction;
|
33
33
|
export type TokenBalancesControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, TokenBalancesControllerState>;
|
34
34
|
export type TokenBalancesControllerEvents = TokenBalancesControllerStateChangeEvent;
|
35
|
-
export type AllowedEvents = TokensControllerStateChangeEvent | PreferencesControllerStateChangeEvent | NetworkControllerStateChangeEvent;
|
35
|
+
export type AllowedEvents = TokensControllerStateChangeEvent | PreferencesControllerStateChangeEvent | NetworkControllerStateChangeEvent | AccountsControllerAccountRemovedEvent;
|
36
36
|
export type TokenBalancesControllerMessenger = RestrictedMessenger<typeof controllerName, TokenBalancesControllerActions | AllowedActions, TokenBalancesControllerEvents | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
|
37
37
|
/**
|
38
38
|
* Get the default TokenBalancesController state.
|
@@ -56,9 +56,7 @@ declare const TokenBalancesController_base: (abstract new (...args: any[]) => {
|
|
56
56
|
_executePoll(input: TokenBalancesPollingInput): Promise<void>;
|
57
57
|
startPolling(input: TokenBalancesPollingInput): string;
|
58
58
|
stopAllPolling(): void;
|
59
|
-
stopPollingByPollingToken(pollingToken: string): void;
|
60
|
-
* A mapping from account address to chain id to token address to balance.
|
61
|
-
*/
|
59
|
+
stopPollingByPollingToken(pollingToken: string): void;
|
62
60
|
onPollingComplete(input: TokenBalancesPollingInput, callback: (input: TokenBalancesPollingInput) => void): void;
|
63
61
|
}) & typeof import("@metamask/base-controller").BaseController;
|
64
62
|
/**
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"TokenBalancesController.d.cts","sourceRoot":"","sources":["../src/TokenBalancesController.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,
|
1
|
+
{"version":3,"file":"TokenBalancesController.d.cts","sourceRoot":"","sources":["../src/TokenBalancesController.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,qCAAqC,EACrC,0CAA0C,EAC1C,oCAAoC,EACrC,sCAAsC;AACvC,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AAGnC,OAAO,KAAK,EACV,2CAA2C,EAC3C,+BAA+B,EAC/B,iCAAiC,EAElC,qCAAqC;AAEtC,OAAO,KAAK,EACV,mCAAmC,EACnC,qCAAqC,EAEtC,yCAAyC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAQ3C,OAAO,KAAK,EACV,8BAA8B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AAM,MAAM,yBAAyB,GAAG;IACtC,OAAO,EAAE,GAAG,CAAC;CACd,CAAC;;;;;;;;;;;;;;;;AAEF;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,6BAC3C,OAAO,cAAc,EACrB,4BAA4B,EAC5B,gCAAgC,CACjC;;IAOC;;;;;;;OAOG;gBACS,EACV,QAA2B,EAC3B,SAAS,EACT,KAAU,GACX,EAAE,8BAA8B;IAwKjC;;;;OAIG;IACG,YAAY,CAAC,EAAE,OAAO,EAAE,EAAE,yBAAyB;IAIzD;;;;;OAKG;IACG,cAAc,CAAC,EAAE,QAAQ,EAAE,GAAE;QAAE,QAAQ,CAAC,EAAE,GAAG,EAAE,CAAA;KAAO;IA0E5D;;;;OAIG;IACG,uBAAuB,CAAC,EAAE,OAAO,EAAE,EAAE;QAAE,OAAO,EAAE,GAAG,CAAA;KAAE;IAmF3D;;OAEG;IACH,UAAU;CAiCX;AAED,eAAe,uBAAuB,CAAC"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import type { AccountsControllerGetSelectedAccountAction } from "@metamask/accounts-controller";
|
1
|
+
import type { AccountsControllerAccountRemovedEvent, AccountsControllerGetSelectedAccountAction, AccountsControllerListAccountsAction } from "@metamask/accounts-controller";
|
2
2
|
import type { RestrictedMessenger, ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
|
3
3
|
import type { NetworkControllerGetNetworkClientByIdAction, NetworkControllerGetStateAction, NetworkControllerStateChangeEvent } from "@metamask/network-controller";
|
4
4
|
import type { PreferencesControllerGetStateAction, PreferencesControllerStateChangeEvent } from "@metamask/preferences-controller";
|
@@ -29,10 +29,10 @@ export type TokenBalancesControllerState = {
|
|
29
29
|
};
|
30
30
|
export type TokenBalancesControllerGetStateAction = ControllerGetStateAction<typeof controllerName, TokenBalancesControllerState>;
|
31
31
|
export type TokenBalancesControllerActions = TokenBalancesControllerGetStateAction;
|
32
|
-
export type AllowedActions = NetworkControllerGetNetworkClientByIdAction | NetworkControllerGetStateAction | TokensControllerGetStateAction | PreferencesControllerGetStateAction | AccountsControllerGetSelectedAccountAction;
|
32
|
+
export type AllowedActions = NetworkControllerGetNetworkClientByIdAction | NetworkControllerGetStateAction | TokensControllerGetStateAction | PreferencesControllerGetStateAction | AccountsControllerGetSelectedAccountAction | AccountsControllerListAccountsAction;
|
33
33
|
export type TokenBalancesControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, TokenBalancesControllerState>;
|
34
34
|
export type TokenBalancesControllerEvents = TokenBalancesControllerStateChangeEvent;
|
35
|
-
export type AllowedEvents = TokensControllerStateChangeEvent | PreferencesControllerStateChangeEvent | NetworkControllerStateChangeEvent;
|
35
|
+
export type AllowedEvents = TokensControllerStateChangeEvent | PreferencesControllerStateChangeEvent | NetworkControllerStateChangeEvent | AccountsControllerAccountRemovedEvent;
|
36
36
|
export type TokenBalancesControllerMessenger = RestrictedMessenger<typeof controllerName, TokenBalancesControllerActions | AllowedActions, TokenBalancesControllerEvents | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
|
37
37
|
/**
|
38
38
|
* Get the default TokenBalancesController state.
|
@@ -56,9 +56,7 @@ declare const TokenBalancesController_base: (abstract new (...args: any[]) => {
|
|
56
56
|
_executePoll(input: TokenBalancesPollingInput): Promise<void>;
|
57
57
|
startPolling(input: TokenBalancesPollingInput): string;
|
58
58
|
stopAllPolling(): void;
|
59
|
-
stopPollingByPollingToken(pollingToken: string): void;
|
60
|
-
* A mapping from account address to chain id to token address to balance.
|
61
|
-
*/
|
59
|
+
stopPollingByPollingToken(pollingToken: string): void;
|
62
60
|
onPollingComplete(input: TokenBalancesPollingInput, callback: (input: TokenBalancesPollingInput) => void): void;
|
63
61
|
}) & typeof import("@metamask/base-controller").BaseController;
|
64
62
|
/**
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"TokenBalancesController.d.mts","sourceRoot":"","sources":["../src/TokenBalancesController.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,
|
1
|
+
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xB,OAAO,cAAc,EACrB,4BAA4B,CAC7B,CAAC;AAEJ,MAAM,MAAM,6BAA6B,GACvC,uCAAuC,CAAC;AAE1C,MAAM,MAAM,aAAa,GACrB,gCAAgC,GAChC,qCAAqC,GACrC,iCAAiC,GACjC,qCAAqC,CAAC;AAE1C,MAAM,MAAM,gCAAgC,GAAG,mBAAmB,CAChE,OAAO,cAAc,EACrB,8BAA8B,GAAG,cAAc,EAC/C,6BAA6B,GAAG,aAAa,EAC7C,cAAc,CAAC,MAAM,CAAC,EACtB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,4BAA4B,IAAI,4BAA4B,CAI3E;AAED,yEAAyE;AACzE,MAAM,MAAM,yBAAyB,GAAG;IACtC,OAAO,EAAE,GAAG,CAAC;CACd,CAAC;;;;;;;;;;;;;;;;AAEF;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,6BAC3C,OAAO,cAAc,EACrB,4BAA4B,EAC5B,gCAAgC,CACjC;;IAOC;;;;;;;OAOG;gBACS,EACV,QAA2B,EAC3B,SAAS,EACT,KAAU,GACX,EAAE,8BAA8B;IAwKjC;;;;OAIG;IACG,YAAY,CAAC,EAAE,OAAO,EAAE,EAAE,yBAAyB;IAIzD;;;;;OAKG;IACG,cAAc,CAAC,EAAE,QAAQ,EAAE,GAAE;QAAE,QAAQ,CAAC,EAAE,GAAG,EAAE,CAAA;KAAO;IA0E5D;;;;OAIG;IACG,uBAAuB,CAAC,EAAE,OAAO,EAAE,EAAE;QAAE,OAAO,EAAE,GAAG,CAAA;KAAE;IAmF3D;;OAEG;IACH,UAAU;CAiCX;AAED,eAAe,uBAAuB,CAAC"}
|
@@ -9,7 +9,7 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
10
10
|
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
11
11
|
};
|
12
|
-
var _TokenBalancesController_instances, _TokenBalancesController_queryMultipleAccounts, _TokenBalancesController_allTokens, _TokenBalancesController_allDetectedTokens, _TokenBalancesController_calculateQueryMultipleAccounts, _TokenBalancesController_onPreferencesStateChange, _TokenBalancesController_onTokensStateChange, _TokenBalancesController_onNetworkStateChange, _TokenBalancesController_getChainIds, _TokenBalancesController_getNetworkClient;
|
12
|
+
var _TokenBalancesController_instances, _TokenBalancesController_queryMultipleAccounts, _TokenBalancesController_allTokens, _TokenBalancesController_allDetectedTokens, _TokenBalancesController_calculateQueryMultipleAccounts, _TokenBalancesController_onPreferencesStateChange, _TokenBalancesController_onTokensStateChange, _TokenBalancesController_onNetworkStateChange, _TokenBalancesController_handleOnAccountRemoved, _TokenBalancesController_getChainIds, _TokenBalancesController_handleTokensControllerStateChange, _TokenBalancesController_getNetworkClient;
|
13
13
|
import { Contract } from "@ethersproject/contracts";
|
14
14
|
import { Web3Provider } from "@ethersproject/providers";
|
15
15
|
import { toChecksumHexAddress, toHex } from "@metamask/controller-utils";
|
@@ -100,7 +100,9 @@ export class TokenBalancesController extends StaticIntervalPollingController() {
|
|
100
100
|
!isEqual(__classPrivateFieldGet(this, _TokenBalancesController_allDetectedTokens, "f")[chainId], allDetectedTokens[chainId]));
|
101
101
|
__classPrivateFieldSet(this, _TokenBalancesController_allTokens, allTokens, "f");
|
102
102
|
__classPrivateFieldSet(this, _TokenBalancesController_allDetectedTokens, allDetectedTokens, "f");
|
103
|
-
this
|
103
|
+
__classPrivateFieldGet(this, _TokenBalancesController_instances, "m", _TokenBalancesController_handleTokensControllerStateChange).call(this, {
|
104
|
+
chainIds: chainIdsToUpdate,
|
105
|
+
}).catch(console.error);
|
104
106
|
});
|
105
107
|
/**
|
106
108
|
* Returns an array of chain ids that have tokens.
|
@@ -126,6 +128,8 @@ export class TokenBalancesController extends StaticIntervalPollingController() {
|
|
126
128
|
this.messagingSystem.subscribe('TokensController:stateChange', __classPrivateFieldGet(this, _TokenBalancesController_onTokensStateChange, "f").bind(this));
|
127
129
|
// Subscribe to network state changes
|
128
130
|
this.messagingSystem.subscribe('NetworkController:stateChange', __classPrivateFieldGet(this, _TokenBalancesController_instances, "m", _TokenBalancesController_onNetworkStateChange).bind(this));
|
131
|
+
// subscribe to account removed event to cleanup stale balances
|
132
|
+
this.messagingSystem.subscribe('AccountsController:accountRemoved', (accountId) => __classPrivateFieldGet(this, _TokenBalancesController_instances, "m", _TokenBalancesController_handleOnAccountRemoved).call(this, accountId));
|
129
133
|
}
|
130
134
|
/**
|
131
135
|
* Polls for erc20 token balances.
|
@@ -165,6 +169,7 @@ export class TokenBalancesController extends StaticIntervalPollingController() {
|
|
165
169
|
Object.entries(__classPrivateFieldGet(this, _TokenBalancesController_allTokens, "f")[chainId] ?? {}).forEach(addTokens);
|
166
170
|
Object.entries(__classPrivateFieldGet(this, _TokenBalancesController_allDetectedTokens, "f")[chainId] ?? {}).forEach(addTokens);
|
167
171
|
let results = [];
|
172
|
+
const currentTokenBalances = this.messagingSystem.call('TokenBalancesController:getState');
|
168
173
|
if (accountTokenPairs.length > 0) {
|
169
174
|
const provider = new Web3Provider(__classPrivateFieldGet(this, _TokenBalancesController_instances, "m", _TokenBalancesController_getNetworkClient).call(this, chainId).provider);
|
170
175
|
const calls = accountTokenPairs.map(({ accountAddress, tokenAddress }) => ({
|
@@ -174,17 +179,26 @@ export class TokenBalancesController extends StaticIntervalPollingController() {
|
|
174
179
|
}));
|
175
180
|
results = await multicallOrFallback(calls, chainId, provider);
|
176
181
|
}
|
182
|
+
const updatedResults = results.map((res, i) => {
|
183
|
+
const { value } = res;
|
184
|
+
const { accountAddress, tokenAddress } = accountTokenPairs[i];
|
185
|
+
const currentTokenBalanceValueForAccount = currentTokenBalances.tokenBalances?.[accountAddress]?.[chainId]?.[tokenAddress];
|
186
|
+
const isTokenBalanceValueChanged = currentTokenBalanceValueForAccount !== toHex(value);
|
187
|
+
return {
|
188
|
+
...res,
|
189
|
+
isTokenBalanceValueChanged,
|
190
|
+
};
|
191
|
+
});
|
192
|
+
// if all values of isTokenBalanceValueChanged are false, return
|
193
|
+
if (updatedResults.every((result) => !result.isTokenBalanceValueChanged)) {
|
194
|
+
return;
|
195
|
+
}
|
177
196
|
this.update((state) => {
|
178
197
|
var _a, _b;
|
179
|
-
|
180
|
-
|
181
|
-
for (const accountAddress of Object.keys(state.tokenBalances)) {
|
182
|
-
state.tokenBalances[accountAddress][chainId] = {};
|
183
|
-
}
|
184
|
-
for (let i = 0; i < results.length; i++) {
|
185
|
-
const { success, value } = results[i];
|
198
|
+
for (let i = 0; i < updatedResults.length; i++) {
|
199
|
+
const { success, value, isTokenBalanceValueChanged } = updatedResults[i];
|
186
200
|
const { accountAddress, tokenAddress } = accountTokenPairs[i];
|
187
|
-
if (success) {
|
201
|
+
if (success && isTokenBalanceValueChanged) {
|
188
202
|
((_b = ((_a = state.tokenBalances)[accountAddress] ?? (_a[accountAddress] = {})))[chainId] ?? (_b[chainId] = {}))[tokenAddress] = toHex(value);
|
189
203
|
}
|
190
204
|
}
|
@@ -212,6 +226,61 @@ _TokenBalancesController_queryMultipleAccounts = new WeakMap(), _TokenBalancesCo
|
|
212
226
|
});
|
213
227
|
}
|
214
228
|
}
|
229
|
+
}, _TokenBalancesController_handleOnAccountRemoved = function _TokenBalancesController_handleOnAccountRemoved(accountId) {
|
230
|
+
const accounts = this.messagingSystem.call('AccountsController:listAccounts');
|
231
|
+
const accountAddress = accounts.find((account) => account.id === accountId)?.address;
|
232
|
+
if (!accountAddress) {
|
233
|
+
return;
|
234
|
+
}
|
235
|
+
this.update((state) => {
|
236
|
+
delete state.tokenBalances[accountAddress];
|
237
|
+
});
|
238
|
+
}, _TokenBalancesController_handleTokensControllerStateChange = async function _TokenBalancesController_handleTokensControllerStateChange({ chainIds, } = {}) {
|
239
|
+
const currentTokenBalancesState = this.messagingSystem.call('TokenBalancesController:getState');
|
240
|
+
const currentTokenBalances = currentTokenBalancesState.tokenBalances;
|
241
|
+
const currentAllTokens = __classPrivateFieldGet(this, _TokenBalancesController_allTokens, "f");
|
242
|
+
const chainIdsSet = new Set(chainIds);
|
243
|
+
// first we check if the state change was due to a token being removed
|
244
|
+
for (const currentAccount of Object.keys(currentTokenBalances)) {
|
245
|
+
const allChains = currentTokenBalances[currentAccount];
|
246
|
+
for (const currentChain of Object.keys(allChains)) {
|
247
|
+
if (chainIds?.length && !chainIdsSet.has(currentChain)) {
|
248
|
+
continue;
|
249
|
+
}
|
250
|
+
const tokensObject = allChains[currentChain];
|
251
|
+
const allCurrentTokens = Object.keys(tokensObject);
|
252
|
+
const existingTokensInState = currentAllTokens[currentChain]?.[currentAccount] || [];
|
253
|
+
const existingSet = new Set(existingTokensInState.map((elm) => elm.address));
|
254
|
+
for (const singleToken of allCurrentTokens) {
|
255
|
+
if (!existingSet.has(singleToken)) {
|
256
|
+
this.update((state) => {
|
257
|
+
delete state.tokenBalances[currentAccount][currentChain][singleToken];
|
258
|
+
});
|
259
|
+
}
|
260
|
+
}
|
261
|
+
}
|
262
|
+
}
|
263
|
+
// then we check if the state change was due to a token being added
|
264
|
+
let shouldUpdate = false;
|
265
|
+
for (const currentChain of Object.keys(currentAllTokens)) {
|
266
|
+
if (chainIds?.length && !chainIdsSet.has(currentChain)) {
|
267
|
+
continue;
|
268
|
+
}
|
269
|
+
const accountsPerChain = currentAllTokens[currentChain];
|
270
|
+
for (const currentAccount of Object.keys(accountsPerChain)) {
|
271
|
+
const tokensList = accountsPerChain[currentAccount];
|
272
|
+
const tokenBalancesObject = currentTokenBalances[currentAccount]?.[currentChain] || {};
|
273
|
+
for (const singleToken of tokensList) {
|
274
|
+
if (!tokenBalancesObject?.[singleToken.address]) {
|
275
|
+
shouldUpdate = true;
|
276
|
+
break;
|
277
|
+
}
|
278
|
+
}
|
279
|
+
}
|
280
|
+
}
|
281
|
+
if (shouldUpdate) {
|
282
|
+
await this.updateBalances({ chainIds }).catch(console.error);
|
283
|
+
}
|
215
284
|
}, _TokenBalancesController_getNetworkClient = function _TokenBalancesController_getNetworkClient(chainId) {
|
216
285
|
const { networkConfigurationsByChainId } = this.messagingSystem.call('NetworkController:getState');
|
217
286
|
const networkConfiguration = networkConfigurationsByChainId[chainId];
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"TokenBalancesController.mjs","sourceRoot":"","sources":["../src/TokenBalancesController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,QAAQ,EAAE,iCAAiC;AACpD,OAAO,EAAE,YAAY,EAAE,iCAAiC;AAOxD,OAAO,EAAE,oBAAoB,EAAE,KAAK,EAAE,mCAAmC;AACzE,OAAO,EAAE,QAAQ,EAAE,oCAAoC;AAOvD,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;;;AAY/E,OAAO,EAAE,mBAAmB,EAAE,wBAAoB;AAQlD,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,MAAM,cAAc,GAAG,yBAAyB,CAAC;AAEjD,MAAM,QAAQ,GAAG;IACf,aAAa,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;CACnD,CAAC;AAgEF;;;;GAIG;AACH,MAAM,UAAU,4BAA4B;IAC1C,OAAO;QACL,aAAa,EAAE,EAAE;KAClB,CAAC;AACJ,CAAC;AAOD;;;GAGG;AACH,MAAM,OAAO,uBAAwB,SAAQ,+BAA+B,EAI3E;IAOC;;;;;;;OAOG;IACH,YAAY,EACV,QAAQ,GAAG,gBAAgB,EAC3B,SAAS,EACT,KAAK,GAAG,EAAE,GACqB;;QAC/B,KAAK,CAAC;YACJ,IAAI,EAAE,cAAc;YACpB,QAAQ;YACR,SAAS;YACT,KAAK,EAAE;gBACL,GAAG,4BAA4B,EAAE;gBACjC,GAAG,KAAK;aACT;SACF,CAAC,CAAC;;QA3BL,iEAAgC;QAEhC,qDAA+C;QAE/C,6DAA+D;QAsD/D;;;;;;WAMG;QACH,kEAAkC,CAAC,EAC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B,wCAAwC,EACxC,eAAe,CAChB,CAAC;AACJ,CAAC;AAGH,eAAe,uBAAuB,CAAC","sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport { Web3Provider } from '@ethersproject/providers';\nimport type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { toChecksumHexAddress, toHex } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type {\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n NetworkControllerStateChangeEvent,\n NetworkState,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n PreferencesState,\n} from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\nimport type BN from 'bn.js';\nimport type { Patch } from 'immer';\nimport { isEqual } from 'lodash';\n\nimport type { MulticallResult } from './multicall';\nimport { multicallOrFallback } from './multicall';\nimport type { Token } from './TokenRatesController';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerState,\n TokensControllerStateChangeEvent,\n} from './TokensController';\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst controllerName = 'TokenBalancesController';\n\nconst metadata = {\n tokenBalances: { persist: true, anonymous: false },\n};\n\n/**\n * Token balances controller options\n * @property interval - Polling interval used to fetch new token balances.\n * @property messenger - A messenger.\n * @property state - Initial state for the controller.\n */\ntype TokenBalancesControllerOptions = {\n interval?: number;\n messenger: TokenBalancesControllerMessenger;\n state?: Partial<TokenBalancesControllerState>;\n};\n\n/**\n * A mapping from account address to chain id to token address to balance.\n */\ntype TokenBalances = Record<Hex, Record<Hex, Record<Hex, Hex>>>;\n\n/**\n * Token balances controller state\n * @property tokenBalances - A mapping from account address to chain id to token address to balance.\n */\nexport type TokenBalancesControllerState = {\n tokenBalances: TokenBalances;\n};\n\nexport type TokenBalancesControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenBalancesControllerState\n>;\n\nexport type TokenBalancesControllerActions =\n TokenBalancesControllerGetStateAction;\n\nexport type AllowedActions =\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetStateAction\n | TokensControllerGetStateAction\n | PreferencesControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction;\n\nexport type TokenBalancesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n TokenBalancesControllerState\n >;\n\nexport type TokenBalancesControllerEvents =\n TokenBalancesControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | TokensControllerStateChangeEvent\n | PreferencesControllerStateChangeEvent\n | NetworkControllerStateChangeEvent;\n\nexport type TokenBalancesControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n TokenBalancesControllerActions | AllowedActions,\n TokenBalancesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Get the default TokenBalancesController state.\n *\n * @returns The default TokenBalancesController state.\n */\nexport function getDefaultTokenBalancesState(): TokenBalancesControllerState {\n return {\n tokenBalances: {},\n };\n}\n\n/** The input to start polling for the {@link TokenBalancesController} */\nexport type TokenBalancesPollingInput = {\n chainId: Hex;\n};\n\n/**\n * Controller that passively polls on a set interval token balances\n * for tokens stored in the TokensController\n */\nexport class TokenBalancesController extends StaticIntervalPollingController<TokenBalancesPollingInput>()<\n typeof controllerName,\n TokenBalancesControllerState,\n TokenBalancesControllerMessenger\n> {\n #queryMultipleAccounts: boolean;\n\n #allTokens: TokensControllerState['allTokens'];\n\n #allDetectedTokens: TokensControllerState['allDetectedTokens'];\n\n /**\n * Construct a Token Balances Controller.\n *\n * @param options - The controller options.\n * @param options.interval - Polling interval used to fetch new token balances.\n * @param options.state - Initial state to set on this controller.\n * @param options.messenger - The controller restricted messenger.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state = {},\n }: TokenBalancesControllerOptions) {\n super({\n name: controllerName,\n metadata,\n messenger,\n state: {\n ...getDefaultTokenBalancesState(),\n ...state,\n },\n });\n\n this.setIntervalLength(interval);\n\n // Set initial preference for querying multiple accounts, and subscribe to changes\n this.#queryMultipleAccounts = this.#calculateQueryMultipleAccounts(\n this.messagingSystem.call('PreferencesController:getState'),\n );\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n this.#onPreferencesStateChange.bind(this),\n );\n\n // Set initial tokens, and subscribe to changes\n ({\n allTokens: this.#allTokens,\n allDetectedTokens: this.#allDetectedTokens,\n } = this.messagingSystem.call('TokensController:getState'));\n\n this.messagingSystem.subscribe(\n 'TokensController:stateChange',\n this.#onTokensStateChange.bind(this),\n );\n\n // Subscribe to network state changes\n this.messagingSystem.subscribe(\n 'NetworkController:stateChange',\n this.#onNetworkStateChange.bind(this),\n );\n }\n\n /**\n * Determines whether to query all accounts, or just the selected account.\n * @param preferences - The preferences state.\n * @param preferences.isMultiAccountBalancesEnabled - whether to query all accounts (mobile).\n * @param preferences.useMultiAccountBalanceChecker - whether to query all accounts (extension).\n * @returns true if all accounts should be queried.\n */\n #calculateQueryMultipleAccounts = ({\n isMultiAccountBalancesEnabled,\n useMultiAccountBalanceChecker,\n }: PreferencesState & { useMultiAccountBalanceChecker?: boolean }) => {\n return Boolean(\n // Note: These settings have different names on extension vs mobile\n isMultiAccountBalancesEnabled || useMultiAccountBalanceChecker,\n );\n };\n\n /**\n * Handles the event for preferences state changes.\n * @param preferences - The preferences state.\n */\n #onPreferencesStateChange = (preferences: PreferencesState) => {\n // Update the user preference for whether to query multiple accounts.\n const queryMultipleAccounts =\n this.#calculateQueryMultipleAccounts(preferences);\n\n // Refresh when flipped off -> on\n const refresh = queryMultipleAccounts && !this.#queryMultipleAccounts;\n this.#queryMultipleAccounts = queryMultipleAccounts;\n\n if (refresh) {\n this.updateBalances().catch(console.error);\n }\n };\n\n /**\n * Handles the event for tokens state changes.\n * @param state - The token state.\n * @param state.allTokens - The state for imported tokens across all chains.\n * @param state.allDetectedTokens - The state for detected tokens across all chains.\n */\n #onTokensStateChange = ({\n allTokens,\n allDetectedTokens,\n }: TokensControllerState) => {\n // Refresh token balances on chains whose tokens have changed.\n const chainIds = this.#getChainIds(allTokens, allDetectedTokens);\n const chainIdsToUpdate = chainIds.filter(\n (chainId) =>\n !isEqual(this.#allTokens[chainId], allTokens[chainId]) ||\n !isEqual(this.#allDetectedTokens[chainId], allDetectedTokens[chainId]),\n );\n\n this.#allTokens = allTokens;\n this.#allDetectedTokens = allDetectedTokens;\n\n this.updateBalances({ chainIds: chainIdsToUpdate }).catch(console.error);\n };\n\n /**\n * Handles the event for network state changes.\n * @param _ - The network state.\n * @param patches - An array of patch operations performed on the network state.\n */\n #onNetworkStateChange(_: NetworkState, patches: Patch[]) {\n // Remove state for deleted networks\n for (const patch of patches) {\n if (\n patch.op === 'remove' &&\n patch.path[0] === 'networkConfigurationsByChainId'\n ) {\n const removedChainId = patch.path[1] as Hex;\n\n this.update((state) => {\n for (const accountAddress of Object.keys(state.tokenBalances)) {\n delete state.tokenBalances[accountAddress as Hex][removedChainId];\n }\n });\n }\n }\n }\n\n /**\n * Returns an array of chain ids that have tokens.\n * @param allTokens - The state for imported tokens across all chains.\n * @param allDetectedTokens - The state for detected tokens across all chains.\n * @returns An array of chain ids that have tokens.\n */\n #getChainIds = (\n allTokens: TokensControllerState['allTokens'],\n allDetectedTokens: TokensControllerState['allDetectedTokens'],\n ) =>\n [\n ...new Set([\n ...Object.keys(allTokens),\n ...Object.keys(allDetectedTokens),\n ]),\n ] as Hex[];\n\n /**\n * Polls for erc20 token balances.\n * @param input - The input for the poll.\n * @param input.chainId - The chain id to poll token balances on.\n */\n async _executePoll({ chainId }: TokenBalancesPollingInput) {\n await this.updateBalancesByChainId({ chainId });\n }\n\n /**\n * Updates the token balances for the given chain ids.\n * @param input - The input for the update.\n * @param input.chainIds - The chain ids to update token balances for.\n * Or omitted to update all chains that contain tokens.\n */\n async updateBalances({ chainIds }: { chainIds?: Hex[] } = {}) {\n chainIds ??= this.#getChainIds(this.#allTokens, this.#allDetectedTokens);\n\n await Promise.allSettled(\n chainIds.map((chainId) => this.updateBalancesByChainId({ chainId })),\n );\n }\n\n /**\n * Updates token balances for the given chain id.\n * @param input - The input for the update.\n * @param input.chainId - The chain id to update token balances on.\n */\n async updateBalancesByChainId({ chainId }: { chainId: Hex }) {\n const { address: selectedAccountAddress } = this.messagingSystem.call(\n 'AccountsController:getSelectedAccount',\n );\n\n const isSelectedAccount = (accountAddress: string) =>\n toChecksumHexAddress(accountAddress) ===\n toChecksumHexAddress(selectedAccountAddress);\n\n const accountTokenPairs: { accountAddress: Hex; tokenAddress: Hex }[] = [];\n\n const addTokens = ([accountAddress, tokens]: [string, Token[]]) =>\n this.#queryMultipleAccounts || isSelectedAccount(accountAddress)\n ? tokens.forEach((t) =>\n accountTokenPairs.push({\n accountAddress: accountAddress as Hex,\n tokenAddress: t.address as Hex,\n }),\n )\n : undefined;\n\n // Balances will be updated for both imported and detected tokens\n Object.entries(this.#allTokens[chainId] ?? {}).forEach(addTokens);\n Object.entries(this.#allDetectedTokens[chainId] ?? {}).forEach(addTokens);\n\n let results: MulticallResult[] = [];\n\n if (accountTokenPairs.length > 0) {\n const provider = new Web3Provider(\n this.#getNetworkClient(chainId).provider,\n );\n\n const calls = accountTokenPairs.map(\n ({ accountAddress, tokenAddress }) => ({\n contract: new Contract(tokenAddress, abiERC20, provider),\n functionSignature: 'balanceOf(address)',\n arguments: [accountAddress],\n }),\n );\n\n results = await multicallOrFallback(calls, chainId, provider);\n }\n\n this.update((state) => {\n // Reset so that when accounts or tokens are removed,\n // their balances are removed rather than left stale.\n for (const accountAddress of Object.keys(state.tokenBalances)) {\n state.tokenBalances[accountAddress as Hex][chainId] = {};\n }\n\n for (let i = 0; i < results.length; i++) {\n const { success, value } = results[i];\n const { accountAddress, tokenAddress } = accountTokenPairs[i];\n\n if (success) {\n ((state.tokenBalances[accountAddress] ??= {})[chainId] ??= {})[\n tokenAddress\n ] = toHex(value as BN);\n }\n }\n });\n }\n\n /**\n * Reset the controller state to the default state.\n */\n resetState() {\n this.update(() => {\n return getDefaultTokenBalancesState();\n });\n }\n\n /**\n * Returns the network client for a given chain id\n * @param chainId - The chain id to get the network client for.\n * @returns The network client for the given chain id.\n */\n #getNetworkClient(chainId: Hex) {\n const { networkConfigurationsByChainId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n\n const networkConfiguration = networkConfigurationsByChainId[chainId];\n if (!networkConfiguration) {\n throw new Error(\n `TokenBalancesController: No network configuration found for chainId ${chainId}`,\n );\n }\n\n const { networkClientId } =\n networkConfiguration.rpcEndpoints[\n networkConfiguration.defaultRpcEndpointIndex\n ];\n\n return this.messagingSystem.call(\n `NetworkController:getNetworkClientById`,\n networkClientId,\n );\n }\n}\n\nexport default TokenBalancesController;\n"]}
|
1
|
+
{"version":3,"file":"TokenBalancesController.mjs","sourceRoot":"","sources":["../src/TokenBalancesController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,QAAQ,EAAE,iCAAiC;AACpD,OAAO,EAAE,YAAY,EAAE,iCAAiC;AAWxD,OAAO,EAAE,oBAAoB,EAAE,KAAK,EAAE,mCAAmC;AACzE,OAAO,EAAE,QAAQ,EAAE,oCAAoC;AAOvD,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;;;AAY/E,OAAO,EAAE,mBAAmB,EAAE,wBAAoB;AAQlD,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,MAAM,cAAc,GAAG,yBAAyB,CAAC;AAEjD,MAAM,QAAQ,GAAG;IACf,aAAa,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;CACnD,CAAC;AAkEF;;;;GAIG;AACH,MAAM,UAAU,4BAA4B;IAC1C,OAAO;QACL,aAAa,EAAE,EAAE;KAClB,CAAC;AACJ,CAAC;AAOD;;;GAGG;AACH,MAAM,OAAO,uBAAwB,SAAQ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AGH,eAAe,uBAAuB,CAAC","sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport { Web3Provider } from '@ethersproject/providers';\nimport type {\n AccountsControllerAccountRemovedEvent,\n AccountsControllerGetSelectedAccountAction,\n AccountsControllerListAccountsAction,\n} from '@metamask/accounts-controller';\nimport type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { toChecksumHexAddress, toHex } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type {\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n NetworkControllerStateChangeEvent,\n NetworkState,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n PreferencesState,\n} from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\nimport type BN from 'bn.js';\nimport type { Patch } from 'immer';\nimport { isEqual } from 'lodash';\n\nimport type { MulticallResult } from './multicall';\nimport { multicallOrFallback } from './multicall';\nimport type { Token } from './TokenRatesController';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerState,\n TokensControllerStateChangeEvent,\n} from './TokensController';\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst controllerName = 'TokenBalancesController';\n\nconst metadata = {\n tokenBalances: { persist: true, anonymous: false },\n};\n\n/**\n * Token balances controller options\n * @property interval - Polling interval used to fetch new token balances.\n * @property messenger - A messenger.\n * @property state - Initial state for the controller.\n */\ntype TokenBalancesControllerOptions = {\n interval?: number;\n messenger: TokenBalancesControllerMessenger;\n state?: Partial<TokenBalancesControllerState>;\n};\n\n/**\n * A mapping from account address to chain id to token address to balance.\n */\ntype TokenBalances = Record<Hex, Record<Hex, Record<Hex, Hex>>>;\n\n/**\n * Token balances controller state\n * @property tokenBalances - A mapping from account address to chain id to token address to balance.\n */\nexport type TokenBalancesControllerState = {\n tokenBalances: TokenBalances;\n};\n\nexport type TokenBalancesControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenBalancesControllerState\n>;\n\nexport type TokenBalancesControllerActions =\n TokenBalancesControllerGetStateAction;\n\nexport type AllowedActions =\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetStateAction\n | TokensControllerGetStateAction\n | PreferencesControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction\n | AccountsControllerListAccountsAction;\n\nexport type TokenBalancesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n TokenBalancesControllerState\n >;\n\nexport type TokenBalancesControllerEvents =\n TokenBalancesControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | TokensControllerStateChangeEvent\n | PreferencesControllerStateChangeEvent\n | NetworkControllerStateChangeEvent\n | AccountsControllerAccountRemovedEvent;\n\nexport type TokenBalancesControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n TokenBalancesControllerActions | AllowedActions,\n TokenBalancesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Get the default TokenBalancesController state.\n *\n * @returns The default TokenBalancesController state.\n */\nexport function getDefaultTokenBalancesState(): TokenBalancesControllerState {\n return {\n tokenBalances: {},\n };\n}\n\n/** The input to start polling for the {@link TokenBalancesController} */\nexport type TokenBalancesPollingInput = {\n chainId: Hex;\n};\n\n/**\n * Controller that passively polls on a set interval token balances\n * for tokens stored in the TokensController\n */\nexport class TokenBalancesController extends StaticIntervalPollingController<TokenBalancesPollingInput>()<\n typeof controllerName,\n TokenBalancesControllerState,\n TokenBalancesControllerMessenger\n> {\n #queryMultipleAccounts: boolean;\n\n #allTokens: TokensControllerState['allTokens'];\n\n #allDetectedTokens: TokensControllerState['allDetectedTokens'];\n\n /**\n * Construct a Token Balances Controller.\n *\n * @param options - The controller options.\n * @param options.interval - Polling interval used to fetch new token balances.\n * @param options.state - Initial state to set on this controller.\n * @param options.messenger - The controller restricted messenger.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state = {},\n }: TokenBalancesControllerOptions) {\n super({\n name: controllerName,\n metadata,\n messenger,\n state: {\n ...getDefaultTokenBalancesState(),\n ...state,\n },\n });\n\n this.setIntervalLength(interval);\n\n // Set initial preference for querying multiple accounts, and subscribe to changes\n this.#queryMultipleAccounts = this.#calculateQueryMultipleAccounts(\n this.messagingSystem.call('PreferencesController:getState'),\n );\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n this.#onPreferencesStateChange.bind(this),\n );\n\n // Set initial tokens, and subscribe to changes\n ({\n allTokens: this.#allTokens,\n allDetectedTokens: this.#allDetectedTokens,\n } = this.messagingSystem.call('TokensController:getState'));\n\n this.messagingSystem.subscribe(\n 'TokensController:stateChange',\n this.#onTokensStateChange.bind(this),\n );\n\n // Subscribe to network state changes\n this.messagingSystem.subscribe(\n 'NetworkController:stateChange',\n this.#onNetworkStateChange.bind(this),\n );\n\n // subscribe to account removed event to cleanup stale balances\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountRemoved',\n (accountId: string) => this.#handleOnAccountRemoved(accountId),\n );\n }\n\n /**\n * Determines whether to query all accounts, or just the selected account.\n * @param preferences - The preferences state.\n * @param preferences.isMultiAccountBalancesEnabled - whether to query all accounts (mobile).\n * @param preferences.useMultiAccountBalanceChecker - whether to query all accounts (extension).\n * @returns true if all accounts should be queried.\n */\n #calculateQueryMultipleAccounts = ({\n isMultiAccountBalancesEnabled,\n useMultiAccountBalanceChecker,\n }: PreferencesState & { useMultiAccountBalanceChecker?: boolean }) => {\n return Boolean(\n // Note: These settings have different names on extension vs mobile\n isMultiAccountBalancesEnabled || useMultiAccountBalanceChecker,\n );\n };\n\n /**\n * Handles the event for preferences state changes.\n * @param preferences - The preferences state.\n */\n #onPreferencesStateChange = (preferences: PreferencesState) => {\n // Update the user preference for whether to query multiple accounts.\n const queryMultipleAccounts =\n this.#calculateQueryMultipleAccounts(preferences);\n\n // Refresh when flipped off -> on\n const refresh = queryMultipleAccounts && !this.#queryMultipleAccounts;\n this.#queryMultipleAccounts = queryMultipleAccounts;\n\n if (refresh) {\n this.updateBalances().catch(console.error);\n }\n };\n\n /**\n * Handles the event for tokens state changes.\n * @param state - The token state.\n * @param state.allTokens - The state for imported tokens across all chains.\n * @param state.allDetectedTokens - The state for detected tokens across all chains.\n */\n #onTokensStateChange = ({\n allTokens,\n allDetectedTokens,\n }: TokensControllerState) => {\n // Refresh token balances on chains whose tokens have changed.\n const chainIds = this.#getChainIds(allTokens, allDetectedTokens);\n const chainIdsToUpdate = chainIds.filter(\n (chainId) =>\n !isEqual(this.#allTokens[chainId], allTokens[chainId]) ||\n !isEqual(this.#allDetectedTokens[chainId], allDetectedTokens[chainId]),\n );\n\n this.#allTokens = allTokens;\n this.#allDetectedTokens = allDetectedTokens;\n this.#handleTokensControllerStateChange({\n chainIds: chainIdsToUpdate,\n }).catch(console.error);\n };\n\n /**\n * Handles the event for network state changes.\n * @param _ - The network state.\n * @param patches - An array of patch operations performed on the network state.\n */\n #onNetworkStateChange(_: NetworkState, patches: Patch[]) {\n // Remove state for deleted networks\n for (const patch of patches) {\n if (\n patch.op === 'remove' &&\n patch.path[0] === 'networkConfigurationsByChainId'\n ) {\n const removedChainId = patch.path[1] as Hex;\n\n this.update((state) => {\n for (const accountAddress of Object.keys(state.tokenBalances)) {\n delete state.tokenBalances[accountAddress as Hex][removedChainId];\n }\n });\n }\n }\n }\n\n /**\n * Handles changes when an account has been removed.\n *\n * @param accountId - The account id being removed.\n */\n #handleOnAccountRemoved(accountId: string) {\n const accounts = this.messagingSystem.call(\n 'AccountsController:listAccounts',\n );\n const accountAddress = accounts.find(\n (account) => account.id === accountId,\n )?.address;\n if (!accountAddress) {\n return;\n }\n\n this.update((state) => {\n delete state.tokenBalances[accountAddress as `0x${string}`];\n });\n }\n\n /**\n * Returns an array of chain ids that have tokens.\n * @param allTokens - The state for imported tokens across all chains.\n * @param allDetectedTokens - The state for detected tokens across all chains.\n * @returns An array of chain ids that have tokens.\n */\n #getChainIds = (\n allTokens: TokensControllerState['allTokens'],\n allDetectedTokens: TokensControllerState['allDetectedTokens'],\n ) =>\n [\n ...new Set([\n ...Object.keys(allTokens),\n ...Object.keys(allDetectedTokens),\n ]),\n ] as Hex[];\n\n /**\n * Polls for erc20 token balances.\n * @param input - The input for the poll.\n * @param input.chainId - The chain id to poll token balances on.\n */\n async _executePoll({ chainId }: TokenBalancesPollingInput) {\n await this.updateBalancesByChainId({ chainId });\n }\n\n /**\n * Updates the token balances for the given chain ids.\n * @param input - The input for the update.\n * @param input.chainIds - The chain ids to update token balances for.\n * Or omitted to update all chains that contain tokens.\n */\n async updateBalances({ chainIds }: { chainIds?: Hex[] } = {}) {\n chainIds ??= this.#getChainIds(this.#allTokens, this.#allDetectedTokens);\n\n await Promise.allSettled(\n chainIds.map((chainId) => this.updateBalancesByChainId({ chainId })),\n );\n }\n\n async #handleTokensControllerStateChange({\n chainIds,\n }: { chainIds?: Hex[] } = {}) {\n const currentTokenBalancesState = this.messagingSystem.call(\n 'TokenBalancesController:getState',\n );\n const currentTokenBalances = currentTokenBalancesState.tokenBalances;\n const currentAllTokens = this.#allTokens;\n const chainIdsSet = new Set(chainIds);\n\n // first we check if the state change was due to a token being removed\n for (const currentAccount of Object.keys(currentTokenBalances)) {\n const allChains = currentTokenBalances[currentAccount as `0x${string}`];\n for (const currentChain of Object.keys(allChains)) {\n if (chainIds?.length && !chainIdsSet.has(currentChain as Hex)) {\n continue;\n }\n const tokensObject = allChains[currentChain as Hex];\n const allCurrentTokens = Object.keys(tokensObject);\n const existingTokensInState =\n currentAllTokens[currentChain as Hex]?.[\n currentAccount as `0x${string}`\n ] || [];\n const existingSet = new Set(\n existingTokensInState.map((elm) => elm.address),\n );\n\n for (const singleToken of allCurrentTokens) {\n if (!existingSet.has(singleToken)) {\n this.update((state) => {\n delete state.tokenBalances[currentAccount as Hex][\n currentChain as Hex\n ][singleToken as `0x${string}`];\n });\n }\n }\n }\n }\n\n // then we check if the state change was due to a token being added\n let shouldUpdate = false;\n for (const currentChain of Object.keys(currentAllTokens)) {\n if (chainIds?.length && !chainIdsSet.has(currentChain as Hex)) {\n continue;\n }\n const accountsPerChain = currentAllTokens[currentChain as Hex];\n\n for (const currentAccount of Object.keys(accountsPerChain)) {\n const tokensList = accountsPerChain[currentAccount as `0x${string}`];\n const tokenBalancesObject =\n currentTokenBalances[currentAccount as `0x${string}`]?.[\n currentChain as Hex\n ] || {};\n for (const singleToken of tokensList) {\n if (!tokenBalancesObject?.[singleToken.address as `0x${string}`]) {\n shouldUpdate = true;\n break;\n }\n }\n }\n }\n if (shouldUpdate) {\n await this.updateBalances({ chainIds }).catch(console.error);\n }\n }\n\n /**\n * Updates token balances for the given chain id.\n * @param input - The input for the update.\n * @param input.chainId - The chain id to update token balances on.\n */\n async updateBalancesByChainId({ chainId }: { chainId: Hex }) {\n const { address: selectedAccountAddress } = this.messagingSystem.call(\n 'AccountsController:getSelectedAccount',\n );\n\n const isSelectedAccount = (accountAddress: string) =>\n toChecksumHexAddress(accountAddress) ===\n toChecksumHexAddress(selectedAccountAddress);\n\n const accountTokenPairs: { accountAddress: Hex; tokenAddress: Hex }[] = [];\n\n const addTokens = ([accountAddress, tokens]: [string, Token[]]) =>\n this.#queryMultipleAccounts || isSelectedAccount(accountAddress)\n ? tokens.forEach((t) =>\n accountTokenPairs.push({\n accountAddress: accountAddress as Hex,\n tokenAddress: t.address as Hex,\n }),\n )\n : undefined;\n\n // Balances will be updated for both imported and detected tokens\n Object.entries(this.#allTokens[chainId] ?? {}).forEach(addTokens);\n Object.entries(this.#allDetectedTokens[chainId] ?? {}).forEach(addTokens);\n\n let results: MulticallResult[] = [];\n\n const currentTokenBalances = this.messagingSystem.call(\n 'TokenBalancesController:getState',\n );\n\n if (accountTokenPairs.length > 0) {\n const provider = new Web3Provider(\n this.#getNetworkClient(chainId).provider,\n );\n\n const calls = accountTokenPairs.map(\n ({ accountAddress, tokenAddress }) => ({\n contract: new Contract(tokenAddress, abiERC20, provider),\n functionSignature: 'balanceOf(address)',\n arguments: [accountAddress],\n }),\n );\n\n results = await multicallOrFallback(calls, chainId, provider);\n }\n\n const updatedResults: (MulticallResult & {\n isTokenBalanceValueChanged?: boolean;\n })[] = results.map((res, i) => {\n const { value } = res;\n const { accountAddress, tokenAddress } = accountTokenPairs[i];\n const currentTokenBalanceValueForAccount =\n currentTokenBalances.tokenBalances?.[accountAddress]?.[chainId]?.[\n tokenAddress\n ];\n const isTokenBalanceValueChanged =\n currentTokenBalanceValueForAccount !== toHex(value as BN);\n return {\n ...res,\n isTokenBalanceValueChanged,\n };\n });\n\n // if all values of isTokenBalanceValueChanged are false, return\n if (updatedResults.every((result) => !result.isTokenBalanceValueChanged)) {\n return;\n }\n\n this.update((state) => {\n for (let i = 0; i < updatedResults.length; i++) {\n const { success, value, isTokenBalanceValueChanged } =\n updatedResults[i];\n const { accountAddress, tokenAddress } = accountTokenPairs[i];\n if (success && isTokenBalanceValueChanged) {\n ((state.tokenBalances[accountAddress] ??= {})[chainId] ??= {})[\n tokenAddress\n ] = toHex(value as BN);\n }\n }\n });\n }\n\n /**\n * Reset the controller state to the default state.\n */\n resetState() {\n this.update(() => {\n return getDefaultTokenBalancesState();\n });\n }\n\n /**\n * Returns the network client for a given chain id\n * @param chainId - The chain id to get the network client for.\n * @returns The network client for the given chain id.\n */\n #getNetworkClient(chainId: Hex) {\n const { networkConfigurationsByChainId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n\n const networkConfiguration = networkConfigurationsByChainId[chainId];\n if (!networkConfiguration) {\n throw new Error(\n `TokenBalancesController: No network configuration found for chainId ${chainId}`,\n );\n }\n\n const { networkClientId } =\n networkConfiguration.rpcEndpoints[\n networkConfiguration.defaultRpcEndpointIndex\n ];\n\n return this.messagingSystem.call(\n `NetworkController:getNetworkClientById`,\n networkClientId,\n );\n }\n}\n\nexport default TokenBalancesController;\n"]}
|