-
-
Notifications
You must be signed in to change notification settings - Fork 213
/
Copy pathTokenBalancesController.ts
418 lines (362 loc) · 13.1 KB
/
TokenBalancesController.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
import { Contract } from '@ethersproject/contracts';
import { Web3Provider } from '@ethersproject/providers';
import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';
import type {
RestrictedMessenger,
ControllerGetStateAction,
ControllerStateChangeEvent,
} from '@metamask/base-controller';
import { toChecksumHexAddress, toHex } from '@metamask/controller-utils';
import { abiERC20 } from '@metamask/metamask-eth-abis';
import type {
NetworkControllerGetNetworkClientByIdAction,
NetworkControllerGetStateAction,
NetworkControllerStateChangeEvent,
NetworkState,
} from '@metamask/network-controller';
import { StaticIntervalPollingController } from '@metamask/polling-controller';
import type {
PreferencesControllerGetStateAction,
PreferencesControllerStateChangeEvent,
PreferencesState,
} from '@metamask/preferences-controller';
import type { Hex } from '@metamask/utils';
import type BN from 'bn.js';
import type { Patch } from 'immer';
import { isEqual } from 'lodash';
import type { MulticallResult } from './multicall';
import { multicallOrFallback } from './multicall';
import type { Token } from './TokenRatesController';
import type {
TokensControllerGetStateAction,
TokensControllerState,
TokensControllerStateChangeEvent,
} from './TokensController';
const DEFAULT_INTERVAL = 180000;
const controllerName = 'TokenBalancesController';
const metadata = {
tokenBalances: { persist: true, anonymous: false },
};
/**
* Token balances controller options
* @property interval - Polling interval used to fetch new token balances.
* @property messenger - A messenger.
* @property state - Initial state for the controller.
*/
type TokenBalancesControllerOptions = {
interval?: number;
messenger: TokenBalancesControllerMessenger;
state?: Partial<TokenBalancesControllerState>;
};
/**
* A mapping from account address to chain id to token address to balance.
*/
type TokenBalances = Record<Hex, Record<Hex, Record<Hex, Hex>>>;
/**
* Token balances controller state
* @property tokenBalances - A mapping from account address to chain id to token address to balance.
*/
export type TokenBalancesControllerState = {
tokenBalances: TokenBalances;
};
export type TokenBalancesControllerGetStateAction = ControllerGetStateAction<
typeof controllerName,
TokenBalancesControllerState
>;
export type TokenBalancesControllerActions =
TokenBalancesControllerGetStateAction;
export type AllowedActions =
| NetworkControllerGetNetworkClientByIdAction
| NetworkControllerGetStateAction
| TokensControllerGetStateAction
| PreferencesControllerGetStateAction
| AccountsControllerGetSelectedAccountAction;
export type TokenBalancesControllerStateChangeEvent =
ControllerStateChangeEvent<
typeof controllerName,
TokenBalancesControllerState
>;
export type TokenBalancesControllerEvents =
TokenBalancesControllerStateChangeEvent;
export type AllowedEvents =
| TokensControllerStateChangeEvent
| PreferencesControllerStateChangeEvent
| NetworkControllerStateChangeEvent;
export type TokenBalancesControllerMessenger = RestrictedMessenger<
typeof controllerName,
TokenBalancesControllerActions | AllowedActions,
TokenBalancesControllerEvents | AllowedEvents,
AllowedActions['type'],
AllowedEvents['type']
>;
/**
* Get the default TokenBalancesController state.
*
* @returns The default TokenBalancesController state.
*/
export function getDefaultTokenBalancesState(): TokenBalancesControllerState {
return {
tokenBalances: {},
};
}
/** The input to start polling for the {@link TokenBalancesController} */
export type TokenBalancesPollingInput = {
chainId: Hex;
};
/**
* Controller that passively polls on a set interval token balances
* for tokens stored in the TokensController
*/
export class TokenBalancesController extends StaticIntervalPollingController<TokenBalancesPollingInput>()<
typeof controllerName,
TokenBalancesControllerState,
TokenBalancesControllerMessenger
> {
#queryMultipleAccounts: boolean;
#allTokens: TokensControllerState['allTokens'];
#allDetectedTokens: TokensControllerState['allDetectedTokens'];
/**
* Construct a Token Balances Controller.
*
* @param options - The controller options.
* @param options.interval - Polling interval used to fetch new token balances.
* @param options.state - Initial state to set on this controller.
* @param options.messenger - The controller restricted messenger.
*/
constructor({
interval = DEFAULT_INTERVAL,
messenger,
state = {},
}: TokenBalancesControllerOptions) {
super({
name: controllerName,
metadata,
messenger,
state: {
...getDefaultTokenBalancesState(),
...state,
},
});
this.setIntervalLength(interval);
// Set initial preference for querying multiple accounts, and subscribe to changes
this.#queryMultipleAccounts = this.#calculateQueryMultipleAccounts(
this.messagingSystem.call('PreferencesController:getState'),
);
this.messagingSystem.subscribe(
'PreferencesController:stateChange',
this.#onPreferencesStateChange.bind(this),
);
// Set initial tokens, and subscribe to changes
({
allTokens: this.#allTokens,
allDetectedTokens: this.#allDetectedTokens,
} = this.messagingSystem.call('TokensController:getState'));
this.messagingSystem.subscribe(
'TokensController:stateChange',
this.#onTokensStateChange.bind(this),
);
// Subscribe to network state changes
this.messagingSystem.subscribe(
'NetworkController:stateChange',
this.#onNetworkStateChange.bind(this),
);
}
/**
* Determines whether to query all accounts, or just the selected account.
* @param preferences - The preferences state.
* @param preferences.isMultiAccountBalancesEnabled - whether to query all accounts (mobile).
* @param preferences.useMultiAccountBalanceChecker - whether to query all accounts (extension).
* @returns true if all accounts should be queried.
*/
#calculateQueryMultipleAccounts = ({
isMultiAccountBalancesEnabled,
useMultiAccountBalanceChecker,
}: PreferencesState & { useMultiAccountBalanceChecker?: boolean }) => {
return Boolean(
// Note: These settings have different names on extension vs mobile
isMultiAccountBalancesEnabled || useMultiAccountBalanceChecker,
);
};
/**
* Handles the event for preferences state changes.
* @param preferences - The preferences state.
*/
#onPreferencesStateChange = (preferences: PreferencesState) => {
// Update the user preference for whether to query multiple accounts.
const queryMultipleAccounts =
this.#calculateQueryMultipleAccounts(preferences);
// Refresh when flipped off -> on
const refresh = queryMultipleAccounts && !this.#queryMultipleAccounts;
this.#queryMultipleAccounts = queryMultipleAccounts;
if (refresh) {
this.updateBalances().catch(console.error);
}
};
/**
* Handles the event for tokens state changes.
* @param state - The token state.
* @param state.allTokens - The state for imported tokens across all chains.
* @param state.allDetectedTokens - The state for detected tokens across all chains.
*/
#onTokensStateChange = ({
allTokens,
allDetectedTokens,
}: TokensControllerState) => {
// Refresh token balances on chains whose tokens have changed.
const chainIds = this.#getChainIds(allTokens, allDetectedTokens);
const chainIdsToUpdate = chainIds.filter(
(chainId) =>
!isEqual(this.#allTokens[chainId], allTokens[chainId]) ||
!isEqual(this.#allDetectedTokens[chainId], allDetectedTokens[chainId]),
);
this.#allTokens = allTokens;
this.#allDetectedTokens = allDetectedTokens;
this.updateBalances({ chainIds: chainIdsToUpdate }).catch(console.error);
};
/**
* Handles the event for network state changes.
* @param _ - The network state.
* @param patches - An array of patch operations performed on the network state.
*/
#onNetworkStateChange(_: NetworkState, patches: Patch[]) {
// Remove state for deleted networks
for (const patch of patches) {
if (
patch.op === 'remove' &&
patch.path[0] === 'networkConfigurationsByChainId'
) {
const removedChainId = patch.path[1] as Hex;
this.update((state) => {
for (const accountAddress of Object.keys(state.tokenBalances)) {
delete state.tokenBalances[accountAddress as Hex][removedChainId];
}
});
}
}
}
/**
* Returns an array of chain ids that have tokens.
* @param allTokens - The state for imported tokens across all chains.
* @param allDetectedTokens - The state for detected tokens across all chains.
* @returns An array of chain ids that have tokens.
*/
#getChainIds = (
allTokens: TokensControllerState['allTokens'],
allDetectedTokens: TokensControllerState['allDetectedTokens'],
) =>
[
...new Set([
...Object.keys(allTokens),
...Object.keys(allDetectedTokens),
]),
] as Hex[];
/**
* Polls for erc20 token balances.
* @param input - The input for the poll.
* @param input.chainId - The chain id to poll token balances on.
*/
async _executePoll({ chainId }: TokenBalancesPollingInput) {
await this.updateBalancesByChainId({ chainId });
}
/**
* Updates the token balances for the given chain ids.
* @param input - The input for the update.
* @param input.chainIds - The chain ids to update token balances for.
* Or omitted to update all chains that contain tokens.
*/
async updateBalances({ chainIds }: { chainIds?: Hex[] } = {}) {
chainIds ??= this.#getChainIds(this.#allTokens, this.#allDetectedTokens);
await Promise.allSettled(
chainIds.map((chainId) => this.updateBalancesByChainId({ chainId })),
);
}
/**
* Updates token balances for the given chain id.
* @param input - The input for the update.
* @param input.chainId - The chain id to update token balances on.
*/
async updateBalancesByChainId({ chainId }: { chainId: Hex }) {
const { address: selectedAccountAddress } = this.messagingSystem.call(
'AccountsController:getSelectedAccount',
);
const isSelectedAccount = (accountAddress: string) =>
toChecksumHexAddress(accountAddress) ===
toChecksumHexAddress(selectedAccountAddress);
const accountTokenPairs: { accountAddress: Hex; tokenAddress: Hex }[] = [];
const addTokens = ([accountAddress, tokens]: [string, Token[]]) =>
this.#queryMultipleAccounts || isSelectedAccount(accountAddress)
? tokens.forEach((t) =>
accountTokenPairs.push({
accountAddress: accountAddress as Hex,
tokenAddress: t.address as Hex,
}),
)
: undefined;
// Balances will be updated for both imported and detected tokens
Object.entries(this.#allTokens[chainId] ?? {}).forEach(addTokens);
Object.entries(this.#allDetectedTokens[chainId] ?? {}).forEach(addTokens);
let results: MulticallResult[] = [];
if (accountTokenPairs.length > 0) {
const provider = new Web3Provider(
this.#getNetworkClient(chainId).provider,
);
const calls = accountTokenPairs.map(
({ accountAddress, tokenAddress }) => ({
contract: new Contract(tokenAddress, abiERC20, provider),
functionSignature: 'balanceOf(address)',
arguments: [accountAddress],
}),
);
results = await multicallOrFallback(calls, chainId, provider);
}
this.update((state) => {
// Reset so that when accounts or tokens are removed,
// their balances are removed rather than left stale.
for (const accountAddress of Object.keys(state.tokenBalances)) {
state.tokenBalances[accountAddress as Hex][chainId] = {};
}
for (let i = 0; i < results.length; i++) {
const { success, value } = results[i];
const { accountAddress, tokenAddress } = accountTokenPairs[i];
if (success) {
((state.tokenBalances[accountAddress] ??= {})[chainId] ??= {})[
tokenAddress
] = toHex(value as BN);
}
}
});
}
/**
* Reset the controller state to the default state.
*/
resetState() {
this.update(() => {
return getDefaultTokenBalancesState();
});
}
/**
* Returns the network client for a given chain id
* @param chainId - The chain id to get the network client for.
* @returns The network client for the given chain id.
*/
#getNetworkClient(chainId: Hex) {
const { networkConfigurationsByChainId } = this.messagingSystem.call(
'NetworkController:getState',
);
const networkConfiguration = networkConfigurationsByChainId[chainId];
if (!networkConfiguration) {
throw new Error(
`TokenBalancesController: No network configuration found for chainId ${chainId}`,
);
}
const { networkClientId } =
networkConfiguration.rpcEndpoints[
networkConfiguration.defaultRpcEndpointIndex
];
return this.messagingSystem.call(
`NetworkController:getNetworkClientById`,
networkClientId,
);
}
}
export default TokenBalancesController;