@metamask-previews/assets-controllers 25.0.0-preview.83a88a4 → 25.0.0-preview.bc4dd941
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **BREAKING:** Adds `@metamask/accounts-controller` ^8.0.0 and `@metamask/keyring-controller` ^12.0.0 as dependencies and peer dependencies. ([#3775](https://github.com/MetaMask/core/pull/3775/)).
|
|
13
|
+
- **BREAKING:** `TokenDetectionController` newly subscribes to the `PreferencesController:stateChange`, `AccountsController:selectedAccountChange`, `KeyringController:lock`, `KeyringController:unlock` events, and allows the `PreferencesController:getState` messenger action. ([#3775](https://github.com/MetaMask/core/pull/3775/))
|
|
14
|
+
|
|
15
|
+
### Changed
|
|
16
|
+
|
|
17
|
+
- **BREAKING:** `TokenDetectionController` is merged with `DetectTokensController` from the `metamask-extension` repo. ([#3775](https://github.com/MetaMask/core/pull/3775/))
|
|
18
|
+
- **BREAKING:** `TokenDetectionController` now resets its polling interval to the default value of 3 minutes when token detection is triggered by external controller events `KeyringController:unlock`, `TokenListController:stateChange`, `PreferencesController:stateChange`, `AccountsController:selectedAccountChange`.
|
|
19
|
+
- **BREAKING:** `TokenDetectionController` now refetches tokens on `NetworkController:networkDidChange` if the `networkClientId` is changed instead of `chainId`.
|
|
20
|
+
- **BREAKING:** `TokenDetectionController` cannot initiate polling or token detection if `KeyringController` state is locked.
|
|
21
|
+
- **BREAKING:** The `detectTokens` method now excludes tokens that are already included in the `TokensController`'s `detectedTokens` list from the batch of incoming tokens it sends to the `TokensController` `addDetectedTokens` method.
|
|
22
|
+
- **BREAKING:** The constructor for `TokenDetectionController` expects a new required proprerty `trackMetaMetricsEvent`, which defines the callback that is called in the `detectTokens` method.
|
|
23
|
+
- **BREAKING:** In Mainnet, even if the `PreferenceController`'s `useTokenDetection` option is set to false, automatic token detection is performed on the legacy token list (token data from the contract-metadata repo).
|
|
24
|
+
|
|
25
|
+
### Removed
|
|
26
|
+
|
|
27
|
+
- **BREAKING:** `TokenDetectionController` constructor no longer accepts options `onPreferencesStateChange`, `getPreferencesState`. ([#3775](https://github.com/MetaMask/core/pull/3775/))
|
|
28
|
+
- **BREAKING:** `TokenDetectionController` no longer allows the `NetworkController:stateChange` event. The `NetworkController:networkDidChange` event can be used instead. ([#3775](https://github.com/MetaMask/core/pull/3775/))
|
|
29
|
+
|
|
10
30
|
## [25.0.0]
|
|
11
31
|
|
|
12
32
|
### Added
|
|
@@ -1,18 +1,21 @@
|
|
|
1
|
+
import type { AccountsControllerSelectedAccountChangeEvent } from '@metamask/accounts-controller';
|
|
1
2
|
import type { RestrictedControllerMessenger, ControllerGetStateAction, ControllerStateChangeEvent } from '@metamask/base-controller';
|
|
2
|
-
import type {
|
|
3
|
+
import type { KeyringControllerGetStateAction, KeyringControllerLockEvent, KeyringControllerUnlockEvent } from '@metamask/keyring-controller';
|
|
4
|
+
import type { NetworkClientId, NetworkControllerNetworkDidChangeEvent, NetworkControllerGetNetworkConfigurationByNetworkClientId } from '@metamask/network-controller';
|
|
3
5
|
import { StaticIntervalPollingController } from '@metamask/polling-controller';
|
|
4
|
-
import type {
|
|
6
|
+
import type { PreferencesControllerGetStateAction, PreferencesControllerStateChangeEvent } from '@metamask/preferences-controller';
|
|
5
7
|
import type { AssetsContractController } from './AssetsContractController';
|
|
6
|
-
import type { GetTokenListState, TokenListStateChange } from './TokenListController';
|
|
8
|
+
import type { GetTokenListState, TokenListStateChange, TokenListToken } from './TokenListController';
|
|
7
9
|
import type { TokensController, TokensState } from './TokensController';
|
|
10
|
+
export declare const STATIC_MAINNET_TOKEN_LIST: Record<string, Partial<TokenListToken>>;
|
|
8
11
|
export declare const controllerName = "TokenDetectionController";
|
|
9
12
|
export declare type TokenDetectionState = Record<never, never>;
|
|
10
13
|
export declare type TokenDetectionControllerGetStateAction = ControllerGetStateAction<typeof controllerName, TokenDetectionState>;
|
|
11
14
|
export declare type TokenDetectionControllerActions = TokenDetectionControllerGetStateAction;
|
|
12
|
-
export declare type AllowedActions = NetworkControllerGetNetworkConfigurationByNetworkClientId | GetTokenListState;
|
|
15
|
+
export declare type AllowedActions = NetworkControllerGetNetworkConfigurationByNetworkClientId | GetTokenListState | KeyringControllerGetStateAction | PreferencesControllerGetStateAction;
|
|
13
16
|
export declare type TokenDetectionControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, TokenDetectionState>;
|
|
14
17
|
export declare type TokenDetectionControllerEvents = TokenDetectionControllerStateChangeEvent;
|
|
15
|
-
export declare type AllowedEvents =
|
|
18
|
+
export declare type AllowedEvents = AccountsControllerSelectedAccountChangeEvent | NetworkControllerNetworkDidChangeEvent | TokenListStateChange | KeyringControllerLockEvent | KeyringControllerUnlockEvent | PreferencesControllerStateChangeEvent;
|
|
16
19
|
export declare type TokenDetectionControllerMessenger = RestrictedControllerMessenger<typeof controllerName, TokenDetectionControllerActions | AllowedActions, TokenDetectionControllerEvents | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
|
|
17
20
|
/**
|
|
18
21
|
* Controller that passively polls on a set interval for Tokens auto detection
|
|
@@ -21,6 +24,7 @@ export declare type TokenDetectionControllerMessenger = RestrictedControllerMess
|
|
|
21
24
|
* @property selectedAddress - Vault selected address
|
|
22
25
|
* @property networkClientId - The network client ID of the current selected network
|
|
23
26
|
* @property disabled - Boolean to track if network requests are blocked
|
|
27
|
+
* @property isUnlocked - Boolean to track if the keyring state is unlocked
|
|
24
28
|
* @property isDetectionEnabledFromPreferences - Boolean to track if detection is enabled from PreferencesController
|
|
25
29
|
* @property isDetectionEnabledForNetwork - Boolean to track if detected is enabled for current network
|
|
26
30
|
*/
|
|
@@ -35,22 +39,28 @@ export declare class TokenDetectionController extends StaticIntervalPollingContr
|
|
|
35
39
|
* @param options.interval - Polling interval used to fetch new token rates
|
|
36
40
|
* @param options.networkClientId - The selected network client ID of the current network
|
|
37
41
|
* @param options.selectedAddress - Vault selected address
|
|
38
|
-
* @param options.onPreferencesStateChange - Allows subscribing to preferences controller state changes.
|
|
39
42
|
* @param options.addDetectedTokens - Add a list of detected tokens.
|
|
40
43
|
* @param options.getBalancesInSingleCall - Gets the balances of a list of tokens for the given address.
|
|
41
44
|
* @param options.getTokensState - Gets the current state of the Tokens controller.
|
|
42
|
-
* @param options.
|
|
45
|
+
* @param options.trackMetaMetricsEvent - Sets options for MetaMetrics event tracking.
|
|
43
46
|
*/
|
|
44
|
-
constructor({ networkClientId, selectedAddress, interval, disabled,
|
|
47
|
+
constructor({ networkClientId, selectedAddress, interval, disabled, getBalancesInSingleCall, addDetectedTokens, getTokensState, trackMetaMetricsEvent, messenger, }: {
|
|
45
48
|
networkClientId: NetworkClientId;
|
|
46
49
|
selectedAddress?: string;
|
|
47
50
|
interval?: number;
|
|
48
51
|
disabled?: boolean;
|
|
49
|
-
onPreferencesStateChange: (listener: (preferencesState: PreferencesState) => void) => void;
|
|
50
52
|
addDetectedTokens: TokensController['addDetectedTokens'];
|
|
51
53
|
getBalancesInSingleCall: AssetsContractController['getBalancesInSingleCall'];
|
|
52
54
|
getTokensState: () => TokensState;
|
|
53
|
-
|
|
55
|
+
trackMetaMetricsEvent: (options: {
|
|
56
|
+
event: string;
|
|
57
|
+
category: string;
|
|
58
|
+
properties: {
|
|
59
|
+
tokens: string[];
|
|
60
|
+
token_standard: string;
|
|
61
|
+
asset_type: string;
|
|
62
|
+
};
|
|
63
|
+
}) => void;
|
|
54
64
|
messenger: TokenDetectionControllerMessenger;
|
|
55
65
|
});
|
|
56
66
|
/**
|
|
@@ -61,6 +71,12 @@ export declare class TokenDetectionController extends StaticIntervalPollingContr
|
|
|
61
71
|
* Blocks controller from making network calls
|
|
62
72
|
*/
|
|
63
73
|
disable(): void;
|
|
74
|
+
/**
|
|
75
|
+
* Internal isActive state
|
|
76
|
+
*
|
|
77
|
+
* @type {object}
|
|
78
|
+
*/
|
|
79
|
+
get isActive(): boolean;
|
|
64
80
|
/**
|
|
65
81
|
* Start polling for detected tokens.
|
|
66
82
|
*/
|
|
@@ -73,11 +89,12 @@ export declare class TokenDetectionController extends StaticIntervalPollingContr
|
|
|
73
89
|
address: string;
|
|
74
90
|
}): Promise<void>;
|
|
75
91
|
/**
|
|
76
|
-
*
|
|
92
|
+
* For each token in the token list provided by the TokenListController, checks the token's balance for the selected account address on the active network.
|
|
93
|
+
* On mainnet, if token detection is disabled in preferences, ERC20 token auto detection will be triggered for each contract address in the legacy token list from the @metamask/contract-metadata repo.
|
|
77
94
|
*
|
|
78
|
-
* @param options - Options
|
|
95
|
+
* @param options - Options for token detection.
|
|
79
96
|
* @param options.networkClientId - The ID of the network client to use.
|
|
80
|
-
* @param options.accountAddress -
|
|
97
|
+
* @param options.accountAddress - the selectedAddress against which to detect for token balances.
|
|
81
98
|
*/
|
|
82
99
|
detectTokens({ networkClientId, accountAddress, }?: {
|
|
83
100
|
networkClientId?: NetworkClientId;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TokenDetectionController.d.ts","sourceRoot":"","sources":["../src/TokenDetectionController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,6BAA6B,EAC7B,wBAAwB,EACxB,0BAA0B,EAC3B,MAAM,2BAA2B,CAAC;
|
|
1
|
+
{"version":3,"file":"TokenDetectionController.d.ts","sourceRoot":"","sources":["../src/TokenDetectionController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,4CAA4C,EAAE,MAAM,+BAA+B,CAAC;AAClG,OAAO,KAAK,EACV,6BAA6B,EAC7B,wBAAwB,EACxB,0BAA0B,EAC3B,MAAM,2BAA2B,CAAC;AAOnC,OAAO,KAAK,EACV,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAC7B,MAAM,8BAA8B,CAAC;AACtC,OA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AAG,OAAO,CAAC,IAAI,CAAC;CAiHvB;AAED,eAAe,wBAAwB,CAAC"}
|
|
@@ -19,13 +19,41 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
19
19
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
20
20
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
21
21
|
};
|
|
22
|
-
var
|
|
22
|
+
var __rest = (this && this.__rest) || function (s, e) {
|
|
23
|
+
var t = {};
|
|
24
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
25
|
+
t[p] = s[p];
|
|
26
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
27
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
28
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
29
|
+
t[p[i]] = s[p[i]];
|
|
30
|
+
}
|
|
31
|
+
return t;
|
|
32
|
+
};
|
|
33
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
34
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
35
|
+
};
|
|
36
|
+
var _TokenDetectionController_instances, _TokenDetectionController_intervalId, _TokenDetectionController_chainId, _TokenDetectionController_selectedAddress, _TokenDetectionController_networkClientId, _TokenDetectionController_disabled, _TokenDetectionController_isUnlocked, _TokenDetectionController_isDetectionEnabledFromPreferences, _TokenDetectionController_isDetectionEnabledForNetwork, _TokenDetectionController_addDetectedTokens, _TokenDetectionController_getBalancesInSingleCall, _TokenDetectionController_getTokensState, _TokenDetectionController_trackMetaMetricsEvent, _TokenDetectionController_registerEventListeners, _TokenDetectionController_stopPolling, _TokenDetectionController_startPolling, _TokenDetectionController_getCorrectChainId, _TokenDetectionController_restartTokenDetection;
|
|
23
37
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
-
exports.TokenDetectionController = exports.controllerName = void 0;
|
|
38
|
+
exports.TokenDetectionController = exports.controllerName = exports.STATIC_MAINNET_TOKEN_LIST = void 0;
|
|
39
|
+
const contract_metadata_1 = __importDefault(require("@metamask/contract-metadata"));
|
|
25
40
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
26
41
|
const polling_controller_1 = require("@metamask/polling-controller");
|
|
27
42
|
const assetsUtil_1 = require("./assetsUtil");
|
|
28
43
|
const DEFAULT_INTERVAL = 180000;
|
|
44
|
+
/**
|
|
45
|
+
* Finds a case insensitive match in an array of strings
|
|
46
|
+
* @param source - An array of strings to search.
|
|
47
|
+
* @param target - The target string to search for.
|
|
48
|
+
* @returns The first match that is found.
|
|
49
|
+
*/
|
|
50
|
+
function findCaseInsensitiveMatch(source, target) {
|
|
51
|
+
return source.find((e) => e.toLowerCase() === target.toLowerCase());
|
|
52
|
+
}
|
|
53
|
+
exports.STATIC_MAINNET_TOKEN_LIST = Object.entries(contract_metadata_1.default).reduce((acc, [base, contract]) => {
|
|
54
|
+
const { logo } = contract, tokenMetadata = __rest(contract, ["logo"]);
|
|
55
|
+
return Object.assign(Object.assign({}, acc), { [base.toLowerCase()]: Object.assign(Object.assign({}, tokenMetadata), { address: base.toLowerCase(), iconUrl: `images/contract/${logo}`, aggregators: [] }) });
|
|
56
|
+
}, {});
|
|
29
57
|
exports.controllerName = 'TokenDetectionController';
|
|
30
58
|
/**
|
|
31
59
|
* Controller that passively polls on a set interval for Tokens auto detection
|
|
@@ -34,6 +62,7 @@ exports.controllerName = 'TokenDetectionController';
|
|
|
34
62
|
* @property selectedAddress - Vault selected address
|
|
35
63
|
* @property networkClientId - The network client ID of the current selected network
|
|
36
64
|
* @property disabled - Boolean to track if network requests are blocked
|
|
65
|
+
* @property isUnlocked - Boolean to track if the keyring state is unlocked
|
|
37
66
|
* @property isDetectionEnabledFromPreferences - Boolean to track if detection is enabled from PreferencesController
|
|
38
67
|
* @property isDetectionEnabledForNetwork - Boolean to track if detected is enabled for current network
|
|
39
68
|
*/
|
|
@@ -47,14 +76,12 @@ class TokenDetectionController extends polling_controller_1.StaticIntervalPollin
|
|
|
47
76
|
* @param options.interval - Polling interval used to fetch new token rates
|
|
48
77
|
* @param options.networkClientId - The selected network client ID of the current network
|
|
49
78
|
* @param options.selectedAddress - Vault selected address
|
|
50
|
-
* @param options.onPreferencesStateChange - Allows subscribing to preferences controller state changes.
|
|
51
79
|
* @param options.addDetectedTokens - Add a list of detected tokens.
|
|
52
80
|
* @param options.getBalancesInSingleCall - Gets the balances of a list of tokens for the given address.
|
|
53
81
|
* @param options.getTokensState - Gets the current state of the Tokens controller.
|
|
54
|
-
* @param options.
|
|
82
|
+
* @param options.trackMetaMetricsEvent - Sets options for MetaMetrics event tracking.
|
|
55
83
|
*/
|
|
56
|
-
constructor({ networkClientId, selectedAddress = '', interval = DEFAULT_INTERVAL, disabled = true,
|
|
57
|
-
const { useTokenDetection: defaultUseTokenDetection } = getPreferencesState();
|
|
84
|
+
constructor({ networkClientId, selectedAddress = '', interval = DEFAULT_INTERVAL, disabled = true, getBalancesInSingleCall, addDetectedTokens, getTokensState, trackMetaMetricsEvent, messenger, }) {
|
|
58
85
|
super({
|
|
59
86
|
name: exports.controllerName,
|
|
60
87
|
messenger,
|
|
@@ -67,47 +94,28 @@ class TokenDetectionController extends polling_controller_1.StaticIntervalPollin
|
|
|
67
94
|
_TokenDetectionController_selectedAddress.set(this, void 0);
|
|
68
95
|
_TokenDetectionController_networkClientId.set(this, void 0);
|
|
69
96
|
_TokenDetectionController_disabled.set(this, void 0);
|
|
97
|
+
_TokenDetectionController_isUnlocked.set(this, void 0);
|
|
70
98
|
_TokenDetectionController_isDetectionEnabledFromPreferences.set(this, void 0);
|
|
71
99
|
_TokenDetectionController_isDetectionEnabledForNetwork.set(this, void 0);
|
|
72
100
|
_TokenDetectionController_addDetectedTokens.set(this, void 0);
|
|
73
101
|
_TokenDetectionController_getBalancesInSingleCall.set(this, void 0);
|
|
74
102
|
_TokenDetectionController_getTokensState.set(this, void 0);
|
|
103
|
+
_TokenDetectionController_trackMetaMetricsEvent.set(this, void 0);
|
|
75
104
|
__classPrivateFieldSet(this, _TokenDetectionController_disabled, disabled, "f");
|
|
76
105
|
this.setIntervalLength(interval);
|
|
77
106
|
__classPrivateFieldSet(this, _TokenDetectionController_networkClientId, networkClientId, "f");
|
|
78
107
|
__classPrivateFieldSet(this, _TokenDetectionController_selectedAddress, selectedAddress, "f");
|
|
79
108
|
__classPrivateFieldSet(this, _TokenDetectionController_chainId, __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_getCorrectChainId).call(this, networkClientId), "f");
|
|
109
|
+
const { useTokenDetection: defaultUseTokenDetection } = this.messagingSystem.call('PreferencesController:getState');
|
|
80
110
|
__classPrivateFieldSet(this, _TokenDetectionController_isDetectionEnabledFromPreferences, defaultUseTokenDetection, "f");
|
|
81
111
|
__classPrivateFieldSet(this, _TokenDetectionController_isDetectionEnabledForNetwork, (0, assetsUtil_1.isTokenDetectionSupportedForNetwork)(__classPrivateFieldGet(this, _TokenDetectionController_chainId, "f")), "f");
|
|
82
112
|
__classPrivateFieldSet(this, _TokenDetectionController_addDetectedTokens, addDetectedTokens, "f");
|
|
83
113
|
__classPrivateFieldSet(this, _TokenDetectionController_getBalancesInSingleCall, getBalancesInSingleCall, "f");
|
|
84
114
|
__classPrivateFieldSet(this, _TokenDetectionController_getTokensState, getTokensState, "f");
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
}
|
|
90
|
-
}));
|
|
91
|
-
onPreferencesStateChange(({ selectedAddress: newSelectedAddress, useTokenDetection }) => __awaiter(this, void 0, void 0, function* () {
|
|
92
|
-
const isSelectedAddressChanged = __classPrivateFieldGet(this, _TokenDetectionController_selectedAddress, "f") !== newSelectedAddress;
|
|
93
|
-
const isDetectionChangedFromPreferences = __classPrivateFieldGet(this, _TokenDetectionController_isDetectionEnabledFromPreferences, "f") !== useTokenDetection;
|
|
94
|
-
__classPrivateFieldSet(this, _TokenDetectionController_selectedAddress, newSelectedAddress, "f");
|
|
95
|
-
__classPrivateFieldSet(this, _TokenDetectionController_isDetectionEnabledFromPreferences, useTokenDetection, "f");
|
|
96
|
-
if (useTokenDetection &&
|
|
97
|
-
(isSelectedAddressChanged || isDetectionChangedFromPreferences)) {
|
|
98
|
-
yield this.detectTokens();
|
|
99
|
-
}
|
|
100
|
-
}));
|
|
101
|
-
this.messagingSystem.subscribe('NetworkController:networkDidChange', ({ selectedNetworkClientId }) => __awaiter(this, void 0, void 0, function* () {
|
|
102
|
-
__classPrivateFieldSet(this, _TokenDetectionController_networkClientId, selectedNetworkClientId, "f");
|
|
103
|
-
const newChainId = __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_getCorrectChainId).call(this, selectedNetworkClientId);
|
|
104
|
-
const isChainIdChanged = __classPrivateFieldGet(this, _TokenDetectionController_chainId, "f") !== newChainId;
|
|
105
|
-
__classPrivateFieldSet(this, _TokenDetectionController_chainId, newChainId, "f");
|
|
106
|
-
__classPrivateFieldSet(this, _TokenDetectionController_isDetectionEnabledForNetwork, (0, assetsUtil_1.isTokenDetectionSupportedForNetwork)(newChainId), "f");
|
|
107
|
-
if (__classPrivateFieldGet(this, _TokenDetectionController_isDetectionEnabledForNetwork, "f") && isChainIdChanged) {
|
|
108
|
-
yield this.detectTokens();
|
|
109
|
-
}
|
|
110
|
-
}));
|
|
115
|
+
__classPrivateFieldSet(this, _TokenDetectionController_trackMetaMetricsEvent, trackMetaMetricsEvent, "f");
|
|
116
|
+
const { isUnlocked } = this.messagingSystem.call('KeyringController:getState');
|
|
117
|
+
__classPrivateFieldSet(this, _TokenDetectionController_isUnlocked, isUnlocked, "f");
|
|
118
|
+
__classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_registerEventListeners).call(this);
|
|
111
119
|
}
|
|
112
120
|
/**
|
|
113
121
|
* Allows controller to make active and passive polling requests
|
|
@@ -121,6 +129,14 @@ class TokenDetectionController extends polling_controller_1.StaticIntervalPollin
|
|
|
121
129
|
disable() {
|
|
122
130
|
__classPrivateFieldSet(this, _TokenDetectionController_disabled, true, "f");
|
|
123
131
|
}
|
|
132
|
+
/**
|
|
133
|
+
* Internal isActive state
|
|
134
|
+
*
|
|
135
|
+
* @type {object}
|
|
136
|
+
*/
|
|
137
|
+
get isActive() {
|
|
138
|
+
return !__classPrivateFieldGet(this, _TokenDetectionController_disabled, "f") && __classPrivateFieldGet(this, _TokenDetectionController_isUnlocked, "f");
|
|
139
|
+
}
|
|
124
140
|
/**
|
|
125
141
|
* Start polling for detected tokens.
|
|
126
142
|
*/
|
|
@@ -139,7 +155,7 @@ class TokenDetectionController extends polling_controller_1.StaticIntervalPollin
|
|
|
139
155
|
}
|
|
140
156
|
_executePoll(networkClientId, options) {
|
|
141
157
|
return __awaiter(this, void 0, void 0, function* () {
|
|
142
|
-
if (
|
|
158
|
+
if (!this.isActive) {
|
|
143
159
|
return;
|
|
144
160
|
}
|
|
145
161
|
yield this.detectTokens({
|
|
@@ -149,29 +165,35 @@ class TokenDetectionController extends polling_controller_1.StaticIntervalPollin
|
|
|
149
165
|
});
|
|
150
166
|
}
|
|
151
167
|
/**
|
|
152
|
-
*
|
|
168
|
+
* For each token in the token list provided by the TokenListController, checks the token's balance for the selected account address on the active network.
|
|
169
|
+
* On mainnet, if token detection is disabled in preferences, ERC20 token auto detection will be triggered for each contract address in the legacy token list from the @metamask/contract-metadata repo.
|
|
153
170
|
*
|
|
154
|
-
* @param options - Options
|
|
171
|
+
* @param options - Options for token detection.
|
|
155
172
|
* @param options.networkClientId - The ID of the network client to use.
|
|
156
|
-
* @param options.accountAddress -
|
|
173
|
+
* @param options.accountAddress - the selectedAddress against which to detect for token balances.
|
|
157
174
|
*/
|
|
158
175
|
detectTokens({ networkClientId, accountAddress, } = {}) {
|
|
159
176
|
return __awaiter(this, void 0, void 0, function* () {
|
|
160
|
-
if (__classPrivateFieldGet(this,
|
|
161
|
-
!__classPrivateFieldGet(this, _TokenDetectionController_isDetectionEnabledForNetwork, "f") ||
|
|
162
|
-
!__classPrivateFieldGet(this, _TokenDetectionController_isDetectionEnabledFromPreferences, "f")) {
|
|
177
|
+
if (!this.isActive || !__classPrivateFieldGet(this, _TokenDetectionController_isDetectionEnabledForNetwork, "f")) {
|
|
163
178
|
return;
|
|
164
179
|
}
|
|
165
|
-
const
|
|
166
|
-
const selectedAddress = accountAddress || __classPrivateFieldGet(this, _TokenDetectionController_selectedAddress, "f");
|
|
180
|
+
const selectedAddress = accountAddress !== null && accountAddress !== void 0 ? accountAddress : __classPrivateFieldGet(this, _TokenDetectionController_selectedAddress, "f");
|
|
167
181
|
const chainId = __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_getCorrectChainId).call(this, networkClientId);
|
|
168
|
-
|
|
169
|
-
|
|
182
|
+
if (!__classPrivateFieldGet(this, _TokenDetectionController_isDetectionEnabledFromPreferences, "f") &&
|
|
183
|
+
chainId !== controller_utils_1.ChainId.mainnet) {
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
const isTokenDetectionInactiveInMainnet = !__classPrivateFieldGet(this, _TokenDetectionController_isDetectionEnabledFromPreferences, "f") && chainId === controller_utils_1.ChainId.mainnet;
|
|
170
187
|
const { tokenList } = this.messagingSystem.call('TokenListController:getState');
|
|
188
|
+
const tokenListUsed = isTokenDetectionInactiveInMainnet
|
|
189
|
+
? exports.STATIC_MAINNET_TOKEN_LIST
|
|
190
|
+
: tokenList;
|
|
191
|
+
const { tokens, detectedTokens } = __classPrivateFieldGet(this, _TokenDetectionController_getTokensState, "f").call(this);
|
|
171
192
|
const tokensToDetect = [];
|
|
172
|
-
for (const
|
|
173
|
-
if (!
|
|
174
|
-
|
|
193
|
+
for (const tokenAddress of Object.keys(tokenListUsed)) {
|
|
194
|
+
if (!findCaseInsensitiveMatch(tokens.map(({ address }) => address), tokenAddress) &&
|
|
195
|
+
!findCaseInsensitiveMatch(detectedTokens.map(({ address }) => address), tokenAddress)) {
|
|
196
|
+
tokensToDetect.push(tokenAddress);
|
|
175
197
|
}
|
|
176
198
|
}
|
|
177
199
|
const sliceOfTokensToDetect = [];
|
|
@@ -189,6 +211,7 @@ class TokenDetectionController extends polling_controller_1.StaticIntervalPollin
|
|
|
189
211
|
var _a;
|
|
190
212
|
const balances = yield __classPrivateFieldGet(this, _TokenDetectionController_getBalancesInSingleCall, "f").call(this, selectedAddress, tokensSlice);
|
|
191
213
|
const tokensToAdd = [];
|
|
214
|
+
const eventTokensDetails = [];
|
|
192
215
|
for (const tokenAddress of Object.keys(balances)) {
|
|
193
216
|
let ignored;
|
|
194
217
|
/* istanbul ignore else */
|
|
@@ -196,9 +219,10 @@ class TokenDetectionController extends polling_controller_1.StaticIntervalPollin
|
|
|
196
219
|
if (ignoredTokens.length) {
|
|
197
220
|
ignored = ignoredTokens.find((ignoredTokenAddress) => ignoredTokenAddress === (0, controller_utils_1.toChecksumHexAddress)(tokenAddress));
|
|
198
221
|
}
|
|
199
|
-
const caseInsensitiveTokenKey = (_a = Object.keys(
|
|
222
|
+
const caseInsensitiveTokenKey = (_a = findCaseInsensitiveMatch(Object.keys(tokenListUsed), tokenAddress)) !== null && _a !== void 0 ? _a : '';
|
|
200
223
|
if (ignored === undefined) {
|
|
201
224
|
const { decimals, symbol, aggregators, iconUrl, name } = tokenList[caseInsensitiveTokenKey];
|
|
225
|
+
eventTokensDetails.push(`${symbol} - ${tokenAddress}`);
|
|
202
226
|
tokensToAdd.push({
|
|
203
227
|
address: tokenAddress,
|
|
204
228
|
decimals,
|
|
@@ -211,6 +235,15 @@ class TokenDetectionController extends polling_controller_1.StaticIntervalPollin
|
|
|
211
235
|
}
|
|
212
236
|
}
|
|
213
237
|
if (tokensToAdd.length) {
|
|
238
|
+
__classPrivateFieldGet(this, _TokenDetectionController_trackMetaMetricsEvent, "f").call(this, {
|
|
239
|
+
event: 'Token Detected',
|
|
240
|
+
category: 'Wallet',
|
|
241
|
+
properties: {
|
|
242
|
+
tokens: eventTokensDetails,
|
|
243
|
+
token_standard: 'ERC20',
|
|
244
|
+
asset_type: 'TOKEN',
|
|
245
|
+
},
|
|
246
|
+
});
|
|
214
247
|
yield __classPrivateFieldGet(this, _TokenDetectionController_addDetectedTokens, "f").call(this, tokensToAdd, {
|
|
215
248
|
selectedAddress,
|
|
216
249
|
chainId,
|
|
@@ -222,13 +255,61 @@ class TokenDetectionController extends polling_controller_1.StaticIntervalPollin
|
|
|
222
255
|
}
|
|
223
256
|
}
|
|
224
257
|
exports.TokenDetectionController = TokenDetectionController;
|
|
225
|
-
_TokenDetectionController_intervalId = new WeakMap(), _TokenDetectionController_chainId = new WeakMap(), _TokenDetectionController_selectedAddress = new WeakMap(), _TokenDetectionController_networkClientId = new WeakMap(), _TokenDetectionController_disabled = new WeakMap(), _TokenDetectionController_isDetectionEnabledFromPreferences = new WeakMap(), _TokenDetectionController_isDetectionEnabledForNetwork = new WeakMap(), _TokenDetectionController_addDetectedTokens = new WeakMap(), _TokenDetectionController_getBalancesInSingleCall = new WeakMap(), _TokenDetectionController_getTokensState = new WeakMap(), _TokenDetectionController_instances = new WeakSet(),
|
|
258
|
+
_TokenDetectionController_intervalId = new WeakMap(), _TokenDetectionController_chainId = new WeakMap(), _TokenDetectionController_selectedAddress = new WeakMap(), _TokenDetectionController_networkClientId = new WeakMap(), _TokenDetectionController_disabled = new WeakMap(), _TokenDetectionController_isUnlocked = new WeakMap(), _TokenDetectionController_isDetectionEnabledFromPreferences = new WeakMap(), _TokenDetectionController_isDetectionEnabledForNetwork = new WeakMap(), _TokenDetectionController_addDetectedTokens = new WeakMap(), _TokenDetectionController_getBalancesInSingleCall = new WeakMap(), _TokenDetectionController_getTokensState = new WeakMap(), _TokenDetectionController_trackMetaMetricsEvent = new WeakMap(), _TokenDetectionController_instances = new WeakSet(), _TokenDetectionController_registerEventListeners = function _TokenDetectionController_registerEventListeners() {
|
|
259
|
+
this.messagingSystem.subscribe('KeyringController:unlock', () => __awaiter(this, void 0, void 0, function* () {
|
|
260
|
+
__classPrivateFieldSet(this, _TokenDetectionController_isUnlocked, true, "f");
|
|
261
|
+
yield __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_restartTokenDetection).call(this);
|
|
262
|
+
}));
|
|
263
|
+
this.messagingSystem.subscribe('KeyringController:lock', () => {
|
|
264
|
+
__classPrivateFieldSet(this, _TokenDetectionController_isUnlocked, false, "f");
|
|
265
|
+
__classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_stopPolling).call(this);
|
|
266
|
+
});
|
|
267
|
+
this.messagingSystem.subscribe('TokenListController:stateChange', ({ tokenList }) => __awaiter(this, void 0, void 0, function* () {
|
|
268
|
+
const hasTokens = Object.keys(tokenList).length;
|
|
269
|
+
if (hasTokens) {
|
|
270
|
+
yield __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_restartTokenDetection).call(this);
|
|
271
|
+
}
|
|
272
|
+
}));
|
|
273
|
+
this.messagingSystem.subscribe('PreferencesController:stateChange', ({ selectedAddress: newSelectedAddress, useTokenDetection }) => __awaiter(this, void 0, void 0, function* () {
|
|
274
|
+
const isSelectedAddressChanged = __classPrivateFieldGet(this, _TokenDetectionController_selectedAddress, "f") !== newSelectedAddress;
|
|
275
|
+
const isDetectionChangedFromPreferences = __classPrivateFieldGet(this, _TokenDetectionController_isDetectionEnabledFromPreferences, "f") !== useTokenDetection;
|
|
276
|
+
__classPrivateFieldSet(this, _TokenDetectionController_selectedAddress, newSelectedAddress, "f");
|
|
277
|
+
__classPrivateFieldSet(this, _TokenDetectionController_isDetectionEnabledFromPreferences, useTokenDetection, "f");
|
|
278
|
+
if (useTokenDetection &&
|
|
279
|
+
(isSelectedAddressChanged || isDetectionChangedFromPreferences)) {
|
|
280
|
+
yield __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_restartTokenDetection).call(this, {
|
|
281
|
+
selectedAddress: __classPrivateFieldGet(this, _TokenDetectionController_selectedAddress, "f"),
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
}));
|
|
285
|
+
this.messagingSystem.subscribe('AccountsController:selectedAccountChange', ({ address: newSelectedAddress }) => __awaiter(this, void 0, void 0, function* () {
|
|
286
|
+
const isSelectedAddressChanged = __classPrivateFieldGet(this, _TokenDetectionController_selectedAddress, "f") !== newSelectedAddress;
|
|
287
|
+
if (isSelectedAddressChanged &&
|
|
288
|
+
__classPrivateFieldGet(this, _TokenDetectionController_isDetectionEnabledFromPreferences, "f")) {
|
|
289
|
+
__classPrivateFieldSet(this, _TokenDetectionController_selectedAddress, newSelectedAddress, "f");
|
|
290
|
+
yield __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_restartTokenDetection).call(this, {
|
|
291
|
+
selectedAddress: __classPrivateFieldGet(this, _TokenDetectionController_selectedAddress, "f"),
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
}));
|
|
295
|
+
this.messagingSystem.subscribe('NetworkController:networkDidChange', ({ selectedNetworkClientId }) => __awaiter(this, void 0, void 0, function* () {
|
|
296
|
+
const isNetworkClientIdChanged = __classPrivateFieldGet(this, _TokenDetectionController_networkClientId, "f") !== selectedNetworkClientId;
|
|
297
|
+
const newChainId = __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_getCorrectChainId).call(this, selectedNetworkClientId);
|
|
298
|
+
__classPrivateFieldSet(this, _TokenDetectionController_isDetectionEnabledForNetwork, (0, assetsUtil_1.isTokenDetectionSupportedForNetwork)(newChainId), "f");
|
|
299
|
+
if (isNetworkClientIdChanged && __classPrivateFieldGet(this, _TokenDetectionController_isDetectionEnabledForNetwork, "f")) {
|
|
300
|
+
__classPrivateFieldSet(this, _TokenDetectionController_networkClientId, selectedNetworkClientId, "f");
|
|
301
|
+
yield __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_restartTokenDetection).call(this, {
|
|
302
|
+
networkClientId: __classPrivateFieldGet(this, _TokenDetectionController_networkClientId, "f"),
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
}));
|
|
306
|
+
}, _TokenDetectionController_stopPolling = function _TokenDetectionController_stopPolling() {
|
|
226
307
|
if (__classPrivateFieldGet(this, _TokenDetectionController_intervalId, "f")) {
|
|
227
308
|
clearInterval(__classPrivateFieldGet(this, _TokenDetectionController_intervalId, "f"));
|
|
228
309
|
}
|
|
229
310
|
}, _TokenDetectionController_startPolling = function _TokenDetectionController_startPolling() {
|
|
230
311
|
return __awaiter(this, void 0, void 0, function* () {
|
|
231
|
-
if (
|
|
312
|
+
if (!this.isActive) {
|
|
232
313
|
return;
|
|
233
314
|
}
|
|
234
315
|
__classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_stopPolling).call(this);
|
|
@@ -241,6 +322,14 @@ _TokenDetectionController_intervalId = new WeakMap(), _TokenDetectionController_
|
|
|
241
322
|
var _a;
|
|
242
323
|
const { chainId } = (_a = this.messagingSystem.call('NetworkController:getNetworkConfigurationByNetworkClientId', networkClientId !== null && networkClientId !== void 0 ? networkClientId : __classPrivateFieldGet(this, _TokenDetectionController_networkClientId, "f"))) !== null && _a !== void 0 ? _a : {};
|
|
243
324
|
return chainId !== null && chainId !== void 0 ? chainId : __classPrivateFieldGet(this, _TokenDetectionController_chainId, "f");
|
|
325
|
+
}, _TokenDetectionController_restartTokenDetection = function _TokenDetectionController_restartTokenDetection({ selectedAddress, networkClientId, } = {}) {
|
|
326
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
327
|
+
yield this.detectTokens({
|
|
328
|
+
networkClientId,
|
|
329
|
+
accountAddress: selectedAddress,
|
|
330
|
+
});
|
|
331
|
+
this.setIntervalLength(DEFAULT_INTERVAL);
|
|
332
|
+
});
|
|
244
333
|
};
|
|
245
334
|
exports.default = TokenDetectionController;
|
|
246
335
|
//# sourceMappingURL=TokenDetectionController.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TokenDetectionController.js","sourceRoot":"","sources":["../src/TokenDetectionController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAKA,iEAGoC;AAOpC,qEAA+E;AAK/E,6CAAmE;AAQnE,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEnB,QAAA,cAAc,GAAG,0BAA0B,CAAC;AAmCzD;;;;;;;;;GASG;AACH,MAAa,wBAAyB,SAAQ,oDAI7C;IAqBC;;;;;;;;;;;;;;OAcG;IACH,YAAY,EACV,eAAe,EACf,eAAe,GAAG,EAAE,EACpB,QAAQ,GAAG,gBAAgB,EAC3B,QAAQ,GAAG,IAAI,EACf,wBAAwB,EACxB,uBAAuB,EACvB,iBAAiB,EACjB,mBAAmB,EACnB,cAAc,EACd,SAAS,GAcV;QACC,MAAM,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,GACnD,mBAAmB,EAAE,CAAC;QAExB,KAAK,CAAC;YACJ,IAAI,EAAE,sBAAc;YACpB,SAAS;YACT,KAAK,EAAE,EAAE;YACT,QAAQ,EAAE,EAAE;SACb,CAAC,CAAC;;QApEL,uDAA4C;QAE5C,oDAAc;QAEd,4DAAyB;QAEzB,4DAAkC;QAElC,qDAAmB;QAEnB,8EAA4C;QAE5C,yEAAuC;QAEvC,8DAAmE;QAEnE,oEAAuF;QAEvF,2DAA4C;QAoD1C,uBAAA,IAAI,sCAAa,QAAQ,MAAA,CAAC;QAC1B,IAAI,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CAAC;QAEjC,uBAAA,IAAI,6CAAoB,eAAe,MAAA,CAAC;QACxC,uBAAA,IAAI,6CAAoB,eAAe,MAAA,CAAC;QACxC,uBAAA,IAAI,qCAAY,uBAAA,IAAI,wFAAmB,MAAvB,IAAI,EAAoB,eAAe,CAAC,MAAA,CAAC;QAEzD,uBAAA,IAAI,+DAAsC,wBAAwB,MAAA,CAAC;QACnE,uB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I,uBAAA,IAAI,0CAAU,EAAE;YAClB,OAAO;SACR;QACD,uBAAA,IAAI,kFAAa,MAAjB,IAAI,CAAe,CAAC;QACpB,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;QAC1B,uBAAA,IAAI,wCAAe,WAAW,CAAC,GAAS,EAAE;YACxC,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;QAC5B,CAAC,CAAA,EAAE,IAAI,CAAC,iBAAiB,EAAE,CAAC,MAAA,CAAC;IAC/B,CAAC;sGAEkB,eAAiC;;IAClD,MAAM,EAAE,OAAO,EAAE,GACf,MAAA,IAAI,CAAC,eAAe,CAAC,IAAI,CACvB,4DAA4D,EAC5D,eAAe,aAAf,eAAe,cAAf,eAAe,GAAI,uBAAA,IAAI,iDAAiB,CACzC,mCAAI,EAAE,CAAC;IACV,OAAO,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,uBAAA,IAAI,yCAAS,CAAC;AAClC,CAAC;AAoHH,kBAAe,wBAAwB,CAAC","sourcesContent":["import type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport {\n safelyExecute,\n toChecksumHexAddress,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkControllerNetworkDidChangeEvent,\n NetworkControllerStateChangeEvent,\n NetworkControllerGetNetworkConfigurationByNetworkClientId,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { PreferencesState } from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport type { AssetsContractController } from './AssetsContractController';\nimport { isTokenDetectionSupportedForNetwork } from './assetsUtil';\nimport type {\n GetTokenListState,\n TokenListStateChange,\n} from './TokenListController';\nimport type { Token } from './TokenRatesController';\nimport type { TokensController, TokensState } from './TokensController';\n\nconst DEFAULT_INTERVAL = 180000;\n\nexport const controllerName = 'TokenDetectionController';\n\nexport type TokenDetectionState = Record<never, never>;\n\nexport type TokenDetectionControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenDetectionState\n>;\n\nexport type TokenDetectionControllerActions =\n TokenDetectionControllerGetStateAction;\n\nexport type AllowedActions =\n | NetworkControllerGetNetworkConfigurationByNetworkClientId\n | GetTokenListState;\n\nexport type TokenDetectionControllerStateChangeEvent =\n ControllerStateChangeEvent<typeof controllerName, TokenDetectionState>;\n\nexport type TokenDetectionControllerEvents =\n TokenDetectionControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | NetworkControllerStateChangeEvent\n | NetworkControllerNetworkDidChangeEvent\n | TokenListStateChange;\n\nexport type TokenDetectionControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n TokenDetectionControllerActions | AllowedActions,\n TokenDetectionControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Controller that passively polls on a set interval for Tokens auto detection\n * @property intervalId - Polling interval used to fetch new token rates\n * @property chainId - The chain ID of the current network\n * @property selectedAddress - Vault selected address\n * @property networkClientId - The network client ID of the current selected network\n * @property disabled - Boolean to track if network requests are blocked\n * @property isDetectionEnabledFromPreferences - Boolean to track if detection is enabled from PreferencesController\n * @property isDetectionEnabledForNetwork - Boolean to track if detected is enabled for current network\n */\nexport class TokenDetectionController extends StaticIntervalPollingController<\n typeof controllerName,\n TokenDetectionState,\n TokenDetectionControllerMessenger\n> {\n #intervalId?: ReturnType<typeof setTimeout>;\n\n #chainId: Hex;\n\n #selectedAddress: string;\n\n #networkClientId: NetworkClientId;\n\n #disabled: boolean;\n\n #isDetectionEnabledFromPreferences: boolean;\n\n #isDetectionEnabledForNetwork: boolean;\n\n readonly #addDetectedTokens: TokensController['addDetectedTokens'];\n\n readonly #getBalancesInSingleCall: AssetsContractController['getBalancesInSingleCall'];\n\n readonly #getTokensState: () => TokensState;\n\n /**\n * Creates a TokenDetectionController instance.\n *\n * @param options - The controller options.\n * @param options.messenger - The controller messaging system.\n * @param options.disabled - If set to true, all network requests are blocked.\n * @param options.interval - Polling interval used to fetch new token rates\n * @param options.networkClientId - The selected network client ID of the current network\n * @param options.selectedAddress - Vault selected address\n * @param options.onPreferencesStateChange - Allows subscribing to preferences controller state changes.\n * @param options.addDetectedTokens - Add a list of detected tokens.\n * @param options.getBalancesInSingleCall - Gets the balances of a list of tokens for the given address.\n * @param options.getTokensState - Gets the current state of the Tokens controller.\n * @param options.getPreferencesState - Gets the state of the preferences controller.\n */\n constructor({\n networkClientId,\n selectedAddress = '',\n interval = DEFAULT_INTERVAL,\n disabled = true,\n onPreferencesStateChange,\n getBalancesInSingleCall,\n addDetectedTokens,\n getPreferencesState,\n getTokensState,\n messenger,\n }: {\n networkClientId: NetworkClientId;\n selectedAddress?: string;\n interval?: number;\n disabled?: boolean;\n onPreferencesStateChange: (\n listener: (preferencesState: PreferencesState) => void,\n ) => void;\n addDetectedTokens: TokensController['addDetectedTokens'];\n getBalancesInSingleCall: AssetsContractController['getBalancesInSingleCall'];\n getTokensState: () => TokensState;\n getPreferencesState: () => PreferencesState;\n messenger: TokenDetectionControllerMessenger;\n }) {\n const { useTokenDetection: defaultUseTokenDetection } =\n getPreferencesState();\n\n super({\n name: controllerName,\n messenger,\n state: {},\n metadata: {},\n });\n\n this.#disabled = disabled;\n this.setIntervalLength(interval);\n\n this.#networkClientId = networkClientId;\n this.#selectedAddress = selectedAddress;\n this.#chainId = this.#getCorrectChainId(networkClientId);\n\n this.#isDetectionEnabledFromPreferences = defaultUseTokenDetection;\n this.#isDetectionEnabledForNetwork = isTokenDetectionSupportedForNetwork(\n this.#chainId,\n );\n\n this.#addDetectedTokens = addDetectedTokens;\n this.#getBalancesInSingleCall = getBalancesInSingleCall;\n this.#getTokensState = getTokensState;\n\n this.messagingSystem.subscribe(\n 'TokenListController:stateChange',\n async ({ tokenList }) => {\n const hasTokens = Object.keys(tokenList).length;\n\n if (hasTokens) {\n await this.detectTokens();\n }\n },\n );\n\n onPreferencesStateChange(\n async ({ selectedAddress: newSelectedAddress, useTokenDetection }) => {\n const isSelectedAddressChanged =\n this.#selectedAddress !== newSelectedAddress;\n const isDetectionChangedFromPreferences =\n this.#isDetectionEnabledFromPreferences !== useTokenDetection;\n\n this.#selectedAddress = newSelectedAddress;\n this.#isDetectionEnabledFromPreferences = useTokenDetection;\n\n if (\n useTokenDetection &&\n (isSelectedAddressChanged || isDetectionChangedFromPreferences)\n ) {\n await this.detectTokens();\n }\n },\n );\n\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n async ({ selectedNetworkClientId }) => {\n this.#networkClientId = selectedNetworkClientId;\n const newChainId = this.#getCorrectChainId(selectedNetworkClientId);\n const isChainIdChanged = this.#chainId !== newChainId;\n this.#chainId = newChainId;\n\n this.#isDetectionEnabledForNetwork =\n isTokenDetectionSupportedForNetwork(newChainId);\n\n if (this.#isDetectionEnabledForNetwork && isChainIdChanged) {\n await this.detectTokens();\n }\n },\n );\n }\n\n /**\n * Allows controller to make active and passive polling requests\n */\n enable() {\n this.#disabled = false;\n }\n\n /**\n * Blocks controller from making network calls\n */\n disable() {\n this.#disabled = true;\n }\n\n /**\n * Start polling for detected tokens.\n */\n async start() {\n this.enable();\n await this.#startPolling();\n }\n\n /**\n * Stop polling for detected tokens.\n */\n stop() {\n this.disable();\n this.#stopPolling();\n }\n\n #stopPolling() {\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n }\n\n /**\n * Starts a new polling interval.\n */\n async #startPolling(): Promise<void> {\n if (this.#disabled) {\n return;\n }\n this.#stopPolling();\n await this.detectTokens();\n this.#intervalId = setInterval(async () => {\n await this.detectTokens();\n }, this.getIntervalLength());\n }\n\n #getCorrectChainId(networkClientId?: NetworkClientId) {\n const { chainId } =\n this.messagingSystem.call(\n 'NetworkController:getNetworkConfigurationByNetworkClientId',\n networkClientId ?? this.#networkClientId,\n ) ?? {};\n return chainId ?? this.#chainId;\n }\n\n async _executePoll(\n networkClientId: string,\n options: { address: string },\n ): Promise<void> {\n if (this.#disabled) {\n return;\n }\n await this.detectTokens({\n networkClientId,\n accountAddress: options.address,\n });\n }\n\n /**\n * Triggers asset ERC20 token auto detection for each contract address in contract metadata on mainnet.\n *\n * @param options - Options to detect tokens.\n * @param options.networkClientId - The ID of the network client to use.\n * @param options.accountAddress - The account address to use.\n */\n async detectTokens({\n networkClientId,\n accountAddress,\n }: {\n networkClientId?: NetworkClientId;\n accountAddress?: string;\n } = {}): Promise<void> {\n if (\n this.#disabled ||\n !this.#isDetectionEnabledForNetwork ||\n !this.#isDetectionEnabledFromPreferences\n ) {\n return;\n }\n const { tokens } = this.#getTokensState();\n const selectedAddress = accountAddress || this.#selectedAddress;\n const chainId = this.#getCorrectChainId(networkClientId);\n\n const tokensAddresses = tokens.map(\n /* istanbul ignore next*/ (token) => token.address.toLowerCase(),\n );\n const { tokenList } = this.messagingSystem.call(\n 'TokenListController:getState',\n );\n const tokensToDetect: string[] = [];\n for (const address of Object.keys(tokenList)) {\n if (!tokensAddresses.includes(address)) {\n tokensToDetect.push(address);\n }\n }\n const sliceOfTokensToDetect = [];\n sliceOfTokensToDetect[0] = tokensToDetect.slice(0, 1000);\n sliceOfTokensToDetect[1] = tokensToDetect.slice(\n 1000,\n tokensToDetect.length - 1,\n );\n\n /* istanbul ignore else */\n if (!selectedAddress) {\n return;\n }\n\n for (const tokensSlice of sliceOfTokensToDetect) {\n if (tokensSlice.length === 0) {\n break;\n }\n\n await safelyExecute(async () => {\n const balances = await this.#getBalancesInSingleCall(\n selectedAddress,\n tokensSlice,\n );\n const tokensToAdd: Token[] = [];\n for (const tokenAddress of Object.keys(balances)) {\n let ignored;\n /* istanbul ignore else */\n const { ignoredTokens } = this.#getTokensState();\n if (ignoredTokens.length) {\n ignored = ignoredTokens.find(\n (ignoredTokenAddress) =>\n ignoredTokenAddress === toChecksumHexAddress(tokenAddress),\n );\n }\n const caseInsensitiveTokenKey =\n Object.keys(tokenList).find(\n (i) => i.toLowerCase() === tokenAddress.toLowerCase(),\n ) ?? '';\n\n if (ignored === undefined) {\n const { decimals, symbol, aggregators, iconUrl, name } =\n tokenList[caseInsensitiveTokenKey];\n tokensToAdd.push({\n address: tokenAddress,\n decimals,\n symbol,\n aggregators,\n image: iconUrl,\n isERC721: false,\n name,\n });\n }\n }\n\n if (tokensToAdd.length) {\n await this.#addDetectedTokens(tokensToAdd, {\n selectedAddress,\n chainId,\n });\n }\n });\n }\n }\n}\n\nexport default TokenDetectionController;\n"]}
|
|
1
|
+
{"version":3,"file":"TokenDetectionController.js","sourceRoot":"","sources":["../src/TokenDetectionController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,oFAAsD;AACtD,iEAIoC;AAWpC,qEAA+E;AAQ/E,6CAAmE;AASnE,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC;;;;;GAKG;AACH,SAAS,wBAAwB,CAAC,MAAgB,EAAE,MAAc;IAChE,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC;AAC9E,CAAC;AAYY,QAAA,yBAAyB,GAAG,MAAM,CAAC,OAAO,CACrD,2BAAW,CACZ,CAAC,MAAM,CAA0C,CAAC,GAAG,EAAE,CAAC,IAAI,EAAE,QAAQ,CAAC,EAAE,EAAE;IAC1E,MAAM,EAAE,IAAI,KAAuB,QAAQ,EAA1B,aAAa,UAAK,QAAQ,EAArC,QAA0B,CAAW,CAAC;IAC5C,uCACK,GAAG,KACN,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,kCACf,aAAa,KAChB,OAAO,EAAE,IAAI,CAAC,WAAW,EAAE,EAC3B,OAAO,EAAE,mBAAmB,IAAI,EAAE,EAClC,WAAW,EAAE,EAAE,OAEjB;AACJ,CAAC,EAAE,EAAE,CAAC,CAAC;AAEM,QAAA,cAAc,GAAG,0BAA0B,CAAC;AAwCzD;;;;;;;;;;GAUG;AACH,MAAa,wBAA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iBAAiB,CAAC,gBAAgB,CAAC,CAAC;IAC3C,CAAC;;AAmIH,kBAAe,wBAAwB,CAAC","sourcesContent":["import type { AccountsControllerSelectedAccountChangeEvent } from '@metamask/accounts-controller';\nimport type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport contractMap from '@metamask/contract-metadata';\nimport {\n ChainId,\n safelyExecute,\n toChecksumHexAddress,\n} from '@metamask/controller-utils';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type {\n NetworkClientId,\n NetworkControllerNetworkDidChangeEvent,\n NetworkControllerGetNetworkConfigurationByNetworkClientId,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n} from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport type { AssetsContractController } from './AssetsContractController';\nimport { isTokenDetectionSupportedForNetwork } from './assetsUtil';\nimport type {\n GetTokenListState,\n TokenListStateChange,\n TokenListToken,\n} from './TokenListController';\nimport type { Token } from './TokenRatesController';\nimport type { TokensController, TokensState } from './TokensController';\n\nconst DEFAULT_INTERVAL = 180000;\n\n/**\n * Finds a case insensitive match in an array of strings\n * @param source - An array of strings to search.\n * @param target - The target string to search for.\n * @returns The first match that is found.\n */\nfunction findCaseInsensitiveMatch(source: string[], target: string) {\n return source.find((e: string) => e.toLowerCase() === target.toLowerCase());\n}\n\ntype LegacyToken = Omit<\n Token,\n 'aggregators' | 'image' | 'balanceError' | 'isERC721'\n> & {\n name: string;\n logo: string;\n erc20?: boolean;\n erc721?: boolean;\n};\n\nexport const STATIC_MAINNET_TOKEN_LIST = Object.entries<LegacyToken>(\n contractMap,\n).reduce<Record<string, Partial<TokenListToken>>>((acc, [base, contract]) => {\n const { logo, ...tokenMetadata } = contract;\n return {\n ...acc,\n [base.toLowerCase()]: {\n ...tokenMetadata,\n address: base.toLowerCase(),\n iconUrl: `images/contract/${logo}`,\n aggregators: [],\n },\n };\n}, {});\n\nexport const controllerName = 'TokenDetectionController';\n\nexport type TokenDetectionState = Record<never, never>;\n\nexport type TokenDetectionControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenDetectionState\n>;\n\nexport type TokenDetectionControllerActions =\n TokenDetectionControllerGetStateAction;\n\nexport type AllowedActions =\n | NetworkControllerGetNetworkConfigurationByNetworkClientId\n | GetTokenListState\n | KeyringControllerGetStateAction\n | PreferencesControllerGetStateAction;\n\nexport type TokenDetectionControllerStateChangeEvent =\n ControllerStateChangeEvent<typeof controllerName, TokenDetectionState>;\n\nexport type TokenDetectionControllerEvents =\n TokenDetectionControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | AccountsControllerSelectedAccountChangeEvent\n | NetworkControllerNetworkDidChangeEvent\n | TokenListStateChange\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n | PreferencesControllerStateChangeEvent;\n\nexport type TokenDetectionControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n TokenDetectionControllerActions | AllowedActions,\n TokenDetectionControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Controller that passively polls on a set interval for Tokens auto detection\n * @property intervalId - Polling interval used to fetch new token rates\n * @property chainId - The chain ID of the current network\n * @property selectedAddress - Vault selected address\n * @property networkClientId - The network client ID of the current selected network\n * @property disabled - Boolean to track if network requests are blocked\n * @property isUnlocked - Boolean to track if the keyring state is unlocked\n * @property isDetectionEnabledFromPreferences - Boolean to track if detection is enabled from PreferencesController\n * @property isDetectionEnabledForNetwork - Boolean to track if detected is enabled for current network\n */\nexport class TokenDetectionController extends StaticIntervalPollingController<\n typeof controllerName,\n TokenDetectionState,\n TokenDetectionControllerMessenger\n> {\n #intervalId?: ReturnType<typeof setTimeout>;\n\n #chainId: Hex;\n\n #selectedAddress: string;\n\n #networkClientId: NetworkClientId;\n\n #disabled: boolean;\n\n #isUnlocked: boolean;\n\n #isDetectionEnabledFromPreferences: boolean;\n\n #isDetectionEnabledForNetwork: boolean;\n\n readonly #addDetectedTokens: TokensController['addDetectedTokens'];\n\n readonly #getBalancesInSingleCall: AssetsContractController['getBalancesInSingleCall'];\n\n readonly #getTokensState: () => TokensState;\n\n readonly #trackMetaMetricsEvent: (options: {\n event: string;\n category: string;\n properties: {\n tokens: string[];\n token_standard: string;\n asset_type: string;\n };\n }) => void;\n\n /**\n * Creates a TokenDetectionController instance.\n *\n * @param options - The controller options.\n * @param options.messenger - The controller messaging system.\n * @param options.disabled - If set to true, all network requests are blocked.\n * @param options.interval - Polling interval used to fetch new token rates\n * @param options.networkClientId - The selected network client ID of the current network\n * @param options.selectedAddress - Vault selected address\n * @param options.addDetectedTokens - Add a list of detected tokens.\n * @param options.getBalancesInSingleCall - Gets the balances of a list of tokens for the given address.\n * @param options.getTokensState - Gets the current state of the Tokens controller.\n * @param options.trackMetaMetricsEvent - Sets options for MetaMetrics event tracking.\n */\n constructor({\n networkClientId,\n selectedAddress = '',\n interval = DEFAULT_INTERVAL,\n disabled = true,\n getBalancesInSingleCall,\n addDetectedTokens,\n getTokensState,\n trackMetaMetricsEvent,\n messenger,\n }: {\n networkClientId: NetworkClientId;\n selectedAddress?: string;\n interval?: number;\n disabled?: boolean;\n addDetectedTokens: TokensController['addDetectedTokens'];\n getBalancesInSingleCall: AssetsContractController['getBalancesInSingleCall'];\n getTokensState: () => TokensState;\n trackMetaMetricsEvent: (options: {\n event: string;\n category: string;\n properties: {\n tokens: string[];\n token_standard: string;\n asset_type: string;\n };\n }) => void;\n messenger: TokenDetectionControllerMessenger;\n }) {\n super({\n name: controllerName,\n messenger,\n state: {},\n metadata: {},\n });\n\n this.#disabled = disabled;\n this.setIntervalLength(interval);\n\n this.#networkClientId = networkClientId;\n this.#selectedAddress = selectedAddress;\n this.#chainId = this.#getCorrectChainId(networkClientId);\n\n const { useTokenDetection: defaultUseTokenDetection } =\n this.messagingSystem.call('PreferencesController:getState');\n this.#isDetectionEnabledFromPreferences = defaultUseTokenDetection;\n this.#isDetectionEnabledForNetwork = isTokenDetectionSupportedForNetwork(\n this.#chainId,\n );\n\n this.#addDetectedTokens = addDetectedTokens;\n this.#getBalancesInSingleCall = getBalancesInSingleCall;\n this.#getTokensState = getTokensState;\n\n this.#trackMetaMetricsEvent = trackMetaMetricsEvent;\n\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.#registerEventListeners();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system subscriptions to controller events.\n */\n #registerEventListeners() {\n this.messagingSystem.subscribe('KeyringController:unlock', async () => {\n this.#isUnlocked = true;\n await this.#restartTokenDetection();\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n this.#stopPolling();\n });\n\n this.messagingSystem.subscribe(\n 'TokenListController:stateChange',\n async ({ tokenList }) => {\n const hasTokens = Object.keys(tokenList).length;\n\n if (hasTokens) {\n await this.#restartTokenDetection();\n }\n },\n );\n\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n async ({ selectedAddress: newSelectedAddress, useTokenDetection }) => {\n const isSelectedAddressChanged =\n this.#selectedAddress !== newSelectedAddress;\n const isDetectionChangedFromPreferences =\n this.#isDetectionEnabledFromPreferences !== useTokenDetection;\n\n this.#selectedAddress = newSelectedAddress;\n this.#isDetectionEnabledFromPreferences = useTokenDetection;\n\n if (\n useTokenDetection &&\n (isSelectedAddressChanged || isDetectionChangedFromPreferences)\n ) {\n await this.#restartTokenDetection({\n selectedAddress: this.#selectedAddress,\n });\n }\n },\n );\n\n this.messagingSystem.subscribe(\n 'AccountsController:selectedAccountChange',\n async ({ address: newSelectedAddress }) => {\n const isSelectedAddressChanged =\n this.#selectedAddress !== newSelectedAddress;\n if (\n isSelectedAddressChanged &&\n this.#isDetectionEnabledFromPreferences\n ) {\n this.#selectedAddress = newSelectedAddress;\n await this.#restartTokenDetection({\n selectedAddress: this.#selectedAddress,\n });\n }\n },\n );\n\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n async ({ selectedNetworkClientId }) => {\n const isNetworkClientIdChanged =\n this.#networkClientId !== selectedNetworkClientId;\n\n const newChainId = this.#getCorrectChainId(selectedNetworkClientId);\n this.#isDetectionEnabledForNetwork =\n isTokenDetectionSupportedForNetwork(newChainId);\n\n if (isNetworkClientIdChanged && this.#isDetectionEnabledForNetwork) {\n this.#networkClientId = selectedNetworkClientId;\n await this.#restartTokenDetection({\n networkClientId: this.#networkClientId,\n });\n }\n },\n );\n }\n\n /**\n * Allows controller to make active and passive polling requests\n */\n enable() {\n this.#disabled = false;\n }\n\n /**\n * Blocks controller from making network calls\n */\n disable() {\n this.#disabled = true;\n }\n\n /**\n * Internal isActive state\n *\n * @type {object}\n */\n get isActive() {\n return !this.#disabled && this.#isUnlocked;\n }\n\n /**\n * Start polling for detected tokens.\n */\n async start() {\n this.enable();\n await this.#startPolling();\n }\n\n /**\n * Stop polling for detected tokens.\n */\n stop() {\n this.disable();\n this.#stopPolling();\n }\n\n #stopPolling() {\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n }\n\n /**\n * Starts a new polling interval.\n */\n async #startPolling(): Promise<void> {\n if (!this.isActive) {\n return;\n }\n this.#stopPolling();\n await this.detectTokens();\n this.#intervalId = setInterval(async () => {\n await this.detectTokens();\n }, this.getIntervalLength());\n }\n\n #getCorrectChainId(networkClientId?: NetworkClientId) {\n const { chainId } =\n this.messagingSystem.call(\n 'NetworkController:getNetworkConfigurationByNetworkClientId',\n networkClientId ?? this.#networkClientId,\n ) ?? {};\n return chainId ?? this.#chainId;\n }\n\n async _executePoll(\n networkClientId: string,\n options: { address: string },\n ): Promise<void> {\n if (!this.isActive) {\n return;\n }\n await this.detectTokens({\n networkClientId,\n accountAddress: options.address,\n });\n }\n\n /**\n * Restart token detection polling period and call detectNewTokens\n * in case of address change or user session initialization.\n *\n * @param options - Options for restart token detection.\n * @param options.selectedAddress - the selectedAddress against which to detect for token balances\n * @param options.networkClientId - The ID of the network client to use.\n */\n async #restartTokenDetection({\n selectedAddress,\n networkClientId,\n }: { selectedAddress?: string; networkClientId?: string } = {}) {\n await this.detectTokens({\n networkClientId,\n accountAddress: selectedAddress,\n });\n this.setIntervalLength(DEFAULT_INTERVAL);\n }\n\n /**\n * For each token in the token list provided by the TokenListController, checks the token's balance for the selected account address on the active network.\n * On mainnet, if token detection is disabled in preferences, ERC20 token auto detection will be triggered for each contract address in the legacy token list from the @metamask/contract-metadata repo.\n *\n * @param options - Options for token detection.\n * @param options.networkClientId - The ID of the network client to use.\n * @param options.accountAddress - the selectedAddress against which to detect for token balances.\n */\n async detectTokens({\n networkClientId,\n accountAddress,\n }: {\n networkClientId?: NetworkClientId;\n accountAddress?: string;\n } = {}): Promise<void> {\n if (!this.isActive || !this.#isDetectionEnabledForNetwork) {\n return;\n }\n const selectedAddress = accountAddress ?? this.#selectedAddress;\n const chainId = this.#getCorrectChainId(networkClientId);\n\n if (\n !this.#isDetectionEnabledFromPreferences &&\n chainId !== ChainId.mainnet\n ) {\n return;\n }\n const isTokenDetectionInactiveInMainnet =\n !this.#isDetectionEnabledFromPreferences && chainId === ChainId.mainnet;\n const { tokenList } = this.messagingSystem.call(\n 'TokenListController:getState',\n );\n const tokenListUsed = isTokenDetectionInactiveInMainnet\n ? STATIC_MAINNET_TOKEN_LIST\n : tokenList;\n\n const { tokens, detectedTokens } = this.#getTokensState();\n const tokensToDetect: string[] = [];\n\n for (const tokenAddress of Object.keys(tokenListUsed)) {\n if (\n !findCaseInsensitiveMatch(\n tokens.map(({ address }) => address),\n tokenAddress,\n ) &&\n !findCaseInsensitiveMatch(\n detectedTokens.map(({ address }) => address),\n tokenAddress,\n )\n ) {\n tokensToDetect.push(tokenAddress);\n }\n }\n const sliceOfTokensToDetect = [];\n sliceOfTokensToDetect[0] = tokensToDetect.slice(0, 1000);\n sliceOfTokensToDetect[1] = tokensToDetect.slice(\n 1000,\n tokensToDetect.length - 1,\n );\n\n /* istanbul ignore else */\n if (!selectedAddress) {\n return;\n }\n\n for (const tokensSlice of sliceOfTokensToDetect) {\n if (tokensSlice.length === 0) {\n break;\n }\n\n await safelyExecute(async () => {\n const balances = await this.#getBalancesInSingleCall(\n selectedAddress,\n tokensSlice,\n );\n const tokensToAdd: Token[] = [];\n const eventTokensDetails = [];\n for (const tokenAddress of Object.keys(balances)) {\n let ignored;\n /* istanbul ignore else */\n const { ignoredTokens } = this.#getTokensState();\n if (ignoredTokens.length) {\n ignored = ignoredTokens.find(\n (ignoredTokenAddress) =>\n ignoredTokenAddress === toChecksumHexAddress(tokenAddress),\n );\n }\n const caseInsensitiveTokenKey =\n findCaseInsensitiveMatch(\n Object.keys(tokenListUsed),\n tokenAddress,\n ) ?? '';\n\n if (ignored === undefined) {\n const { decimals, symbol, aggregators, iconUrl, name } =\n tokenList[caseInsensitiveTokenKey];\n eventTokensDetails.push(`${symbol} - ${tokenAddress}`);\n tokensToAdd.push({\n address: tokenAddress,\n decimals,\n symbol,\n aggregators,\n image: iconUrl,\n isERC721: false,\n name,\n });\n }\n }\n\n if (tokensToAdd.length) {\n this.#trackMetaMetricsEvent({\n event: 'Token Detected',\n category: 'Wallet',\n properties: {\n tokens: eventTokensDetails,\n token_standard: 'ERC20',\n asset_type: 'TOKEN',\n },\n });\n await this.#addDetectedTokens(tokensToAdd, {\n selectedAddress,\n chainId,\n });\n }\n });\n }\n }\n}\n\nexport default TokenDetectionController;\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/assets-controllers",
|
|
3
|
-
"version": "25.0.0-preview.
|
|
3
|
+
"version": "25.0.0-preview.bc4dd941",
|
|
4
4
|
"description": "Controllers which manage interactions involving ERC-20, ERC-721, and ERC-1155 tokens (including NFTs)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -36,11 +36,13 @@
|
|
|
36
36
|
"@ethersproject/contracts": "^5.7.0",
|
|
37
37
|
"@ethersproject/providers": "^5.7.0",
|
|
38
38
|
"@metamask/abi-utils": "^2.0.2",
|
|
39
|
+
"@metamask/accounts-controller": "^10.0.0",
|
|
39
40
|
"@metamask/approval-controller": "^5.1.2",
|
|
40
41
|
"@metamask/base-controller": "^4.1.1",
|
|
41
42
|
"@metamask/contract-metadata": "^2.4.0",
|
|
42
43
|
"@metamask/controller-utils": "^8.0.2",
|
|
43
44
|
"@metamask/eth-query": "^4.0.0",
|
|
45
|
+
"@metamask/keyring-controller": "^12.2.0",
|
|
44
46
|
"@metamask/metamask-eth-abis": "3.0.0",
|
|
45
47
|
"@metamask/network-controller": "^17.2.0",
|
|
46
48
|
"@metamask/polling-controller": "^5.0.0",
|
|
@@ -58,7 +60,8 @@
|
|
|
58
60
|
},
|
|
59
61
|
"devDependencies": {
|
|
60
62
|
"@metamask/auto-changelog": "^3.4.4",
|
|
61
|
-
"@metamask/ethjs-provider-http": "^0.
|
|
63
|
+
"@metamask/ethjs-provider-http": "^0.3.0",
|
|
64
|
+
"@metamask/keyring-api": "^3.0.0",
|
|
62
65
|
"@types/jest": "^27.4.1",
|
|
63
66
|
"@types/lodash": "^4.14.191",
|
|
64
67
|
"@types/node": "^16.18.54",
|
|
@@ -73,7 +76,9 @@
|
|
|
73
76
|
"typescript": "~4.8.4"
|
|
74
77
|
},
|
|
75
78
|
"peerDependencies": {
|
|
79
|
+
"@metamask/accounts-controller": "^10.0.0",
|
|
76
80
|
"@metamask/approval-controller": "^5.1.2",
|
|
81
|
+
"@metamask/keyring-controller": "^12.2.0",
|
|
77
82
|
"@metamask/network-controller": "^17.2.0",
|
|
78
83
|
"@metamask/preferences-controller": "^7.0.0"
|
|
79
84
|
},
|