Skip to content

Commit

Permalink
[detectTokens] Refactor by extracting three methods:`#getCorrectChain…
Browse files Browse the repository at this point in the history
…IdAndNetworkClientId`, `#getTokenListAndSlicesOfTokensToDetect`, `#addDetectedTokens`

- Fixes #1614
- Maintains distinction between private class fields `#{chainId,selectedAddress,networkClientId}{,AgainstWhichToDetect}`, so that `detectTokens` method can be used independently of polling/passive detection (convert to static method?). Is this expected behavior?
  • Loading branch information
MajorLift committed Feb 18, 2024
1 parent bc68646 commit 18fc929
Showing 1 changed file with 105 additions and 61 deletions.
166 changes: 105 additions & 61 deletions packages/assets-controllers/src/TokenDetectionController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,12 @@ export class TokenDetectionController extends StaticIntervalPollingController<

#networkClientId: NetworkClientId;

#chainIdAgainstWhichToDetect: Hex;

#addressAgainstWhichToDetect: string;

#networkClientIdAgainstWhichToDetect: NetworkClientId;

#disabled: boolean;

#isUnlocked: boolean;
Expand Down Expand Up @@ -229,14 +235,18 @@ export class TokenDetectionController extends StaticIntervalPollingController<
this.#disabled = disabled;
this.setIntervalLength(interval);

this.#networkClientId = networkClientId;
this.#selectedAddress =
selectedAddress ??
this.messagingSystem.call('AccountsController:getSelectedAccount')
.address;
const { chainId } =
this.#addressAgainstWhichToDetect = this.#selectedAddress;

const { chainId, networkClientId: correctNetworkClientId } =
this.#getCorrectChainIdAndNetworkClientId(networkClientId);
this.#chainId = chainId;
this.#chainIdAgainstWhichToDetect = this.#chainId;
this.#networkClientId = correctNetworkClientId;
this.#networkClientIdAgainstWhichToDetect = this.#networkClientId;

const { useTokenDetection: defaultUseTokenDetection } =
this.messagingSystem.call('PreferencesController:getState');
Expand Down Expand Up @@ -483,33 +493,52 @@ export class TokenDetectionController extends StaticIntervalPollingController<
return;
}

const addressAgainstWhichToDetect = accountAddress ?? this.#selectedAddress;
const {
chainId: chainIdAgainstWhichToDetect,
networkClientId: networkClientIdAgainstWhichToDetect,
} = this.#getCorrectChainIdAndNetworkClientId(networkClientId);
this.#addressAgainstWhichToDetect = accountAddress ?? this.#selectedAddress;
const { chainId, networkClientId: selectedNetworkClientId } =
this.#getCorrectChainIdAndNetworkClientId(networkClientId);
this.#chainIdAgainstWhichToDetect = chainId;
this.#networkClientIdAgainstWhichToDetect = selectedNetworkClientId;

if (!isTokenDetectionSupportedForNetwork(chainIdAgainstWhichToDetect)) {
if (
!isTokenDetectionSupportedForNetwork(this.#chainIdAgainstWhichToDetect)
) {
return;
}

if (
!this.#isDetectionEnabledFromPreferences &&
chainIdAgainstWhichToDetect !== ChainId.mainnet
this.#chainIdAgainstWhichToDetect !== ChainId.mainnet
) {
return;
}
const { tokenList, slicesOfTokensToDetect } =
this.#getTokenListAndSlicesOfTokensToDetect();
for (const tokensSlice of slicesOfTokensToDetect) {
if (tokensSlice.length === 0) {
break;
}
await this.#addDetectedTokens({
tokenList,
tokensSlice,
});
}
}

#getTokenListAndSlicesOfTokensToDetect(): {
tokenList: Record<
string,
Pick<TokenListToken, 'address' | 'decimals' | 'symbol'>
>;
slicesOfTokensToDetect: string[][];
} {
const isTokenDetectionInactiveInMainnet =
!this.#isDetectionEnabledFromPreferences &&
chainIdAgainstWhichToDetect === ChainId.mainnet;
this.#chainIdAgainstWhichToDetect === ChainId.mainnet;
const { tokensChainsCache } = this.messagingSystem.call(
'TokenListController:getState',
);
const tokenList =
tokensChainsCache[chainIdAgainstWhichToDetect]?.data ?? {};
const tokenListUsed = isTokenDetectionInactiveInMainnet
const tokenList = isTokenDetectionInactiveInMainnet
? STATIC_MAINNET_TOKEN_LIST
: tokenList;
: tokensChainsCache[this.#chainIdAgainstWhichToDetect]?.data ?? {};

const { allTokens, allDetectedTokens, allIgnoredTokens } =
this.messagingSystem.call('TokensController:getState');
Expand All @@ -519,9 +548,12 @@ export class TokenDetectionController extends StaticIntervalPollingController<
allIgnoredTokens,
].map((tokens) =>
(
tokens[chainIdAgainstWhichToDetect]?.[addressAgainstWhichToDetect] ?? []
tokens[this.#chainIdAgainstWhichToDetect]?.[
this.#addressAgainstWhichToDetect
] ?? []
).map((value) => (typeof value === 'string' ? value : value.address)),
);

const tokensToDetect: string[] = [];
for (const tokenAddress of Object.keys(tokenList)) {
if (
Expand All @@ -535,60 +567,72 @@ export class TokenDetectionController extends StaticIntervalPollingController<
tokensToDetect.push(tokenAddress);
}
}

const slicesOfTokensToDetect = [];
slicesOfTokensToDetect[0] = tokensToDetect.slice(0, 1000);
slicesOfTokensToDetect[1] = tokensToDetect.slice(
1000,
tokensToDetect.length - 1,
);
for (const tokensSlice of slicesOfTokensToDetect) {
if (tokensSlice.length === 0) {
break;

return { tokenList, slicesOfTokensToDetect };
}

async #addDetectedTokens({
tokenList,
tokensSlice,
}: {
tokenList: Record<
string,
Partial<TokenListToken> & Pick<Token, 'address' | 'symbol' | 'decimals'>
>;
tokensSlice: string[];
}): Promise<void> {
await safelyExecute(async () => {
const balances = await this.#getBalancesInSingleCall(
this.#addressAgainstWhichToDetect,
tokensSlice,
this.#networkClientIdAgainstWhichToDetect,
);

const tokensWithBalance: Token[] = [];
const eventTokensDetails: string[] = [];
for (const nonZeroTokenAddress of Object.keys(balances)) {
const { decimals, symbol, aggregators, iconUrl, name } =
tokenList[nonZeroTokenAddress];
eventTokensDetails.push(`${symbol} - ${nonZeroTokenAddress}`);
tokensWithBalance.push({
address: nonZeroTokenAddress,
decimals,
symbol,
aggregators,
image: iconUrl,
isERC721: false,
name,
});
}

await safelyExecute(async () => {
const balances = await this.#getBalancesInSingleCall(
addressAgainstWhichToDetect,
tokensSlice,
networkClientIdAgainstWhichToDetect,
if (tokensWithBalance.length) {
this.#trackMetaMetricsEvent({
event: 'Token Detected',
category: 'Wallet',
properties: {
tokens: eventTokensDetails,
token_standard: 'ERC20',
asset_type: 'TOKEN',
},
});

await this.messagingSystem.call(
'TokensController:addDetectedTokens',
tokensWithBalance,
{
selectedAddress: this.#addressAgainstWhichToDetect,
chainId: this.#chainIdAgainstWhichToDetect,
},
);
const tokensWithBalance: Token[] = [];
const eventTokensDetails: string[] = [];
for (const nonZeroTokenAddress of Object.keys(balances)) {
const { decimals, symbol, aggregators, iconUrl, name } =
tokenListUsed[nonZeroTokenAddress];
eventTokensDetails.push(`${symbol} - ${nonZeroTokenAddress}`);
tokensWithBalance.push({
address: nonZeroTokenAddress,
decimals,
symbol,
aggregators,
image: iconUrl,
isERC721: false,
name,
});
}
if (tokensWithBalance.length) {
this.#trackMetaMetricsEvent({
event: 'Token Detected',
category: 'Wallet',
properties: {
tokens: eventTokensDetails,
token_standard: 'ERC20',
asset_type: 'TOKEN',
},
});
await this.messagingSystem.call(
'TokensController:addDetectedTokens',
tokensWithBalance,
{
selectedAddress: addressAgainstWhichToDetect,
chainId: chainIdAgainstWhichToDetect,
},
);
}
});
}
}
});
}
}

Expand Down

0 comments on commit 18fc929

Please sign in to comment.