forked from MetaMask/core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAccountTrackerController.ts
More file actions
349 lines (315 loc) · 11.1 KB
/
AccountTrackerController.ts
File metadata and controls
349 lines (315 loc) · 11.1 KB
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
import type { BaseConfig, BaseState } from '@metamask/base-controller';
import { query, safelyExecuteWithTimeout } from '@metamask/controller-utils';
import EthQuery from '@metamask/eth-query';
import type { Provider } from '@metamask/eth-query';
import type {
NetworkClientId,
NetworkController,
} from '@metamask/network-controller';
import { StaticIntervalPollingControllerV1 } from '@metamask/polling-controller';
import type { PreferencesState } from '@metamask/preferences-controller';
import type { Hex } from '@metamask/utils';
import { assert } from '@metamask/utils';
import { Mutex } from 'async-mutex';
import { cloneDeep } from 'lodash';
/**
* @type AccountInformation
*
* Account information object
* @property balance - Hex string of an account balancec in wei
*/
// This interface was created before this ESLint rule was added.
// Convert to a `type` in a future major version.
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
export interface AccountInformation {
balance: string;
}
/**
* @type AccountTrackerConfig
*
* Account tracker controller configuration
* @property provider - Provider used to create a new underlying EthQuery instance
*/
// This interface was created before this ESLint rule was added.
// Remove in a future major version.
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
export interface AccountTrackerConfig extends BaseConfig {
interval: number;
provider?: Provider;
}
/**
* @type AccountTrackerState
*
* Account tracker controller state
* @property accounts - Map of addresses to account information
*/
// This interface was created before this ESLint rule was added.
// Remove in a future major version.
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
export interface AccountTrackerState extends BaseState {
accounts: { [address: string]: AccountInformation };
accountsByChainId: Record<string, { [address: string]: AccountInformation }>;
}
/**
* Controller that tracks the network balances for all user accounts.
*/
export class AccountTrackerController extends StaticIntervalPollingControllerV1<
AccountTrackerConfig,
AccountTrackerState
> {
private _provider?: Provider;
private readonly refreshMutex = new Mutex();
private handle?: ReturnType<typeof setTimeout>;
private syncAccounts(newChainId: string) {
const accounts = { ...this.state.accounts };
const accountsByChainId = cloneDeep(this.state.accountsByChainId);
const existing = Object.keys(accounts);
if (!accountsByChainId[newChainId]) {
accountsByChainId[newChainId] = {};
existing.forEach((address) => {
accountsByChainId[newChainId][address] = { balance: '0x0' };
});
}
const addresses = Object.keys(this.getIdentities());
const newAddresses = addresses.filter(
(address) => !existing.includes(address),
);
const oldAddresses = existing.filter(
(address) => !addresses.includes(address),
);
newAddresses.forEach((address) => {
accounts[address] = { balance: '0x0' };
});
Object.keys(accountsByChainId).forEach((chainId) => {
newAddresses.forEach((address) => {
accountsByChainId[chainId][address] = {
balance: '0x0',
};
});
});
oldAddresses.forEach((address) => {
delete accounts[address];
});
Object.keys(accountsByChainId).forEach((chainId) => {
oldAddresses.forEach((address) => {
delete accountsByChainId[chainId][address];
});
});
this.update({ accounts, accountsByChainId });
}
/**
* Name of this controller used during composition
*/
override name = 'AccountTrackerController' as const;
private readonly getIdentities: () => PreferencesState['identities'];
private readonly getSelectedAddress: () => PreferencesState['selectedAddress'];
private readonly getMultiAccountBalancesEnabled: () => PreferencesState['isMultiAccountBalancesEnabled'];
private readonly getCurrentChainId: () => Hex;
private readonly getNetworkClientById: NetworkController['getNetworkClientById'];
/**
* Creates an AccountTracker instance.
*
* @param options - The controller options.
* @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
* @param options.getIdentities - Gets the identities from the Preferences store.
* @param options.getSelectedAddress - Gets the selected address from the Preferences store.
* @param options.getMultiAccountBalancesEnabled - Gets the multi account balances enabled flag from the Preferences store.
* @param options.getCurrentChainId - Gets the chain ID for the current network from the Network store.
* @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.
* @param config - Initial options used to configure this controller.
* @param state - Initial state to set on this controller.
*/
constructor(
{
onPreferencesStateChange,
getIdentities,
getSelectedAddress,
getMultiAccountBalancesEnabled,
getCurrentChainId,
getNetworkClientById,
}: {
onPreferencesStateChange: (
listener: (preferencesState: PreferencesState) => void,
) => void;
getIdentities: () => PreferencesState['identities'];
getSelectedAddress: () => PreferencesState['selectedAddress'];
getMultiAccountBalancesEnabled: () => PreferencesState['isMultiAccountBalancesEnabled'];
getCurrentChainId: () => Hex;
getNetworkClientById: NetworkController['getNetworkClientById'];
},
config?: Partial<AccountTrackerConfig>,
state?: Partial<AccountTrackerState>,
) {
super(config, state);
this.defaultConfig = {
interval: 10000,
};
this.defaultState = {
accounts: {},
accountsByChainId: {
[getCurrentChainId()]: {},
},
};
this.initialize();
this.setIntervalLength(this.config.interval);
this.getIdentities = getIdentities;
this.getSelectedAddress = getSelectedAddress;
this.getMultiAccountBalancesEnabled = getMultiAccountBalancesEnabled;
this.getCurrentChainId = getCurrentChainId;
this.getNetworkClientById = getNetworkClientById;
onPreferencesStateChange(() => {
this.refresh();
});
this.poll();
}
/**
* Sets a new provider.
*
* TODO: Replace this wth a method.
*
* @param provider - Provider used to create a new underlying EthQuery instance.
*/
set provider(provider: Provider) {
this._provider = provider;
}
get provider() {
throw new Error('Property only used for setting');
}
/**
* Resolves a networkClientId to a network client config
* or globally selected network config if not provided
*
* @param networkClientId - Optional networkClientId to fetch a network client with
* @returns network client config
*/
#getCorrectNetworkClient(networkClientId?: NetworkClientId): {
chainId: string;
ethQuery?: EthQuery;
} {
if (networkClientId) {
const networkClient = this.getNetworkClientById(networkClientId);
return {
chainId: networkClient.configuration.chainId,
ethQuery: new EthQuery(networkClient.provider),
};
}
return {
chainId: this.getCurrentChainId(),
ethQuery: this._provider ? new EthQuery(this._provider) : undefined,
};
}
/**
* Starts a new polling interval.
*
* @param interval - Polling interval trigger a 'refresh'.
*/
async poll(interval?: number): Promise<void> {
interval && this.configure({ interval }, false, false);
this.handle && clearTimeout(this.handle);
await this.refresh();
this.handle = setTimeout(() => {
this.poll(this.config.interval);
}, this.config.interval);
}
/**
* Refreshes the balances of the accounts using the networkClientId
*
* @param networkClientId - The network client ID used to get balances.
*/
async _executePoll(networkClientId: string): Promise<void> {
this.refresh(networkClientId);
}
/**
* Refreshes the balances of the accounts depending on the multi-account setting.
* If multi-account is disabled, only updates the selected account balance.
* If multi-account is enabled, updates balances for all accounts.
*
* @param networkClientId - Optional networkClientId to fetch a network client with
*/
refresh = async (networkClientId?: NetworkClientId) => {
const releaseLock = await this.refreshMutex.acquire();
try {
const { chainId, ethQuery } =
this.#getCorrectNetworkClient(networkClientId);
this.syncAccounts(chainId);
const { accounts, accountsByChainId } = this.state;
const isMultiAccountBalancesEnabled =
this.getMultiAccountBalancesEnabled();
const accountsToUpdate = isMultiAccountBalancesEnabled
? Object.keys(accounts)
: [this.getSelectedAddress()];
const accountsForChain = { ...accountsByChainId[chainId] };
for (const address of accountsToUpdate) {
const balance = await this.getBalanceFromChain(address, ethQuery);
if (balance) {
accountsForChain[address] = {
balance,
};
}
}
this.update({
...(chainId === this.getCurrentChainId() && {
accounts: accountsForChain,
}),
accountsByChainId: {
...this.state.accountsByChainId,
[chainId]: accountsForChain,
},
});
} finally {
releaseLock();
}
};
/**
* Fetches the balance of a given address from the blockchain.
*
* @param address - The account address to fetch the balance for.
* @param ethQuery - The EthQuery instance to query getBalnce with.
* @returns A promise that resolves to the balance in a hex string format.
*/
private async getBalanceFromChain(
address: string,
ethQuery?: EthQuery,
): Promise<string | undefined> {
return await safelyExecuteWithTimeout(async () => {
assert(ethQuery, 'Provider not set.');
return await query(ethQuery, 'getBalance', [address]);
});
}
/**
* Sync accounts balances with some additional addresses.
*
* @param addresses - the additional addresses, may be hardware wallet addresses.
* @param networkClientId - Optional networkClientId to fetch a network client with.
* @returns accounts - addresses with synced balance
*/
async syncBalanceWithAddresses(
addresses: string[],
networkClientId?: NetworkClientId,
): Promise<Record<string, { balance: string }>> {
const { ethQuery } = this.#getCorrectNetworkClient(networkClientId);
return await Promise.all(
addresses.map((address): Promise<[string, string] | undefined> => {
return safelyExecuteWithTimeout(async () => {
assert(ethQuery, 'Provider not set.');
const balance = await query(ethQuery, 'getBalance', [address]);
return [address, balance];
});
}),
).then((value) => {
return value.reduce((obj, item) => {
if (!item) {
return obj;
}
const [address, balance] = item;
return {
...obj,
[address]: {
balance,
},
};
}, {});
});
}
}
export default AccountTrackerController;