forked from MetaMask/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTokenDetectionController.ts
307 lines (276 loc) · 9.38 KB
/
TokenDetectionController.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
import {
BaseController,
BaseConfig,
BaseState,
} from '@metamask/base-controller';
import type { NetworkState } from '@metamask/network-controller';
import type { PreferencesState } from '@metamask/preferences-controller';
import {
safelyExecute,
toChecksumHexAddress,
} from '@metamask/controller-utils';
import { isTokenDetectionSupportedForNetwork } from './assetsUtil';
import type { TokensController, TokensState } from './TokensController';
import type { AssetsContractController } from './AssetsContractController';
import { Token } from './TokenRatesController';
import { TokenListState } from './TokenListController';
const DEFAULT_INTERVAL = 180000;
/**
* @type TokenDetectionConfig
*
* TokenDetection configuration
* @property interval - Polling interval used to fetch new token rates
* @property selectedAddress - Vault selected address
* @property chainId - The chain ID of the current network
* @property isDetectionEnabledFromPreferences - Boolean to track if detection is enabled from PreferencesController
* @property isDetectionEnabledForNetwork - Boolean to track if detected is enabled for current network
*/
export interface TokenDetectionConfig extends BaseConfig {
interval: number;
selectedAddress: string;
chainId: string;
isDetectionEnabledFromPreferences: boolean;
isDetectionEnabledForNetwork: boolean;
}
/**
* Controller that passively polls on a set interval for Tokens auto detection
*/
export class TokenDetectionController extends BaseController<
TokenDetectionConfig,
BaseState
> {
private intervalId?: ReturnType<typeof setTimeout>;
/**
* Name of this controller used during composition
*/
override name = 'TokenDetectionController';
private getBalancesInSingleCall: AssetsContractController['getBalancesInSingleCall'];
private addDetectedTokens: TokensController['addDetectedTokens'];
private getTokensState: () => TokensState;
private getTokenListState: () => TokenListState;
/**
* Creates a TokenDetectionController instance.
*
* @param options - The controller options.
* @param options.onPreferencesStateChange - Allows subscribing to preferences controller state changes.
* @param options.onNetworkStateChange - Allows subscribing to network controller state changes.
* @param options.onTokenListStateChange - Allows subscribing to token list controller state changes.
* @param options.getBalancesInSingleCall - Gets the balances of a list of tokens for the given address.
* @param options.addDetectedTokens - Add a list of detected tokens.
* @param options.getTokenListState - Gets the current state of the TokenList controller.
* @param options.getTokensState - Gets the current state of the Tokens controller.
* @param options.getNetworkState - Gets the state of the network controller.
* @param options.getPreferencesState - Gets the state of the preferences controller.
* @param config - Initial options used to configure this controller.
* @param state - Initial state to set on this controller.
*/
constructor(
{
onPreferencesStateChange,
onNetworkStateChange,
onTokenListStateChange,
getBalancesInSingleCall,
addDetectedTokens,
getTokenListState,
getTokensState,
getNetworkState,
getPreferencesState,
}: {
onPreferencesStateChange: (
listener: (preferencesState: PreferencesState) => void,
) => void;
onNetworkStateChange: (
listener: (networkState: NetworkState) => void,
) => void;
onTokenListStateChange: (
listener: (tokenListState: TokenListState) => void,
) => void;
getBalancesInSingleCall: AssetsContractController['getBalancesInSingleCall'];
addDetectedTokens: TokensController['addDetectedTokens'];
getTokenListState: () => TokenListState;
getTokensState: () => TokensState;
getNetworkState: () => NetworkState;
getPreferencesState: () => PreferencesState;
},
config?: Partial<TokenDetectionConfig>,
state?: Partial<BaseState>,
) {
const {
providerConfig: { chainId: defaultChainId },
} = getNetworkState();
const { useTokenDetection: defaultUseTokenDetection } =
getPreferencesState();
super(config, state);
this.defaultConfig = {
interval: DEFAULT_INTERVAL,
selectedAddress: '',
disabled: true,
chainId: defaultChainId,
isDetectionEnabledFromPreferences: defaultUseTokenDetection,
isDetectionEnabledForNetwork:
isTokenDetectionSupportedForNetwork(defaultChainId),
...config,
};
this.initialize();
this.getTokensState = getTokensState;
this.getTokenListState = getTokenListState;
this.addDetectedTokens = addDetectedTokens;
this.getBalancesInSingleCall = getBalancesInSingleCall;
onTokenListStateChange(({ tokenList }) => {
const hasTokens = Object.keys(tokenList).length;
if (hasTokens) {
this.detectTokens();
}
});
onPreferencesStateChange(({ selectedAddress, useTokenDetection }) => {
const {
selectedAddress: currentSelectedAddress,
isDetectionEnabledFromPreferences,
} = this.config;
const isSelectedAddressChanged =
selectedAddress !== currentSelectedAddress;
const isDetectionChangedFromPreferences =
isDetectionEnabledFromPreferences !== useTokenDetection;
this.configure({
isDetectionEnabledFromPreferences: useTokenDetection,
selectedAddress,
});
if (
useTokenDetection &&
(isSelectedAddressChanged || isDetectionChangedFromPreferences)
) {
this.detectTokens();
}
});
onNetworkStateChange(({ providerConfig: { chainId } }) => {
const { chainId: currentChainId } = this.config;
const isDetectionEnabledForNetwork =
isTokenDetectionSupportedForNetwork(chainId);
const isChainIdChanged = currentChainId !== chainId;
this.configure({
chainId,
isDetectionEnabledForNetwork,
});
if (isDetectionEnabledForNetwork && isChainIdChanged) {
this.detectTokens();
}
});
}
/**
* Start polling for detected tokens.
*/
async start() {
this.configure({ disabled: false });
await this.startPolling();
}
/**
* Stop polling for detected tokens.
*/
stop() {
this.configure({ disabled: true });
this.stopPolling();
}
private stopPolling() {
if (this.intervalId) {
clearInterval(this.intervalId);
}
}
/**
* Starts a new polling interval.
*
* @param interval - An interval on which to poll.
*/
private async startPolling(interval?: number): Promise<void> {
interval && this.configure({ interval }, false, false);
this.stopPolling();
await this.detectTokens();
this.intervalId = setInterval(async () => {
await this.detectTokens();
}, this.config.interval);
}
/**
* Triggers asset ERC20 token auto detection for each contract address in contract metadata on mainnet.
*/
async detectTokens() {
const {
disabled,
isDetectionEnabledForNetwork,
isDetectionEnabledFromPreferences,
} = this.config;
if (
disabled ||
!isDetectionEnabledForNetwork ||
!isDetectionEnabledFromPreferences
) {
return;
}
const { tokens } = this.getTokensState();
const { selectedAddress, chainId } = this.config;
const tokensAddresses = tokens.map(
/* istanbul ignore next*/ (token) => token.address.toLowerCase(),
);
const { tokenList } = this.getTokenListState();
const tokensToDetect: string[] = [];
for (const address in tokenList) {
if (!tokensAddresses.includes(address)) {
tokensToDetect.push(address);
}
}
const sliceOfTokensToDetect = [];
sliceOfTokensToDetect[0] = tokensToDetect.slice(0, 1000);
sliceOfTokensToDetect[1] = tokensToDetect.slice(
1000,
tokensToDetect.length - 1,
);
/* istanbul ignore else */
if (!selectedAddress) {
return;
}
for (const tokensSlice of sliceOfTokensToDetect) {
if (tokensSlice.length === 0) {
break;
}
await safelyExecute(async () => {
const balances = await this.getBalancesInSingleCall(
selectedAddress,
tokensSlice,
);
const tokensToAdd: Token[] = [];
for (const tokenAddress in balances) {
let ignored;
/* istanbul ignore else */
const { ignoredTokens } = this.getTokensState();
if (ignoredTokens.length) {
ignored = ignoredTokens.find(
(ignoredTokenAddress) =>
ignoredTokenAddress === toChecksumHexAddress(tokenAddress),
);
}
const caseInsensitiveTokenKey =
Object.keys(tokenList).find(
(i) => i.toLowerCase() === tokenAddress.toLowerCase(),
) || '';
if (ignored === undefined) {
const { decimals, symbol, aggregators, iconUrl } =
tokenList[caseInsensitiveTokenKey];
tokensToAdd.push({
address: tokenAddress,
decimals,
symbol,
aggregators,
image: iconUrl,
isERC721: false,
});
}
}
if (tokensToAdd.length) {
await this.addDetectedTokens(tokensToAdd, {
selectedAddress,
chainId,
});
}
});
}
}
}
export default TokenDetectionController;