-
-
Notifications
You must be signed in to change notification settings - Fork 196
/
TokensController.ts
810 lines (754 loc) · 26.4 KB
/
TokensController.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
import { EventEmitter } from 'events';
import contractsMap from '@metamask/contract-metadata';
import { abiERC721 } from '@metamask/metamask-eth-abis';
import { v1 as random } from 'uuid';
import { Mutex } from 'async-mutex';
import { Contract } from '@ethersproject/contracts';
import { Web3Provider } from '@ethersproject/providers';
import { AbortController as WhatwgAbortController } from 'abort-controller';
import {
BaseController,
BaseConfig,
BaseState,
} from '@metamask/base-controller';
import type { PreferencesState } from '@metamask/preferences-controller';
import type { NetworkState } from '@metamask/network-controller';
import {
NetworkType,
toChecksumHexAddress,
MAINNET,
ERC721_INTERFACE_ID,
} from '@metamask/controller-utils';
import type { Token } from './TokenRatesController';
import { TokenListToken } from './TokenListController';
import {
formatAggregatorNames,
formatIconUrlWithProxy,
validateTokenToWatch,
} from './assetsUtil';
import {
fetchTokenMetadata,
TOKEN_METADATA_NO_SUPPORT_ERROR,
} from './token-service';
/**
* @type TokensConfig
*
* Tokens controller configuration
* @property networkType - Network ID as per net_version
* @property selectedAddress - Vault selected address
*/
export interface TokensConfig extends BaseConfig {
networkType: NetworkType;
selectedAddress: string;
chainId: string;
provider: any;
}
/**
* @type AssetSuggestionResult
* @property result - Promise resolving to a new suggested asset address
* @property suggestedAssetMeta - Meta information about this new suggested asset
*/
interface AssetSuggestionResult {
result: Promise<string>;
suggestedAssetMeta: SuggestedAssetMeta;
}
enum SuggestedAssetStatus {
accepted = 'accepted',
failed = 'failed',
pending = 'pending',
rejected = 'rejected',
}
export type SuggestedAssetMetaBase = {
id: string;
time: number;
type: string;
asset: Token;
};
/**
* @type SuggestedAssetMeta
*
* Suggested asset by EIP747 meta data
* @property error - Synthesized error information for failed asset suggestions
* @property id - Generated UUID associated with this suggested asset
* @property status - String status of this this suggested asset
* @property time - Timestamp associated with this this suggested asset
* @property type - Type type this suggested asset
* @property asset - Asset suggested object
*/
export type SuggestedAssetMeta =
| (SuggestedAssetMetaBase & {
status: SuggestedAssetStatus.failed;
error: Error;
})
| (SuggestedAssetMetaBase & {
status:
| SuggestedAssetStatus.accepted
| SuggestedAssetStatus.rejected
| SuggestedAssetStatus.pending;
});
/**
* @type TokensState
*
* Assets controller state
* @property tokens - List of tokens associated with the active network and address pair
* @property ignoredTokens - List of ignoredTokens associated with the active network and address pair
* @property detectedTokens - List of detected tokens associated with the active network and address pair
* @property allTokens - Object containing tokens by network and account
* @property allIgnoredTokens - Object containing hidden/ignored tokens by network and account
* @property allDetectedTokens - Object containing tokens detected with non-zero balances
* @property suggestedAssets - List of pending suggested assets to be added or canceled
*/
export interface TokensState extends BaseState {
tokens: Token[];
ignoredTokens: string[];
detectedTokens: Token[];
allTokens: { [key: string]: { [key: string]: Token[] } };
allIgnoredTokens: { [key: string]: { [key: string]: string[] } };
allDetectedTokens: { [key: string]: { [key: string]: Token[] } };
suggestedAssets: SuggestedAssetMeta[];
}
/**
* Controller that stores assets and exposes convenience methods
*/
export class TokensController extends BaseController<
TokensConfig,
TokensState
> {
private mutex = new Mutex();
private ethersProvider: any;
private abortController: WhatwgAbortController;
private failSuggestedAsset(
suggestedAssetMeta: SuggestedAssetMeta,
error: unknown,
) {
const failedSuggestedAssetMeta = {
...suggestedAssetMeta,
status: SuggestedAssetStatus.failed,
error,
};
this.hub.emit(
`${suggestedAssetMeta.id}:finished`,
failedSuggestedAssetMeta,
);
}
/**
* Fetch metadata for a token.
*
* @param tokenAddress - The address of the token.
* @returns The token metadata.
*/
private async fetchTokenMetadata(
tokenAddress: string,
): Promise<TokenListToken | undefined> {
try {
const token = await fetchTokenMetadata<TokenListToken>(
this.config.chainId,
tokenAddress,
this.abortController.signal,
);
return token;
} catch (error) {
if (
error instanceof Error &&
error.message.includes(TOKEN_METADATA_NO_SUPPORT_ERROR)
) {
return undefined;
}
throw error;
}
}
/**
* EventEmitter instance used to listen to specific EIP747 events
*/
hub = new EventEmitter();
/**
* Name of this controller used during composition
*/
override name = 'TokensController';
/**
* Creates a TokensController instance.
*
* @param options - The controller options.
* @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
* @param options.onNetworkStateChange - Allows subscribing to network controller state changes.
* @param options.config - Initial options used to configure this controller.
* @param options.state - Initial state to set on this controller.
*/
constructor({
onPreferencesStateChange,
onNetworkStateChange,
config,
state,
}: {
onPreferencesStateChange: (
listener: (preferencesState: PreferencesState) => void,
) => void;
onNetworkStateChange: (
listener: (networkState: NetworkState) => void,
) => void;
config?: Partial<TokensConfig>;
state?: Partial<TokensState>;
}) {
super(config, state);
this.defaultConfig = {
networkType: MAINNET,
selectedAddress: '',
chainId: '',
provider: undefined,
...config,
};
this.defaultState = {
tokens: [],
ignoredTokens: [],
detectedTokens: [],
allTokens: {},
allIgnoredTokens: {},
allDetectedTokens: {},
suggestedAssets: [],
...state,
};
this.initialize();
this.abortController = new WhatwgAbortController();
onPreferencesStateChange(({ selectedAddress }) => {
const { allTokens, allIgnoredTokens, allDetectedTokens } = this.state;
const { chainId } = this.config;
this.configure({ selectedAddress });
this.update({
tokens: allTokens[chainId]?.[selectedAddress] || [],
ignoredTokens: allIgnoredTokens[chainId]?.[selectedAddress] || [],
detectedTokens: allDetectedTokens[chainId]?.[selectedAddress] || [],
});
});
onNetworkStateChange(({ providerConfig }) => {
const { allTokens, allIgnoredTokens, allDetectedTokens } = this.state;
const { selectedAddress } = this.config;
const { chainId } = providerConfig;
this.abortController.abort();
this.abortController = new WhatwgAbortController();
this.configure({ chainId });
this.ethersProvider = this._instantiateNewEthersProvider();
this.update({
tokens: allTokens[chainId]?.[selectedAddress] || [],
ignoredTokens: allIgnoredTokens[chainId]?.[selectedAddress] || [],
detectedTokens: allDetectedTokens[chainId]?.[selectedAddress] || [],
});
});
}
_instantiateNewEthersProvider(): any {
return new Web3Provider(this.config?.provider);
}
/**
* Adds a token to the stored token list.
*
* @param address - Hex address of the token contract.
* @param symbol - Symbol of the token.
* @param decimals - Number of decimals the token uses.
* @param image - Image of the token.
* @returns Current token list.
*/
async addToken(
address: string,
symbol: string,
decimals: number,
image?: string,
): Promise<Token[]> {
const currentChainId = this.config.chainId;
const releaseLock = await this.mutex.acquire();
try {
address = toChecksumHexAddress(address);
const { tokens, ignoredTokens, detectedTokens } = this.state;
const newTokens: Token[] = [...tokens];
const [isERC721, tokenMetadata] = await Promise.all([
this._detectIsERC721(address),
this.fetchTokenMetadata(address),
]);
if (currentChainId !== this.config.chainId) {
throw new Error(
'TokensController Error: Switched networks while adding token',
);
}
const newEntry: Token = {
address,
symbol,
decimals,
image:
image ||
formatIconUrlWithProxy({
chainId: this.config.chainId,
tokenAddress: address,
}),
isERC721,
aggregators: formatAggregatorNames(tokenMetadata?.aggregators || []),
};
const previousEntry = newTokens.find(
(token) => token.address.toLowerCase() === address.toLowerCase(),
);
if (previousEntry) {
const previousIndex = newTokens.indexOf(previousEntry);
newTokens[previousIndex] = newEntry;
} else {
newTokens.push(newEntry);
}
const newIgnoredTokens = ignoredTokens.filter(
(tokenAddress) => tokenAddress.toLowerCase() !== address.toLowerCase(),
);
const newDetectedTokens = detectedTokens.filter(
(token) => token.address.toLowerCase() !== address.toLowerCase(),
);
const { newAllTokens, newAllIgnoredTokens, newAllDetectedTokens } =
this._getNewAllTokensState({
newTokens,
newIgnoredTokens,
newDetectedTokens,
});
this.update({
tokens: newTokens,
ignoredTokens: newIgnoredTokens,
detectedTokens: newDetectedTokens,
allTokens: newAllTokens,
allIgnoredTokens: newAllIgnoredTokens,
allDetectedTokens: newAllDetectedTokens,
});
return newTokens;
} finally {
releaseLock();
}
}
/**
* Add a batch of tokens.
*
* @param tokensToImport - Array of tokens to import.
*/
async addTokens(tokensToImport: Token[]) {
const releaseLock = await this.mutex.acquire();
const { tokens, detectedTokens, ignoredTokens } = this.state;
const importedTokensMap: { [key: string]: true } = {};
// Used later to dedupe imported tokens
const newTokensMap = tokens.reduce((output, current) => {
output[current.address] = current;
return output;
}, {} as { [address: string]: Token });
try {
tokensToImport.forEach((tokenToAdd) => {
const { address, symbol, decimals, image, aggregators } = tokenToAdd;
const checksumAddress = toChecksumHexAddress(address);
const formattedToken: Token = {
address: checksumAddress,
symbol,
decimals,
image,
aggregators,
};
newTokensMap[address] = formattedToken;
importedTokensMap[address.toLowerCase()] = true;
return formattedToken;
});
const newTokens = Object.values(newTokensMap);
const newDetectedTokens = detectedTokens.filter(
(token) => !importedTokensMap[token.address.toLowerCase()],
);
const newIgnoredTokens = ignoredTokens.filter(
(tokenAddress) => !newTokensMap[tokenAddress.toLowerCase()],
);
const { newAllTokens, newAllDetectedTokens, newAllIgnoredTokens } =
this._getNewAllTokensState({
newTokens,
newDetectedTokens,
newIgnoredTokens,
});
this.update({
tokens: newTokens,
allTokens: newAllTokens,
detectedTokens: newDetectedTokens,
allDetectedTokens: newAllDetectedTokens,
ignoredTokens: newIgnoredTokens,
allIgnoredTokens: newAllIgnoredTokens,
});
} finally {
releaseLock();
}
}
/**
* Ignore a batch of tokens.
*
* @param tokenAddressesToIgnore - Array of token addresses to ignore.
*/
ignoreTokens(tokenAddressesToIgnore: string[]) {
const { ignoredTokens, detectedTokens, tokens } = this.state;
const ignoredTokensMap: { [key: string]: true } = {};
let newIgnoredTokens: string[] = [...ignoredTokens];
const checksummedTokenAddresses = tokenAddressesToIgnore.map((address) => {
const checksumAddress = toChecksumHexAddress(address);
ignoredTokensMap[address.toLowerCase()] = true;
return checksumAddress;
});
newIgnoredTokens = [...ignoredTokens, ...checksummedTokenAddresses];
const newDetectedTokens = detectedTokens.filter(
(token) => !ignoredTokensMap[token.address.toLowerCase()],
);
const newTokens = tokens.filter(
(token) => !ignoredTokensMap[token.address.toLowerCase()],
);
const { newAllIgnoredTokens, newAllDetectedTokens, newAllTokens } =
this._getNewAllTokensState({
newIgnoredTokens,
newDetectedTokens,
newTokens,
});
this.update({
ignoredTokens: newIgnoredTokens,
tokens: newTokens,
detectedTokens: newDetectedTokens,
allIgnoredTokens: newAllIgnoredTokens,
allDetectedTokens: newAllDetectedTokens,
allTokens: newAllTokens,
});
}
/**
* Adds a batch of detected tokens to the stored token list.
*
* @param incomingDetectedTokens - Array of detected tokens to be added or updated.
* @param detectionDetails - An object containing the chain ID and address of the currently selected network on which the incomingDetectedTokens were detected.
* @param detectionDetails.selectedAddress - the account address on which the incomingDetectedTokens were detected.
* @param detectionDetails.chainId - the chainId on which the incomingDetectedTokens were detected.
*/
async addDetectedTokens(
incomingDetectedTokens: Token[],
detectionDetails?: { selectedAddress: string; chainId: string },
) {
const releaseLock = await this.mutex.acquire();
const { tokens, detectedTokens, ignoredTokens } = this.state;
const newTokens: Token[] = [...tokens];
let newDetectedTokens: Token[] = [...detectedTokens];
try {
incomingDetectedTokens.forEach((tokenToAdd) => {
const { address, symbol, decimals, image, aggregators, isERC721 } =
tokenToAdd;
const checksumAddress = toChecksumHexAddress(address);
const newEntry: Token = {
address: checksumAddress,
symbol,
decimals,
image,
isERC721,
aggregators,
};
const previousImportedEntry = newTokens.find(
(token) =>
token.address.toLowerCase() === checksumAddress.toLowerCase(),
);
if (previousImportedEntry) {
// Update existing data of imported token
const previousImportedIndex = newTokens.indexOf(
previousImportedEntry,
);
newTokens[previousImportedIndex] = newEntry;
} else {
const ignoredTokenIndex = ignoredTokens.indexOf(address);
if (ignoredTokenIndex === -1) {
// Add detected token
const previousDetectedEntry = newDetectedTokens.find(
(token) =>
token.address.toLowerCase() === checksumAddress.toLowerCase(),
);
if (previousDetectedEntry) {
const previousDetectedIndex = newDetectedTokens.indexOf(
previousDetectedEntry,
);
newDetectedTokens[previousDetectedIndex] = newEntry;
} else {
newDetectedTokens.push(newEntry);
}
}
}
});
const { selectedAddress: detectionAddress, chainId: detectionChainId } =
detectionDetails || {};
const { newAllTokens, newAllDetectedTokens } = this._getNewAllTokensState(
{
newTokens,
newDetectedTokens,
detectionAddress,
detectionChainId,
},
);
const { chainId, selectedAddress } = this.config;
// if the newly added detectedTokens were detected on (and therefore added to) a different chainId/selectedAddress than the currently configured combo
// the newDetectedTokens (which should contain the detectedTokens on the current chainId/address combo) needs to be repointed to the current chainId/address pair
// if the detectedTokens were detected on the current chainId/address then this won't change anything.
newDetectedTokens =
newAllDetectedTokens?.[chainId]?.[selectedAddress] || [];
this.update({
tokens: newTokens,
allTokens: newAllTokens,
detectedTokens: newDetectedTokens,
allDetectedTokens: newAllDetectedTokens,
});
} finally {
releaseLock();
}
}
/**
* Adds isERC721 field to token object. This is called when a user attempts to add tokens that
* were previously added which do not yet had isERC721 field.
*
* @param tokenAddress - The contract address of the token requiring the isERC721 field added.
* @returns The new token object with the added isERC721 field.
*/
async updateTokenType(tokenAddress: string) {
const isERC721 = await this._detectIsERC721(tokenAddress);
const { tokens } = this.state;
const tokenIndex = tokens.findIndex((token) => {
return token.address.toLowerCase() === tokenAddress.toLowerCase();
});
tokens[tokenIndex].isERC721 = isERC721;
this.update({ tokens });
return tokens[tokenIndex];
}
/**
* Detects whether or not a token is ERC-721 compatible.
*
* @param tokenAddress - The token contract address.
* @returns A boolean indicating whether the token address passed in supports the EIP-721
* interface.
*/
async _detectIsERC721(tokenAddress: string) {
const checksumAddress = toChecksumHexAddress(tokenAddress);
// if this token is already in our contract metadata map we don't need
// to check against the contract
if (contractsMap[checksumAddress]?.erc721 === true) {
return Promise.resolve(true);
} else if (contractsMap[checksumAddress]?.erc20 === true) {
return Promise.resolve(false);
}
const tokenContract = this._createEthersContract(
tokenAddress,
abiERC721,
this.ethersProvider,
);
try {
return await tokenContract.supportsInterface(ERC721_INTERFACE_ID);
} catch (error: any) {
// currently we see a variety of errors across different networks when
// token contracts are not ERC721 compatible. We need to figure out a better
// way of differentiating token interface types but for now if we get an error
// we have to assume the token is not ERC721 compatible.
return false;
}
}
_createEthersContract(
tokenAddress: string,
abi: string,
ethersProvider: any,
): Contract {
const tokenContract = new Contract(tokenAddress, abi, ethersProvider);
return tokenContract;
}
_generateRandomId(): string {
return random();
}
/**
* Adds a new suggestedAsset to state. Parameters will be validated according to
* asset type being watched. A `<suggestedAssetMeta.id>:pending` hub event will be emitted once added.
*
* @param asset - The asset to be watched. For now only ERC20 tokens are accepted.
* @param type - The asset type.
* @returns Object containing a Promise resolving to the suggestedAsset address if accepted.
*/
async watchAsset(asset: Token, type: string): Promise<AssetSuggestionResult> {
const suggestedAssetMeta = {
asset,
id: this._generateRandomId(),
status: SuggestedAssetStatus.pending as SuggestedAssetStatus.pending,
time: Date.now(),
type,
};
try {
switch (type) {
case 'ERC20':
validateTokenToWatch(asset);
break;
default:
throw new Error(`Asset of type ${type} not supported`);
}
} catch (error) {
this.failSuggestedAsset(suggestedAssetMeta, error);
return Promise.reject(error);
}
const result: Promise<string> = new Promise((resolve, reject) => {
this.hub.once(
`${suggestedAssetMeta.id}:finished`,
(meta: SuggestedAssetMeta) => {
switch (meta.status) {
case SuggestedAssetStatus.accepted:
return resolve(meta.asset.address);
case SuggestedAssetStatus.rejected:
return reject(new Error('User rejected to watch the asset.'));
case SuggestedAssetStatus.failed:
return reject(new Error(meta.error.message));
/* istanbul ignore next */
default:
return reject(new Error(`Unknown status: ${meta.status}`));
}
},
);
});
const { suggestedAssets } = this.state;
suggestedAssets.push(suggestedAssetMeta);
this.update({ suggestedAssets: [...suggestedAssets] });
this.hub.emit('pendingSuggestedAsset', suggestedAssetMeta);
return { result, suggestedAssetMeta };
}
/**
* Accepts to watch an asset and updates it's status and deletes the suggestedAsset from state,
* adding the asset to corresponding asset state. In this case ERC20 tokens.
* A `<suggestedAssetMeta.id>:finished` hub event is fired after accepted or failure.
*
* @param suggestedAssetID - The ID of the suggestedAsset to accept.
*/
async acceptWatchAsset(suggestedAssetID: string): Promise<void> {
const { suggestedAssets } = this.state;
const index = suggestedAssets.findIndex(
({ id }) => suggestedAssetID === id,
);
const suggestedAssetMeta = suggestedAssets[index];
try {
switch (suggestedAssetMeta.type) {
case 'ERC20':
const { address, symbol, decimals, image } = suggestedAssetMeta.asset;
await this.addToken(address, symbol, decimals, image);
suggestedAssetMeta.status = SuggestedAssetStatus.accepted;
this.hub.emit(
`${suggestedAssetMeta.id}:finished`,
suggestedAssetMeta,
);
break;
default:
throw new Error(
`Asset of type ${suggestedAssetMeta.type} not supported`,
);
}
} catch (error) {
this.failSuggestedAsset(suggestedAssetMeta, error);
}
const newSuggestedAssets = suggestedAssets.filter(
({ id }) => id !== suggestedAssetID,
);
this.update({ suggestedAssets: [...newSuggestedAssets] });
}
/**
* Rejects a watchAsset request based on its ID by setting its status to "rejected"
* and emitting a `<suggestedAssetMeta.id>:finished` hub event.
*
* @param suggestedAssetID - The ID of the suggestedAsset to accept.
*/
rejectWatchAsset(suggestedAssetID: string) {
const { suggestedAssets } = this.state;
const index = suggestedAssets.findIndex(
({ id }) => suggestedAssetID === id,
);
const suggestedAssetMeta = suggestedAssets[index];
if (!suggestedAssetMeta) {
return;
}
suggestedAssetMeta.status = SuggestedAssetStatus.rejected;
this.hub.emit(`${suggestedAssetMeta.id}:finished`, suggestedAssetMeta);
const newSuggestedAssets = suggestedAssets.filter(
({ id }) => id !== suggestedAssetID,
);
this.update({ suggestedAssets: [...newSuggestedAssets] });
}
/**
* Takes a new tokens and ignoredTokens array for the current network/account combination
* and returns new allTokens and allIgnoredTokens state to update to.
*
* @param params - Object that holds token params.
* @param params.newTokens - The new tokens to set for the current network and selected account.
* @param params.newIgnoredTokens - The new ignored tokens to set for the current network and selected account.
* @param params.newDetectedTokens - The new detected tokens to set for the current network and selected account.
* @param params.detectionAddress - The address on which the detected tokens to add were detected.
* @param params.detectionChainId - The chainId on which the detected tokens to add were detected.
* @returns The updated `allTokens` and `allIgnoredTokens` state.
*/
_getNewAllTokensState(params: {
newTokens?: Token[];
newIgnoredTokens?: string[];
newDetectedTokens?: Token[];
detectionAddress?: string;
detectionChainId?: string;
}) {
const {
newTokens,
newIgnoredTokens,
newDetectedTokens,
detectionAddress,
detectionChainId,
} = params;
const { allTokens, allIgnoredTokens, allDetectedTokens } = this.state;
const { chainId, selectedAddress } = this.config;
const userAddressToAddTokens = detectionAddress ?? selectedAddress;
const chainIdToAddTokens = detectionChainId ?? chainId;
let newAllTokens = allTokens;
if (
newTokens?.length ||
(newTokens &&
allTokens &&
allTokens[chainIdToAddTokens] &&
allTokens[chainIdToAddTokens][userAddressToAddTokens])
) {
const networkTokens = allTokens[chainIdToAddTokens];
const newNetworkTokens = {
...networkTokens,
...{ [userAddressToAddTokens]: newTokens },
};
newAllTokens = {
...allTokens,
...{ [chainIdToAddTokens]: newNetworkTokens },
};
}
let newAllIgnoredTokens = allIgnoredTokens;
if (
newIgnoredTokens?.length ||
(newIgnoredTokens &&
allIgnoredTokens &&
allIgnoredTokens[chainIdToAddTokens] &&
allIgnoredTokens[chainIdToAddTokens][userAddressToAddTokens])
) {
const networkIgnoredTokens = allIgnoredTokens[chainIdToAddTokens];
const newIgnoredNetworkTokens = {
...networkIgnoredTokens,
...{ [userAddressToAddTokens]: newIgnoredTokens },
};
newAllIgnoredTokens = {
...allIgnoredTokens,
...{ [chainIdToAddTokens]: newIgnoredNetworkTokens },
};
}
let newAllDetectedTokens = allDetectedTokens;
if (
newDetectedTokens?.length ||
(newDetectedTokens &&
allDetectedTokens &&
allDetectedTokens[chainIdToAddTokens] &&
allDetectedTokens[chainIdToAddTokens][userAddressToAddTokens])
) {
const networkDetectedTokens = allDetectedTokens[chainIdToAddTokens];
const newDetectedNetworkTokens = {
...networkDetectedTokens,
...{ [userAddressToAddTokens]: newDetectedTokens },
};
newAllDetectedTokens = {
...allDetectedTokens,
...{ [chainIdToAddTokens]: newDetectedNetworkTokens },
};
}
return { newAllTokens, newAllIgnoredTokens, newAllDetectedTokens };
}
/**
* Removes all tokens from the ignored list.
*/
clearIgnoredTokens() {
this.update({ ignoredTokens: [], allIgnoredTokens: {} });
}
}
export default TokensController;