mirror of
https://github.com/Such-Software/hash-wallet.git
synced 2026-12-03 12:24:19 +01:00
CW-1228: Automatically detect wallet tokens for EVM chains (#2827)
* feat: Automatically detect wallet tokens for EVM chains * feat: Disable potential tg scam tokens by default * feat: Add homoglyph normalization to detect spoofing attacks in token symbols * refactor: Improve scam token detection and apply to automatically fetched EVM tokens * refactor: Enhance scam detection for automatically detected tokens in evm wallets * feat: Add fiat check to scam checks on automatically imported token and disable tokens that fail the check * feat: Add fiat check to scam checks on automatically imported token and disable tokens that fail the check * feat: Add fiat check to scam checks on automatically imported token and disable tokens that fail the check * feat: Enable whitelisted tokens with balance when importing wallet tokens
This commit is contained in:
@@ -518,6 +518,10 @@ class EVMChainClient {
|
||||
}
|
||||
|
||||
Future<Erc20Token?> getErc20TokenFromMoralis(String contractAddress, String chainName) async {
|
||||
if (secrets.moralisApiKey.isEmpty) {
|
||||
printV('Moralis API key is empty, cannot fetch token info');
|
||||
return null;
|
||||
}
|
||||
final uri = Uri.https(
|
||||
'deep-index.moralis.io',
|
||||
'/api/v2.2/erc20/metadata',
|
||||
@@ -567,6 +571,93 @@ class EVMChainClient {
|
||||
);
|
||||
}
|
||||
|
||||
Future<List<MoralisWalletTokenBalance>> fetchWalletTokensFromMoralis(
|
||||
String address,
|
||||
String chainName,
|
||||
) async {
|
||||
try {
|
||||
if (secrets.moralisApiKey.isEmpty) {
|
||||
printV('Moralis API key is empty, cannot fetch wallet tokens');
|
||||
return [];
|
||||
}
|
||||
|
||||
final uri = Uri.https(
|
||||
'deep-index.moralis.io',
|
||||
'/api/v2.2/$address/erc20',
|
||||
{
|
||||
"chain": chainName,
|
||||
},
|
||||
);
|
||||
|
||||
final response = await client.get(
|
||||
uri,
|
||||
headers: {
|
||||
"Accept": "application/json",
|
||||
"X-API-Key": secrets.moralisApiKey,
|
||||
},
|
||||
);
|
||||
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
printV('Moralis API returned invalid status code: ${response.statusCode}');
|
||||
return [];
|
||||
}
|
||||
|
||||
final decodedResponse = jsonDecode(response.body) as List;
|
||||
|
||||
final List<MoralisWalletTokenBalance> tokens = [];
|
||||
|
||||
for (final item in decodedResponse) {
|
||||
final tokenData = item as Map<String, dynamic>;
|
||||
|
||||
final balanceStr = tokenData['balance'] as String? ?? '0';
|
||||
final balanceWei = BigInt.tryParse(balanceStr) ?? BigInt.zero;
|
||||
if (balanceWei == BigInt.zero) continue;
|
||||
|
||||
final contractAddress = (tokenData['token_address'] as String? ?? '').toLowerCase();
|
||||
final name = (tokenData['name'] as String? ?? '').toString();
|
||||
final symbol = (tokenData['symbol'] as String? ?? '').toString();
|
||||
final symbolFiltered = symbol.replaceFirst(RegExp('^\\\$'), '');
|
||||
|
||||
final decimalsRaw = tokenData['decimals'];
|
||||
final decimals =
|
||||
decimalsRaw is int ? decimalsRaw : int.tryParse(decimalsRaw.toString()) ?? 18;
|
||||
|
||||
final logo = tokenData['logo'] as String?;
|
||||
final thumbnail = tokenData['thumbnail'] as String?;
|
||||
final iconUrl = logo ?? thumbnail;
|
||||
|
||||
final possibleSpamRaw = tokenData['possible_spam'];
|
||||
final possibleSpam = possibleSpamRaw is bool
|
||||
? possibleSpamRaw
|
||||
: (possibleSpamRaw.toString().toLowerCase() == 'true');
|
||||
|
||||
final verifiedContractRaw = tokenData['verified_contract'];
|
||||
final verifiedContract = verifiedContractRaw is bool
|
||||
? verifiedContractRaw
|
||||
: (verifiedContractRaw.toString().toLowerCase() == 'true');
|
||||
|
||||
tokens.add(
|
||||
MoralisWalletTokenBalance(
|
||||
contractAddress: contractAddress,
|
||||
name: name,
|
||||
symbol: symbolFiltered,
|
||||
decimals: decimals,
|
||||
iconUrl: iconUrl,
|
||||
balanceWei: balanceWei,
|
||||
possibleSpam: possibleSpam,
|
||||
verifiedContract: verifiedContract,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return tokens;
|
||||
} catch (e, stackTrace) {
|
||||
printV('Error fetching wallet tokens from Moralis: ${e.toString()}');
|
||||
printV('Stack trace: ${stackTrace.toString()}');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
Uint8List hexToBytes(String hexString) {
|
||||
return Uint8List.fromList(
|
||||
hex.HEX.decode(hexString.startsWith('0x') ? hexString.substring(2) : hexString));
|
||||
@@ -599,3 +690,25 @@ class EVMChainClient {
|
||||
// return exponent;
|
||||
// }
|
||||
}
|
||||
|
||||
class MoralisWalletTokenBalance {
|
||||
final String contractAddress;
|
||||
final String name;
|
||||
final String symbol;
|
||||
final int decimals;
|
||||
final String? iconUrl;
|
||||
final BigInt balanceWei;
|
||||
final bool possibleSpam;
|
||||
final bool verifiedContract;
|
||||
|
||||
MoralisWalletTokenBalance({
|
||||
required this.contractAddress,
|
||||
required this.name,
|
||||
required this.symbol,
|
||||
required this.decimals,
|
||||
this.iconUrl,
|
||||
required this.balanceWei,
|
||||
required this.possibleSpam,
|
||||
required this.verifiedContract,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import 'package:cw_core/pending_transaction.dart';
|
||||
import 'package:cw_core/sync_status.dart';
|
||||
import 'package:cw_core/transaction_direction.dart';
|
||||
import 'package:cw_core/transaction_priority.dart';
|
||||
import 'package:cw_core/utils/homoglyph_normalizer.dart';
|
||||
import 'package:cw_core/utils/print_verbose.dart';
|
||||
import 'package:cw_core/wallet_addresses.dart';
|
||||
import 'package:cw_core/wallet_base.dart';
|
||||
@@ -440,24 +441,50 @@ abstract class EVMChainWalletBase
|
||||
await save();
|
||||
}
|
||||
|
||||
Future<void> _checkForExistingScamTokens() async {
|
||||
bool isTokenPropertiesSuspicious(Erc20Token token) {
|
||||
final baseCurrencySymbols = CryptoCurrency.all.map((e) => e.title.toUpperCase()).toList();
|
||||
|
||||
bool isTokenWhitelisted = getDefaultTokenContractAddresses
|
||||
.any((element) => element.toLowerCase() == token.contractAddress.toLowerCase());
|
||||
|
||||
// Normalize the token data to check for homoglyph spoofing attack, characters that look like ASCII (Cyrillic, Greek, etc.)
|
||||
final normalizedName = normalizeHomoglyphs(token.name.trim().toUpperCase());
|
||||
final normalizedSymbol = normalizeHomoglyphs(token.symbol.trim().toUpperCase());
|
||||
final normalizedTitle = normalizeHomoglyphs(token.title.trim().toUpperCase());
|
||||
|
||||
final suspiciousStrings = [
|
||||
't.me',
|
||||
'.me',
|
||||
'telegram',
|
||||
'http',
|
||||
'https',
|
||||
'.com',
|
||||
'airdrop',
|
||||
'www',
|
||||
'.xyz',
|
||||
'🎁',
|
||||
];
|
||||
|
||||
final hasSuspiciousData = suspiciousStrings.any(
|
||||
(element) =>
|
||||
normalizedName.toLowerCase().contains(element) ||
|
||||
normalizedSymbol.toLowerCase().contains(element) ||
|
||||
normalizedTitle.toLowerCase().contains(element),
|
||||
);
|
||||
|
||||
// Check if the token symbol is the same as any of the base currencies symbols (ETH, SOL, POL, TRX, etc).
|
||||
// If it is, then it's probably a scam unless it's in the whitelist.
|
||||
final hasSuspiciousSymbol = baseCurrencySymbols.contains(normalizedSymbol);
|
||||
|
||||
return hasSuspiciousData || (hasSuspiciousSymbol && !isTokenWhitelisted);
|
||||
}
|
||||
|
||||
Future<void> _checkForExistingScamTokens() async {
|
||||
for (var token in erc20Currencies) {
|
||||
bool isPotentialScam = false;
|
||||
|
||||
bool isWhitelisted = getDefaultTokenContractAddresses
|
||||
.any((element) => element.toLowerCase() == token.contractAddress.toLowerCase());
|
||||
|
||||
final tokenSymbol = token.title.toUpperCase();
|
||||
|
||||
// check if the token symbol is the same as any of the base currencies symbols (ETH, SOL, POL, TRX, etc):
|
||||
// if it is, then it's probably a scam unless it's in the whitelist
|
||||
if (baseCurrencySymbols.contains(tokenSymbol.trim().toUpperCase()) && !isWhitelisted) {
|
||||
if (isTokenPropertiesSuspicious(token)) {
|
||||
isPotentialScam = true;
|
||||
}
|
||||
|
||||
if (isPotentialScam) {
|
||||
token.isPotentialScam = true;
|
||||
token.iconPath = null;
|
||||
await token.save();
|
||||
@@ -482,6 +509,61 @@ abstract class EVMChainWalletBase
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<Erc20Token>> discoverTokensFromMoralis() async {
|
||||
try {
|
||||
if (!evmChainErc20TokensBox.isOpen) return [];
|
||||
|
||||
final address = walletAddresses.address;
|
||||
if (address.isEmpty) return [];
|
||||
|
||||
final chainName = EVMChainUtils.getDefaultTokenSymbol(selectedChainId).toLowerCase();
|
||||
|
||||
final walletTokens = await _client.fetchWalletTokensFromMoralis(address, chainName);
|
||||
if (walletTokens.isEmpty) return [];
|
||||
|
||||
final existingTokenAddresses = {
|
||||
for (final token in evmChainErc20TokensBox.values)
|
||||
token.contractAddress.toLowerCase(): token,
|
||||
};
|
||||
|
||||
final whitelistedTokenAddresses =
|
||||
getDefaultTokenContractAddresses.map((a) => a.toLowerCase()).toSet();
|
||||
|
||||
final List<Erc20Token> newTokens = [];
|
||||
|
||||
for (final token in walletTokens) {
|
||||
final addr = token.contractAddress.toLowerCase();
|
||||
|
||||
final existingToken = existingTokenAddresses[addr];
|
||||
if (existingToken != null) {
|
||||
if (whitelistedTokenAddresses.contains(addr) && !existingToken.enabled) {
|
||||
existingToken.enabled = true;
|
||||
await existingToken.save();
|
||||
await addErc20Token(existingToken);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
final newToken = Erc20Token(
|
||||
name: token.name,
|
||||
symbol: token.symbol,
|
||||
contractAddress: addr,
|
||||
decimal: token.decimals,
|
||||
iconPath: token.iconUrl,
|
||||
tag: EVMChainUtils.getDefaultTokenTag(selectedChainId),
|
||||
isPotentialScam: token.possibleSpam,
|
||||
);
|
||||
|
||||
newTokens.add(newToken);
|
||||
}
|
||||
|
||||
return newTokens;
|
||||
} catch (e) {
|
||||
printV('Error discovering tokens from Moralis: ${e.toString()}');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
int calculateEstimatedFee(TransactionPriority priority, int? amount) => 0;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user