-
-
Notifications
You must be signed in to change notification settings - Fork 219
/
Copy pathTokensController.ts
1166 lines (1054 loc) · 36.5 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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Contract } from '@ethersproject/contracts';
import { Web3Provider } from '@ethersproject/providers';
import type {
AccountsControllerGetAccountAction,
AccountsControllerGetSelectedAccountAction,
AccountsControllerSelectedEvmAccountChangeEvent,
} from '@metamask/accounts-controller';
import type { AddApprovalRequest } from '@metamask/approval-controller';
import type {
RestrictedMessenger,
ControllerGetStateAction,
ControllerStateChangeEvent,
} from '@metamask/base-controller';
import { BaseController } from '@metamask/base-controller';
import contractsMap from '@metamask/contract-metadata';
import {
toChecksumHexAddress,
ERC721_INTERFACE_ID,
ORIGIN_METAMASK,
ApprovalType,
ERC20,
ERC721,
ERC1155,
isValidHexAddress,
safelyExecute,
} from '@metamask/controller-utils';
import type { InternalAccount } from '@metamask/keyring-internal-api';
import { abiERC721 } from '@metamask/metamask-eth-abis';
import type {
NetworkClientId,
NetworkControllerGetNetworkClientByIdAction,
NetworkControllerNetworkDidChangeEvent,
NetworkControllerStateChangeEvent,
NetworkState,
Provider,
} from '@metamask/network-controller';
import { rpcErrors } from '@metamask/rpc-errors';
import type { Hex } from '@metamask/utils';
import { Mutex } from 'async-mutex';
import type { Patch } from 'immer';
import { v1 as random } from 'uuid';
import { formatAggregatorNames, formatIconUrlWithProxy } from './assetsUtil';
import { ERC20Standard } from './Standards/ERC20Standard';
import { ERC1155Standard } from './Standards/NftStandards/ERC1155/ERC1155Standard';
import {
fetchTokenMetadata,
TOKEN_METADATA_NO_SUPPORT_ERROR,
} from './token-service';
import type {
TokenListMap,
TokenListStateChange,
TokenListToken,
} from './TokenListController';
import type { Token } from './TokenRatesController';
/**
* @type SuggestedAssetMeta
*
* Suggested asset by EIP747 meta data
* @property id - Generated UUID associated with this suggested asset
* @property time - Timestamp associated with this this suggested asset
* @property type - Type type this suggested asset
* @property asset - Asset suggested object
* @property interactingAddress - Account address that requested watch asset
*/
type SuggestedAssetMeta = {
id: string;
time: number;
type: string;
asset: Token;
interactingAddress: string;
};
/**
* @type TokensControllerState
*
* 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
*/
export type TokensControllerState = {
tokens: Token[];
ignoredTokens: string[];
detectedTokens: Token[];
allTokens: { [chainId: Hex]: { [key: string]: Token[] } };
allIgnoredTokens: { [chainId: Hex]: { [key: string]: string[] } };
allDetectedTokens: { [chainId: Hex]: { [key: string]: Token[] } };
};
const metadata = {
tokens: {
persist: true,
anonymous: false,
},
ignoredTokens: {
persist: true,
anonymous: false,
},
detectedTokens: {
persist: true,
anonymous: false,
},
allTokens: {
persist: true,
anonymous: false,
},
allIgnoredTokens: {
persist: true,
anonymous: false,
},
allDetectedTokens: {
persist: true,
anonymous: false,
},
};
const controllerName = 'TokensController';
export type TokensControllerActions =
| TokensControllerGetStateAction
| TokensControllerAddDetectedTokensAction;
export type TokensControllerGetStateAction = ControllerGetStateAction<
typeof controllerName,
TokensControllerState
>;
export type TokensControllerAddDetectedTokensAction = {
type: `${typeof controllerName}:addDetectedTokens`;
handler: TokensController['addDetectedTokens'];
};
/**
* The external actions available to the {@link TokensController}.
*/
export type AllowedActions =
| AddApprovalRequest
| NetworkControllerGetNetworkClientByIdAction
| AccountsControllerGetAccountAction
| AccountsControllerGetSelectedAccountAction;
export type TokensControllerStateChangeEvent = ControllerStateChangeEvent<
typeof controllerName,
TokensControllerState
>;
export type TokensControllerEvents = TokensControllerStateChangeEvent;
export type AllowedEvents =
| NetworkControllerStateChangeEvent
| NetworkControllerNetworkDidChangeEvent
| TokenListStateChange
| AccountsControllerSelectedEvmAccountChangeEvent;
/**
* The messenger of the {@link TokensController}.
*/
export type TokensControllerMessenger = RestrictedMessenger<
typeof controllerName,
TokensControllerActions | AllowedActions,
TokensControllerEvents | AllowedEvents,
AllowedActions['type'],
AllowedEvents['type']
>;
export const getDefaultTokensState = (): TokensControllerState => {
return {
tokens: [],
ignoredTokens: [],
detectedTokens: [],
allTokens: {},
allIgnoredTokens: {},
allDetectedTokens: {},
};
};
/**
* Controller that stores assets and exposes convenience methods
*/
export class TokensController extends BaseController<
typeof controllerName,
TokensControllerState,
TokensControllerMessenger
> {
readonly #mutex = new Mutex();
#chainId: Hex;
#selectedAccountId: string;
#provider: Provider;
#abortController: AbortController;
/**
* Tokens controller options
* @param options - Constructor options.
* @param options.chainId - The chain ID of the current network.
* @param options.provider - Network provider.
* @param options.state - Initial state to set on this controller.
* @param options.messenger - The messenger.
*/
constructor({
chainId: initialChainId,
provider,
state,
messenger,
}: {
chainId: Hex;
provider: Provider;
state?: Partial<TokensControllerState>;
messenger: TokensControllerMessenger;
}) {
super({
name: controllerName,
metadata,
messenger,
state: {
...getDefaultTokensState(),
...state,
},
});
this.#chainId = initialChainId;
this.#provider = provider;
this.#selectedAccountId = this.#getSelectedAccount().id;
this.#abortController = new AbortController();
this.messagingSystem.registerActionHandler(
`${controllerName}:addDetectedTokens` as const,
this.addDetectedTokens.bind(this),
);
this.messagingSystem.subscribe(
'AccountsController:selectedEvmAccountChange',
this.#onSelectedAccountChange.bind(this),
);
this.messagingSystem.subscribe(
'NetworkController:networkDidChange',
this.#onNetworkDidChange.bind(this),
);
this.messagingSystem.subscribe(
'NetworkController:stateChange',
this.#onNetworkStateChange.bind(this),
);
this.messagingSystem.subscribe(
'TokenListController:stateChange',
({ tokenList }) => {
const { tokens } = this.state;
if (tokens.length && !tokens[0].name) {
this.#updateTokensAttribute(tokenList, 'name');
}
},
);
}
/**
* Handles the event when the network changes.
*
* @param networkState - The changed network state.
* @param networkState.selectedNetworkClientId - The ID of the currently
* selected network client.
*/
#onNetworkDidChange({ selectedNetworkClientId }: NetworkState) {
const selectedNetworkClient = this.messagingSystem.call(
'NetworkController:getNetworkClientById',
selectedNetworkClientId,
);
const { allTokens, allIgnoredTokens, allDetectedTokens } = this.state;
const { chainId } = selectedNetworkClient.configuration;
this.#abortController.abort();
this.#abortController = new AbortController();
this.#chainId = chainId;
const selectedAddress = this.#getSelectedAddress();
this.update((state) => {
state.tokens = allTokens[chainId]?.[selectedAddress] || [];
state.ignoredTokens = allIgnoredTokens[chainId]?.[selectedAddress] || [];
state.detectedTokens =
allDetectedTokens[chainId]?.[selectedAddress] || [];
});
}
/**
* Handles the event when the 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) => {
delete state.allTokens[removedChainId];
delete state.allIgnoredTokens[removedChainId];
delete state.allDetectedTokens[removedChainId];
});
}
}
}
/**
* Handles the selected account change in the accounts controller.
* @param selectedAccount - The new selected account
*/
#onSelectedAccountChange(selectedAccount: InternalAccount) {
const { allTokens, allIgnoredTokens, allDetectedTokens } = this.state;
this.#selectedAccountId = selectedAccount.id;
this.update((state) => {
state.tokens = allTokens[this.#chainId]?.[selectedAccount.address] ?? [];
state.ignoredTokens =
allIgnoredTokens[this.#chainId]?.[selectedAccount.address] ?? [];
state.detectedTokens =
allDetectedTokens[this.#chainId]?.[selectedAccount.address] ?? [];
});
}
/**
* Fetch metadata for a token.
*
* @param tokenAddress - The address of the token.
* @returns The token metadata.
*/
async #fetchTokenMetadata(
tokenAddress: string,
): Promise<TokenListToken | undefined> {
try {
const token = await fetchTokenMetadata<TokenListToken>(
this.#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;
}
}
/**
* Adds a token to the stored token list.
*
* @param options - The method argument object.
* @param options.address - Hex address of the token contract.
* @param options.symbol - Symbol of the token.
* @param options.decimals - Number of decimals the token uses.
* @param options.name - Name of the token.
* @param options.image - Image of the token.
* @param options.interactingAddress - The address of the account to add a token to.
* @param options.networkClientId - Network Client ID.
* @returns Current token list.
*/
async addToken({
address,
symbol,
decimals,
name,
image,
interactingAddress,
networkClientId,
}: {
address: string;
symbol: string;
decimals: number;
name?: string;
image?: string;
interactingAddress?: string;
networkClientId?: NetworkClientId;
}): Promise<Token[]> {
const chainId = this.#chainId;
const releaseLock = await this.#mutex.acquire();
const { allTokens, allIgnoredTokens, allDetectedTokens } = this.state;
let currentChainId = chainId;
if (networkClientId) {
currentChainId = this.messagingSystem.call(
'NetworkController:getNetworkClientById',
networkClientId,
).configuration.chainId;
}
const accountAddress =
this.#getAddressOrSelectedAddress(interactingAddress);
const isInteractingWithWalletAccount =
this.#isInteractingWithWallet(accountAddress);
try {
address = toChecksumHexAddress(address);
const tokens = allTokens[currentChainId]?.[accountAddress] || [];
const ignoredTokens =
allIgnoredTokens[currentChainId]?.[accountAddress] || [];
const detectedTokens =
allDetectedTokens[currentChainId]?.[accountAddress] || [];
const newTokens: Token[] = [...tokens];
const [isERC721, tokenMetadata] = await Promise.all([
this.#detectIsERC721(address, networkClientId),
// TODO parameterize the token metadata fetch by networkClientId
this.#fetchTokenMetadata(address),
]);
// TODO remove this once this method is fully parameterized by networkClientId
if (!networkClientId && currentChainId !== this.#chainId) {
throw new Error(
'TokensController Error: Switched networks while adding token',
);
}
const newEntry: Token = {
address,
symbol,
decimals,
image:
image ||
formatIconUrlWithProxy({
chainId: currentChainId,
tokenAddress: address,
}),
isERC721,
aggregators: formatAggregatorNames(tokenMetadata?.aggregators || []),
name,
};
const previousIndex = newTokens.findIndex(
(token) => token.address.toLowerCase() === address.toLowerCase(),
);
if (previousIndex !== -1) {
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,
interactingAddress: accountAddress,
interactingChainId: currentChainId,
});
let newState: Partial<TokensControllerState> = {
allTokens: newAllTokens,
allIgnoredTokens: newAllIgnoredTokens,
allDetectedTokens: newAllDetectedTokens,
};
// Only update active tokens if user is interacting with their active wallet account.
if (isInteractingWithWalletAccount) {
newState = {
...newState,
tokens: newTokens,
ignoredTokens: newIgnoredTokens,
detectedTokens: newDetectedTokens,
};
}
this.update((state) => {
Object.assign(state, newState);
});
return newTokens;
} finally {
releaseLock();
}
}
/**
* Add a batch of tokens.
*
* @param tokensToImport - Array of tokens to import.
* @param networkClientId - Optional network client ID used to determine interacting chain ID.
*/
async addTokens(tokensToImport: Token[], networkClientId?: NetworkClientId) {
const releaseLock = await this.#mutex.acquire();
const { allTokens, ignoredTokens, allDetectedTokens } = this.state;
const importedTokensMap: { [key: string]: true } = {};
let interactingChainId: Hex = this.#chainId;
if (networkClientId) {
interactingChainId = this.messagingSystem.call(
'NetworkController:getNetworkClientById',
networkClientId,
).configuration.chainId;
}
// Used later to dedupe imported tokens
const newTokensMap = [
...(allTokens[interactingChainId]?.[this.#getSelectedAccount().address] ||
[]),
...tokensToImport,
].reduce(
(output, token) => {
output[token.address] = token;
return output;
},
{} as { [address: string]: Token },
);
try {
tokensToImport.forEach((tokenToAdd) => {
const { address, symbol, decimals, image, aggregators, name } =
tokenToAdd;
const checksumAddress = toChecksumHexAddress(address);
const formattedToken: Token = {
address: checksumAddress,
symbol,
decimals,
image,
aggregators,
name,
};
newTokensMap[address] = formattedToken;
importedTokensMap[address.toLowerCase()] = true;
return formattedToken;
});
const newTokens = Object.values(newTokensMap);
const newIgnoredTokens = ignoredTokens.filter(
(tokenAddress) => !newTokensMap[tokenAddress.toLowerCase()],
);
const detectedTokensForGivenChain = interactingChainId
? allDetectedTokens?.[interactingChainId]?.[this.#getSelectedAddress()]
: [];
const newDetectedTokens = detectedTokensForGivenChain?.filter(
(t) => !importedTokensMap[t.address.toLowerCase()],
);
const { newAllTokens, newAllDetectedTokens, newAllIgnoredTokens } =
this.#getNewAllTokensState({
newTokens,
newDetectedTokens,
newIgnoredTokens,
interactingChainId,
});
this.update((state) => {
if (interactingChainId === this.#chainId) {
state.tokens = newTokens;
state.detectedTokens = newDetectedTokens;
state.ignoredTokens = newIgnoredTokens;
}
state.allTokens = newAllTokens;
state.allDetectedTokens = newAllDetectedTokens;
state.allIgnoredTokens = newAllIgnoredTokens;
});
} finally {
releaseLock();
}
}
/**
* Ignore a batch of tokens.
*
* @param tokenAddressesToIgnore - Array of token addresses to ignore.
* @param networkClientId - Optional network client ID used to determine interacting chain ID.
*/
ignoreTokens(
tokenAddressesToIgnore: string[],
networkClientId?: NetworkClientId,
) {
let interactingChainId = this.#chainId;
if (networkClientId) {
interactingChainId = this.messagingSystem.call(
'NetworkController:getNetworkClientById',
networkClientId,
).configuration.chainId;
}
const { allTokens, allDetectedTokens, allIgnoredTokens } = this.state;
const ignoredTokensMap: { [key: string]: true } = {};
const ignoredTokens =
allIgnoredTokens[interactingChainId ?? this.#chainId]?.[
this.#getSelectedAddress()
] || [];
let newIgnoredTokens: string[] = [...ignoredTokens];
const tokens =
allTokens[interactingChainId ?? this.#chainId]?.[
this.#getSelectedAddress()
] || [];
const detectedTokens =
allDetectedTokens[interactingChainId ?? this.#chainId]?.[
this.#getSelectedAddress()
] || [];
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,
interactingChainId,
});
this.update((state) => {
state.allIgnoredTokens = newAllIgnoredTokens;
state.allDetectedTokens = newAllDetectedTokens;
state.allTokens = newAllTokens;
if (interactingChainId === this.#chainId) {
state.detectedTokens = newDetectedTokens;
state.tokens = newTokens;
state.ignoredTokens = newIgnoredTokens;
}
});
}
/**
* 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: Hex },
) {
const releaseLock = await this.#mutex.acquire();
const chainId = detectionDetails?.chainId ?? this.#chainId;
// Previously selectedAddress could be an empty string. This is to preserve the behaviour
const accountAddress =
detectionDetails?.selectedAddress ?? this.#getSelectedAddress();
const { allTokens, allDetectedTokens, allIgnoredTokens } = this.state;
let newTokens = [...(allTokens?.[chainId]?.[accountAddress] ?? [])];
let newDetectedTokens = [
...(allDetectedTokens?.[chainId]?.[accountAddress] ?? []),
];
try {
incomingDetectedTokens.forEach((tokenToAdd) => {
const {
address,
symbol,
decimals,
image,
aggregators,
isERC721,
name,
} = tokenToAdd;
const checksumAddress = toChecksumHexAddress(address);
const newEntry: Token = {
address: checksumAddress,
symbol,
decimals,
image,
isERC721,
aggregators,
name,
};
const previousImportedIndex = newTokens.findIndex(
(token) =>
token.address.toLowerCase() === checksumAddress.toLowerCase(),
);
if (previousImportedIndex !== -1) {
// Update existing data of imported token
newTokens[previousImportedIndex] = newEntry;
} else {
const ignoredTokenIndex =
allIgnoredTokens?.[chainId]?.[accountAddress]?.indexOf(address) ??
-1;
if (ignoredTokenIndex === -1) {
// Add detected token
const previousDetectedIndex = newDetectedTokens.findIndex(
(token) =>
token.address.toLowerCase() === checksumAddress.toLowerCase(),
);
if (previousDetectedIndex !== -1) {
newDetectedTokens[previousDetectedIndex] = newEntry;
} else {
newDetectedTokens.push(newEntry);
}
}
}
});
const { newAllTokens, newAllDetectedTokens } = this.#getNewAllTokensState(
{
newTokens,
newDetectedTokens,
interactingAddress: accountAddress,
interactingChainId: chainId,
},
);
// We may be detecting tokens on a different chain/account pair than are currently configured.
// Re-point `tokens` and `detectedTokens` to keep them referencing the current chain/account.
const selectedAddress = this.#getSelectedAddress();
newTokens = newAllTokens?.[this.#chainId]?.[selectedAddress] || [];
newDetectedTokens =
newAllDetectedTokens?.[this.#chainId]?.[selectedAddress] || [];
this.update((state) => {
state.tokens = newTokens;
state.allTokens = newAllTokens;
state.detectedTokens = newDetectedTokens;
state.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.tokens];
const tokenIndex = tokens.findIndex((token) => {
return token.address.toLowerCase() === tokenAddress.toLowerCase();
});
const updatedToken = { ...tokens[tokenIndex], isERC721 };
tokens[tokenIndex] = updatedToken;
this.update((state) => {
state.tokens = tokens;
});
return updatedToken;
}
/**
* This is a function that updates the tokens name for the tokens name if it is not defined.
*
* @param tokenList - Represents the fetched token list from service API
* @param tokenAttribute - Represents the token attribute that we want to update on the token list
*/
#updateTokensAttribute(
tokenList: TokenListMap,
tokenAttribute: keyof Token & keyof TokenListToken,
) {
const { tokens } = this.state;
const newTokens = tokens.map((token) => {
const newToken = tokenList[token.address.toLowerCase()];
return !token[tokenAttribute] && newToken?.[tokenAttribute]
? { ...token, [tokenAttribute]: newToken[tokenAttribute] }
: { ...token };
});
this.update((state) => {
state.tokens = newTokens;
});
}
/**
* Detects whether or not a token is ERC-721 compatible.
*
* @param tokenAddress - The token contract address.
* @param networkClientId - Optional network client ID to fetch contract info with.
* @returns A boolean indicating whether the token address passed in supports the EIP-721
* interface.
*/
async #detectIsERC721(
tokenAddress: string,
networkClientId?: NetworkClientId,
) {
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,
networkClientId,
);
try {
return await tokenContract.supportsInterface(ERC721_INTERFACE_ID);
} catch (error) {
// 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;
}
}
#getProvider(networkClientId?: NetworkClientId): Web3Provider {
return new Web3Provider(
networkClientId
? this.messagingSystem.call(
'NetworkController:getNetworkClientById',
networkClientId,
).provider
: this.#provider,
);
}
#createEthersContract(
tokenAddress: string,
abi: string,
networkClientId?: NetworkClientId,
): Contract {
const web3provider = this.#getProvider(networkClientId);
const tokenContract = new Contract(tokenAddress, abi, web3provider);
return tokenContract;
}
#generateRandomId(): string {
return random();
}
/**
* Adds a new suggestedAsset to the list of watched assets.
* Parameters will be validated according to the asset type being watched.
*
* @param options - The method options.
* @param options.asset - The asset to be watched. For now only ERC20 tokens are accepted.
* @param options.type - The asset type.
* @param options.interactingAddress - The address of the account that is requesting to watch the asset.
* @param options.networkClientId - Network Client ID.
* @returns A promise that resolves if the asset was watched successfully, and rejects otherwise.
*/
async watchAsset({
asset,
type,
interactingAddress,
networkClientId,
}: {
asset: Token;
type: string;
interactingAddress?: string;
networkClientId?: NetworkClientId;
}): Promise<void> {
if (type !== ERC20) {
throw new Error(`Asset of type ${type} not supported`);
}
if (!asset.address) {
throw rpcErrors.invalidParams('Address must be specified');
}
if (!isValidHexAddress(asset.address)) {
throw rpcErrors.invalidParams(`Invalid address "${asset.address}"`);
}
const selectedAddress =
this.#getAddressOrSelectedAddress(interactingAddress);
// Validate contract
if (await this.#detectIsERC721(asset.address, networkClientId)) {
throw rpcErrors.invalidParams(
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Contract ${asset.address} must match type ${type}, but was detected as ${ERC721}`,
);
}
const provider = this.#getProvider(networkClientId);
const isErc1155 = await safelyExecute(() =>
new ERC1155Standard(provider).contractSupportsBase1155Interface(
asset.address,
),
);
if (isErc1155) {
throw rpcErrors.invalidParams(
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Contract ${asset.address} must match type ${type}, but was detected as ${ERC1155}`,
);
}
const erc20 = new ERC20Standard(provider);
const [contractName, contractSymbol, contractDecimals] = await Promise.all([
safelyExecute(() => erc20.getTokenName(asset.address)),
safelyExecute(() => erc20.getTokenSymbol(asset.address)),
safelyExecute(async () => erc20.getTokenDecimals(asset.address)),
]);
asset.name = contractName;
// Validate symbol
if (!asset.symbol && !contractSymbol) {
throw rpcErrors.invalidParams(
'A symbol is required, but was not found in either the request or contract',
);
}
if (
contractSymbol !== undefined &&
asset.symbol !== undefined &&
asset.symbol.toUpperCase() !== contractSymbol.toUpperCase()
) {
throw rpcErrors.invalidParams(
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`The symbol in the request (${asset.symbol}) does not match the symbol in the contract (${contractSymbol})`,
);
}
asset.symbol = contractSymbol ?? asset.symbol;
if (typeof asset.symbol !== 'string') {
throw rpcErrors.invalidParams(`Invalid symbol: not a string`);
}
if (asset.symbol.length > 11) {
throw rpcErrors.invalidParams(
`Invalid symbol "${asset.symbol}": longer than 11 characters`,
);
}
// Validate decimals
if (asset.decimals === undefined && contractDecimals === undefined) {
throw rpcErrors.invalidParams(
'Decimals are required, but were not found in either the request or contract',
);
}
if (
contractDecimals !== undefined &&
asset.decimals !== undefined &&
String(asset.decimals) !== contractDecimals
) {
throw rpcErrors.invalidParams(
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`The decimals in the request (${asset.decimals}) do not match the decimals in the contract (${contractDecimals})`,
);
}
const decimalsStr = contractDecimals ?? asset.decimals;
const decimalsNum = parseInt(decimalsStr as unknown as string, 10);
if (!Number.isInteger(decimalsNum) || decimalsNum > 36 || decimalsNum < 0) {
throw rpcErrors.invalidParams(
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Invalid decimals "${decimalsStr}": must be an integer 0 <= 36`,
);
}
asset.decimals = decimalsNum;
const suggestedAssetMeta: SuggestedAssetMeta = {
asset,
id: this.#generateRandomId(),
time: Date.now(),
type,
interactingAddress: selectedAddress,
};
await this.#requestApproval(suggestedAssetMeta);
const { address, symbol, decimals, name, image } = asset;
await this.addToken({
address,
symbol,
decimals,
name,
image,
interactingAddress: suggestedAssetMeta.interactingAddress,