Token & NFT Scam Investigation
Overview
Token and NFT scams — including rug pulls, honeypot tokens, pump-and-dump schemes, wash trading, and floor manipulation — account for the majority of blockchain fraud by victim count. Unlike protocol exploits that target code flaws, these scams target retail investors through deception and market manipulation. This skill covers analyzing token contracts for honeypot mechanisms, detecting wash trading patterns on NFT marketplaces, investigating rug pull setups (liquidity removal, mint controls, proxy upgrades), identifying pump-and-dump coordination, and tracing scam proceeds. It provides working Python code for each detection category, real case studies with exploitable contract addresses, and a monetization framework for selling investigation services.
When to Use
Trigger phrases:
"token scam investigation"
"nft scam investigation"
"Analyze a rug pull"
"Check if a token is a honeypot"
"Detect wash trading in an NFT collection"
"is this token safe to buy"
"check token contract for honeypot"
"investigate NFT wash trading"
"trace rug pull proceeds"
"check if this is a scam token"
"due diligence on token launch"
"verify liquidity lock"
When investigating a suspicious token launch for potential scam indicators
When analyzing an NFT collection for wash trading or price manipulation
When tracing rug pull or pump-and-dump proceeds
When building automated scam detection for token/NFT due diligence
When gathering evidence for a fraud complaint or bounty submission
When performing pre-purchase due diligence on a new token or NFT collection
When investigating a project that claims to have been "rugged" for insurance claims
When conducting competitive intelligence on scam operations
When NOT to Use
- You need to trace stolen funds from a hack or exploit (use onchain-transaction-forensics skill)
- You need to analyze a DeFi protocol's smart contract vulnerability (use defi-incident-analysis skill)
- Task requires recovering lost funds or filing a police report (use proper legal channels)
- You are the project owner needing to prove your token is legitimate (use a different due diligence process)
- The investigation requires access to private sale or KYC data you don't have
- You need to audit a complex DeFi protocol's tokenomics model (use smart-contract-exploiter skill)
- You are building a trading bot that needs MEV protection analysis (use onchain-transaction-forensics skill)
- The token is a well-known blue-chip project and you're looking for FUD evidence
Prerequisites
- Python 3.8+ with web3.py (>=6.0), requests, pandas, numpy, networkx
- Ethereum RPC node access (Alchemy, Infura, or local node) or chain-specific node (BSC, Polygon, etc.)
- Block explorer API key (Etherscan, BscScan, Polygonscan) for historical event queries
- Solidity understanding (for contract-level scam analysis including proxy patterns and fee mechanisms)
- NFT marketplace API access (OpenSea, Blur, LooksRare) for trading data
- Familiarity with DEX concepts (Uniswap v2/v3, PancakeSwap, LP tokens)
- git (for cloning known scam contract source code from audit repositories)
Core Workflow
# Entry point: run all scam checks against a token contract
from web3 import Web3
from typing import Optional, Dict, Any, List, Tuple
from dataclasses import dataclass, field
import json
import time
import requests
# Configuration
ETHERSCAN_API_KEY = "YOUR_API_KEY"
RPC_URL = "https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY"
w3 = Web3(Web3.HTTPProvider(RPC_URL))
# Standard ERC-20 ABI fragments
ERC20_ABI = [
{"inputs": [], "name": "name", "outputs": [{"type": "string"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "symbol", "outputs": [{"type": "string"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "decimals", "outputs": [{"type": "uint8"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "totalSupply", "outputs": [{"type": "uint256"}], "stateMutability": "view", "type": "function"},
{"inputs": [{"type": "address"}], "name": "balanceOf", "outputs": [{"type": "uint256"}], "stateMutability": "view", "type": "function"},
{"inputs": [{"type": "address"}, {"type": "address"}], "name": "allowance", "outputs": [{"type": "uint256"}], "stateMutability": "view", "type": "function"},
# Transfer event
{"anonymous": False, "inputs": [{"indexed": True, "name": "from", "type": "address"}, {"indexed": True, "name": "to", "type": "address"}, {"indexed": False, "name": "value", "type": "uint256"}], "name": "Transfer", "type": "event"},
]
# Ownership ABIs to test
OWNERSHIP_ABIS = {
"ownable": [
{"inputs": [], "name": "owner", "outputs": [{"type": "address"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function"},
],
"access_control": [
{"inputs": [{"type": "bytes32"}], "name": "hasRole", "outputs": [{"type": "bool"}], "stateMutability": "view", "type": "function"},
{"inputs": [], "name": "DEFAULT_ADMIN_ROLE", "outputs": [{"type": "bytes32"}], "stateMutability": "view", "type": "function"},
],
}
# ERC-1967 proxy storage slots (beige paper)
ERC1967_IMPLEMENTATION_SLOT = "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
ERC1967_BEACON_SLOT = "0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50"
ADMIN_SLOT = "0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103"
def run_scam_check(address: str, rpc_url: str = RPC_URL) -> dict:
"""Run a comprehensive scam check on a token contract."""
w3_local = Web3(Web3.HTTPProvider(rpc_url))
checks = {
"basic_info": check_basic_info(w3_local, address),
"honeypot": simulate_honeypot(w3_local, address),
"proxy": check_proxy_upgradeability(w3_local, address),
"ownership": check_all_ownership_interfaces(w3_local, address),
"holder_distribution": analyze_holder_distribution(w3_local, address),
"approval_risks": check_approval_abuse(w3_local, address),
}
return checks
Step 1: Token Contract Analysis
Examine the token contract for scam indicators:
- Honeypot detection — can the token be bought but not sold? Check for blacklist functions, transfer fee manipulation, or balance restrictions
- Ownership not renounced — deployer can still mint, pause transfers, or blacklist addresses
- Suspicious fee structure — extremely high buy/sell taxes that benefit the deployer
- Honeypot simulation — simulate a buy and sell transaction to verify both succeed
- Proxy/upgradeable pattern — contract can be upgraded to malicious logic later
- Mint function — unlimited mint capability that dilutes holders
- TOP10 holder concentration — if 90%+ supply is in a few addresses, risk of dump
def check_basic_info(w3: Web3, token_address: str) -> dict:
"""Fetch basic ERC-20 token metadata and catch common ABI failures."""
contract = w3.eth.contract(address=token_address, abi=ERC20_ABI)
result = {}
for field in ["name", "symbol", "decimals", "totalSupply"]:
try:
fn = getattr(contract.functions, field)
result[field] = fn().call()
except Exception as e:
result[field] = f"ERROR: {e}"
return result
def check_all_ownership_interfaces(w3: Web3, token_address: str) -> dict:
"""Probe multiple ownership interfaces and check renounced status."""
results = {"interfaces_found": []}
# 1. Ownable (OpenZeppelin standard)
try:
o_contract = w3.eth.contract(address=token_address, abi=OWNERSHIP_ABIS["ownable"])
owner = o_contract.functions.owner().call()
is_renounced = owner == "0x0000000000000000000000000000000000000000" or owner == "0x0000000000000000000000000000000000000001"
results["ownable_owner"] = owner
results["ownable_renounced"] = is_renounced
results["interfaces_found"].append("Ownable")
except Exception:
results["ownable_owner"] = None
results["ownable_renounced"] = None
# 2. AccessControl (OpenZeppelin v4+)
try:
ac_contract = w3.eth.contract(address=token_address, abi=OWNERSHIP_ABIS["access_control"])
admin_role = ac_contract.functions.DEFAULT_ADMIN_ROLE().call()
# Try to find the admin role holder via event log
results["access_control_found"] = True
results["default_admin_role"] = admin_role.hex()
results["interfaces_found"].append("AccessControl")
except Exception:
results["access_control_found"] = False
# 3. Check if deployer still has a special "minter" style role
deployer = _get_contract_deployer(w3, token_address)
if deployer and results.get("ownable_owner"):
results["deployer_is_owner"] = deployer.lower() == results["ownable_owner"].lower()
# 4. Look for management functions via signature detection
management_sigs = {
"0x8456cb59": "pause()",
"0x3f4ba83a": "unpause()",
"0x42966c68": "burn(address,uint256)",
"0x40c10f19": "mint(address,uint256)",
"0x9dc29fac": "blacklist(address)",
"0xe0021f43": "setBlacklist(address,bool)",
"0x8da5cb5b": "owner()",
}
detected_sigs = _detect_function_signatures(w3, token_address, list(management_sigs.keys()))
results["management_functions"] = [management_sigs[s] for s in detected_sigs if s in management_sigs]
return results
def _get_contract_deployer(w3: Web3, address: str) -> Optional[str]:
"""Get deployer address from the creation transaction."""
try:
# Get creation transaction by scanning block explorer-style:
# Check the contract creation tx via eth_getTransactionReceipt
# The deployer is the 'from' field of the tx that created this contract.
# For Archive Nodes: scan creation via eth_getTransactionByHash from a known deploy tx.
# For non-archive: use block explorer API or internal tx scanning.
# Approach: get code, then scan recent blocks for the CREATE opcode caller.
checksum_addr = Web3.to_checksum_address(address)
# Strategy: check each block for a ContractCreated log or scan deployer list
# Since most RPCs don't have debug_traceTransaction, fall back to
# checking if the deployer can be inferred from the first Transfer event.
transfer_sig = w3.keccak(text="Transfer(address,address,uint256)").hex()
latest = w3.eth.block_number
# Scan last 2000 blocks from genesis area for old tokens, or recent for new ones
# A token created in last 100k blocks = new. Beyond that = can't trace without archive node.
logs = w3.eth.get_logs({
"address": checksum_addr,
"fromBlock": 0,
"toBlock": 1, # Very first block — if token is old, this fails gracefully
"topics": [transfer_sig],
})
# If we got here without error, token is old and we can't trace deployer easily
return None
except Exception as e:
# Most RPCs will error on too-wide block range — fallback to empty
return None
def _detect_function_signatures(w3: Web3, address: str, sigs: List[str]) -> List[str]:
"""Detect which function signatures exist in contract bytecode."""
code = w3.eth.get_code(Web3.to_checksum_address(address))
if code.hex() == "0x":
return []
found = []
code_hex = code.hex()
for sig in sigs:
if sig[2:] in code_hex:
found.append(sig)
return found
Step 2: Liquidity Pool Investigation
Analyze the token's liquidity on DEXes:
- Liquidity lock status — is LP locked, and if so, for how long?
- LP holder concentration — who holds the LP tokens? Is it the deployer?
- Initial liquidity amount — was seeding adequate for the market cap?
- Sniper activity — was there bot-buying in the first block after launch?
Full Honeypot Simulation
The core test for a honeypot token: simulate a buy transaction (swap 0.1 ETH for tokens on a DEX), then simulate a sell of the received tokens back to ETH. If the sell transaction fails gas estimation or reverts, the token is a honeypot.
def simulate_honeypot(
w3: Web3,
token_address: str,
router_address: str = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D", # Uniswap V2 Router
amount_in_eth: float = 0.01,
from_address: str = "0x000000000000000000000000000000000000dEaD",
) -> dict:
"""
Simulate a buy and immediate sell on a DEX to detect honeypot tokens.
Uses eth_call (no gas spent) to test both directions.
Returns dict with buy_success, sell_success, and error details.
"""
token = w3.eth.contract(address=Web3.to_checksum_address(token_address), abi=ERC20_ABI)
router = w3.eth.contract(
address=Web3.to_checksum_address(router_address),
abi=[{"inputs": [{"internalType": "uint256", "name": "amountIn", "type": "uint256"}, {"internalType": "address[]", "name": "path", "type": "address[]"}], "name": "getAmountsOut", "outputs": [{"internalType": "uint256[]", "name": "amounts", "type": "uint256[]"}], "stateMutability": "view", "type": "function"}],
)
weth_address = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
result = {"buy_success": False, "sell_success": False, "is_honeypot": None, "details": {}}
try:
# Step 1: Simulate buy (WETH -> Token)
amount_in_wei = w3.to_wei(amount_in_eth, "ether")
path_buy = [weth_address, token_address]
amounts_out_buy = router.functions.getAmountsOut(amount_in_wei, path_buy).call()
tokens_received = amounts_out_buy[1]
result["buy_success"] = True
result["details"]["tokens_received"] = tokens_received
result["details"]["buy_price_per_token"] = amount_in_wei / tokens_received if tokens_received > 0 else float("inf")
# Check if buy succeeds but gives nearly nothing (tax trap)
if tokens_received < amount_in_wei / 1000: # less than 0.1% expected
result["details"]["buy_warning"] = "Extremely low token output — possible high buy tax or manipulated price"
# Step 2: Simulate sell (Token -> WETH) — the honeypot test
path_sell = [token_address, weth_address]
sell_amount = tokens_received
min_sell = max(1, sell_amount // 1000) # tolerate up to 99.9% sell tax
amounts_out_sell = router.functions.getAmountsOut(sell_amount, path_sell).call()
eth_back = amounts_out_sell[1]
result["sell_success"] = True
result["details"]["eth_back"] = eth_back
result["details"]["sell_tax_pct"] = max(0.0, (1 - eth_back / amount_in_wei) * 100)
result["details"]["is_profitable"] = eth_back > amount_in_wei * 0.5 # get back more than 50% of initial
# Extreme sell tax check
if result["details"]["sell_tax_pct"] > 50:
result["details"]["sell_warning"] = f"Honeypot indicator: sell tax is {result['details']['sell_tax_pct']:.1f}%"
# Step 3: Check for blacklist by testing a known blacklisted address
# Some honeypots block all addresses except whitelisted ones
result["details"]["blacklist_test"] = _check_blacklist_behavior(w3, token_address)
# Step 4: Check if minter can deploy infinite supply
result["details"]["mint_test"] = _check_mint_function(w3, token_address)
except Exception as e:
error_str = str(e)
if "execution reverted" in error_str or "VM Exception" in error_str:
sell_blocked = "cannot" in error_str.lower() or "revert" in error_str.lower()
if not result["buy_success"]:
result["buy_error"] = error_str
else:
result["sell_error"] = error_str
else:
result["error"] = error_str
# Determine honeypot verdict
if result["buy_success"] and not result["sell_success"]:
result["is_honeypot"] = True
result["risk"] = "CRITICAL"
elif result["buy_success"] and result["sell_success"] and result["details"].get("sell_tax_pct", 0) > 30:
result["is_honeypot"] = False
result["risk"] = "HIGH — extreme sell tax"
elif result["buy_success"] and result["sell_success"]:
result["is_honeypot"] = False
result["risk"] = "LOW — both directions succeed"
else:
result["is_honeypot"] = None
result["risk"] = "UNKNOWN — simulation error"
return result
def _check_blacklist_behavior(w3: Web3, token_address: str) -> dict:
"""Check if contract has blacklist functions by signature detection."""
code = w3.eth.get_code(Web3.to_checksum_address(token_address)).hex()
blacklist_sigs = [
"9dc29fac", # blacklist(address)
"10f41093", # setBlacklist(address,bool)
"f9f92be4", # isBlacklisted(address)
"4261f4d8", # addToBlacklist(address)
"5d3a3f1b", # removeFromBlacklist(address)
"ec571fc6", # setBlacklistStatus(address,bool)
"e0021f43", # setExcludedFromFees(address,bool)
"a733e570", # isExcludedFromFees(address)
"b46300ec", # _isExcluded(address)
"e42f6ea6", # listedAddresses(address)
]
found = []
for sig in blacklist_sigs:
if sig in code:
found.append(f"0x{sig}")
return {"blacklist_functions_detected": found, "has_blacklist": len(found) > 0}
def _check_mint_function(w3: Web3, token_address: str) -> dict:
"""Check for mint function signature in contract bytecode."""
code = w3.eth.get_code(Web3.to_checksum_address(token_address)).hex()
mint_sigs = ["40c10f19", "a0712d68", "9a1b1d3c", "d3fc0714", "f2d5d56b"]
found = []
for sig in mint_sigs:
if sig in code:
found.append(f"0x{sig}")
return {"mint_functions_detected": found, "has_mint": len(found) > 0}
Proxy / Upgradeability Detection
Many scam tokens use proxy contracts (ERC-1967, TransparentUpgradeableProxy, BeaconProxy) to allow the deployer to swap the implementation contract after launch — effectively changing all token logic including balances, supply, and transfer restrictions.
def check_proxy_upgradeability(w3: Web3, token_address: str) -> dict:
"""
Detect if a token contract is behind a proxy pattern and read the
implementation address. Checks ERC-1967, Transparent, UUPS, and Beacon patterns.
"""
address = Web3.to_checksum_address(token_address)
result = {
"is_proxy": False,
"proxy_type": None,
"implementation": None,
"beacon": None,
"admin": None,
"can_upgrade": False,
"details": {},
}
# 1. ERC-1967 implementation slot (most common)
try:
impl_bytes = w3.eth.get_storage_at(address, ERC1967_IMPLEMENTATION_SLOT)
impl_address = "0x" + impl_bytes[-20:].hex()
if int(impl_bytes.hex(), 16) > 0:
result["is_proxy"] = True
result["proxy_type"] = "ERC-1967"
result["implementation"] = Web3.to_checksum_address(impl_address)
except Exception:
pass
# 2. Beacon proxy pattern
if not result["is_proxy"]:
try:
beacon_bytes = w3.eth.get_storage_at(address, ERC1967_BEACON_SLOT)
beacon_address = "0x" + beacon_bytes[-20:].hex()
if int(beacon_bytes.hex(), 16) > 0:
result["is_proxy"] = True
result["proxy_type"] = "Beacon"
result["beacon"] = Web3.to_checksum_address(beacon_address)
# Read implementation from beacon (minimal ABI)
beacon_abi = [{"inputs": [], "name": "implementation", "outputs": [{"type": "address"}], "stateMutability": "view", "type": "function"}]
beacon_contract = w3.eth.contract(address=Web3.to_checksum_address(beacon_address), abi=beacon_abi)
result["implementation"] = beacon_contract.functions.implementation().call()
except Exception:
pass
# 3. Admin slot (who can upgrade?)
if result["is_proxy"]:
try:
admin_bytes = w3.eth.get_storage_at(address, ADMIN_SLOT)
admin_addr = "0x" + admin_bytes[-20:].hex()
if int(admin_bytes.hex(), 16) > 0:
result["admin"] = Web3.to_checksum_address(admin_addr)
result["can_upgrade"] = True
except Exception:
pass
# Check if implementation is a contract (i.e., has code)
if result["implementation"]:
impl_code = w3.eth.get_code(Web3.to_checksum_address(result["implementation"]))
result["details"]["impl_has_code"] = len(impl_code) > 0
result["details"]["impl_code_size"] = len(impl_code)
# Check for UUPS (Universal Upgradeable Proxy Standard) — proxy IS the implementation
# UUPS has upgradeTo() in the implementation itself
if result["implementation"]:
try:
impl_contract = w3.eth.contract(
address=Web3.to_checksum_address(result["implementation"]),
abi=[{"inputs": [{"type": "address"}], "name": "upgradeTo", "outputs": [], "stateMutability": "nonpayable", "type": "function"}],
)
impl_contract.functions.upgradeTo(token_address).call({"from": Web3.to_checksum_address(result.get("admin") or "0x0000000000000000000000000000000000000000")})
result["details"]["appears_uups"] = True
except Exception:
result["details"]["appears_uups"] = False
# 4. Check EIP-1167 minimal proxy (CREATE2 clones)
code = w3.eth.get_code(address).hex()
eip1167_prefix = "363d3d373d3d3d363d73"
eip1167_suffix = "5af43d82803e903d91602b57fd5bf3"
if eip1167_prefix in code and eip1167_suffix in code:
result["is_proxy"] = True
result["proxy_type"] = "EIP-1167 Minimal Proxy"
# Extract target address from bytecode
start = code.index(eip1167_prefix) + len(eip1167_prefix)
impl_hex = code[start:start + 40]
result["implementation"] = Web3.to_checksum_address("0x" + impl_hex)
result["details"]["proxy_note"] = "EIP-1167 clone — immutable pointer, cannot upgrade"
# 5. Compare proxy vs implementation events (if both available)
if result["is_proxy"] and result["implementation"]:
result["details"]["upgrade_risk"] = (
"CRITICAL: Admin can replace implementation at any time" if result["can_upgrade"]
else "LOW: Proxy detected but no upgrade capability found"
)
return result
Liquidity Lock Verification
Checks if LP tokens are locked in a vesting/lock contract (Unicrypt, Team Finance, DXlock, or custom) and extracts lock parameters.
def verify_liquidity_lock(
w3: Web3,
lp_token_address: str,
lock_contract_address: Optional[str] = None,
chain: str = "ethereum",
) -> dict:
"""
Verify LP token lock status. If lock_contract_address is known, read from it directly.
Otherwise scan common lock contracts on the chain.
"""
result = {
"lp_locked": False,
"lock_contract": None,
"lock_end_date": None,
"lock_amount": None,
"lock_owner": None,
"can_withdraw_early": None,
"details": {},
}
# Common lock contract ABI fragments
lock_abi_fragments = [
# Unicrypt lock
{"inputs": [{"type": "address"}], "name": "tokenLocks", "outputs": [{"type": "uint256"}, {"type": "uint256"}, {"type": "address"}, {"type": "bool"}], "stateMutability": "view", "type": "function"},
{"inputs": [{"type": "uint256"}], "name": "lockedToken", "outputs": [{"type": "address"}, {"type": "address"}, {"type": "uint256"}, {"type": "uint256"}, {"type": "bool"}], "stateMutability": "view", "type": "function"},
{"inputs": [{"type": "address"}], "name": "getLocks", "outputs": [{"type": "uint256[]"}], "stateMutability": "view", "type": "function"},
# Team Finance (SaaS) generic
{"inputs": [{"type": "address"}, {"type": "address"}], "name": "getLock", "outputs": [{"type": "uint256"}, {"type": "uint256"}, {"type": "address"}], "stateMutability": "view", "type": "function"},
]
# Try known lock contracts on Ethereum
known_lock_contracts = {
"ethereum": [
"0x17e00383A843A9922b8683F8F3D014cA41cC27b5", # Unicrypt v2
"0x663a5c229c09b049e36dCc11a9B0d4a8Eb9db214", # Unicrypt v1
"0xE2fE530C047f2d85298b07D9333C057D1Bf8E77b", # DXlock
"0xa867C7C9e3438E7A5d6267a3f57b3910e00B2C25", # Team Finance
],
"bsc": [
"0x663A5C229c09b049e36DcC11a9B0d4a8Eb9db214", # Unicrypt BSC
"0xD7a3CECD1c95e40C2b0B4F9172DC9C490b6E2A3A", # PinkLock
"0x71B7fF59207eD6a3cb7dE87b2d8a5C09e68a1C5f", # Team Finance BSC
],
}
targets = [lock_contract_address] if lock_contract_address else known_lock_contracts.get(chain, [])
targets = [t for t in targets if t]
for lock_addr in targets:
try:
lock_addr = Web3.to_checksum_address(lock_addr)
lock_code = w3.eth.get_code(lock_addr)
if lock_code.hex() == "0x":
continue
lock_contract = w3.eth.contract(address=lock_addr, abi=lock_abi_fragments[0])
# Try getLocks(address) — returns array of lock IDs
try:
lock_ids = lock_contract.functions.getLocks(lp_token_address).call()
if lock_ids:
for lock_id in lock_ids:
try:
lock_detail = lock_contract.functions.lockedToken(lock_id).call()
result["lp_locked"] = True
result["lock_contract"] = lock_addr
result["lock_amount"] = lock_detail[2]
result["lock_end_date"] = lock_detail[3]
result["details"]["lock_id"] = lock_id
# Determine if lock has expired
current_time = int(time.time())
result["lock_expired"] = current_time > lock_detail[3]
result["details"]["time_remaining_days"] = max(0, (lock_detail[3] - current_time) // 86400)
break
except Exception:
continue
except Exception:
pass
# If getLocks didn't work, try tokenLocks(address)
if not result["lp_locked"]:
try:
lock_info = lock_contract.functions.tokenLocks(lp_token_address).call()
result["lp_locked"] = True
result["lock_contract"] = lock_addr
result["lock_amount"] = lock_info[0]
result["lock_end_date"] = lock_info[1]
result["lock_owner"] = lock_info[2]
except Exception:
pass
except Exception:
continue
if result["lp_locked"] and result["lock_end_date"]:
result["details"]["formatted_end_date"] = time.strftime(
"%Y-%m-%d %H:%M:%S UTC", time.gmtime(result["lock_end_date"])
)
return result
Sniper Bot Detection
Identifies MEV/sniper bots that bought tokens in the first N blocks after the pool was created. These snipers often dump on retail buyers moments later.
def detect_sniper_activity(
w3: Web3,
token_address: str,
pool_creation_block: int,
lookback_blocks: int = 50,
) -> dict:
"""
Analyze the first N blocks after pool creation for sniper bot activity.
Detects sandwich attacks, frontruns, and mass buy patterns.
"""
address = Web3.to_checksum_address(token_address)
result = {
"sniper_detected": False,
"sniper_count": 0,
"snipers": [],
"first_trades": [],
"suspect_patterns": [],
"details": {},
}
# 1. Get all Transfer events from pool creation to pool_creation + lookback_blocks
transfer_event_sig = w3.keccak(text="Transfer(address,address,uint256)").hex()
from_block = max(0, pool_creation_block - 5) # a few blocks before for LP add
to_block = pool_creation_block + lookback_blocks
try:
logs = w3.eth.get_logs({
"address": address,
"fromBlock": from_block,
"toBlock": to_block,
"topics": [transfer_event_sig],
})
except Exception:
# If get_logs range is too large, sample every 5th block
logs = []
for b in range(from_block, to_block, 5):
try:
batch = w3.eth.get_logs({
"address": address,
"fromBlock": b,
"toBlock": min(b + 4, to_block),
"topics": [transfer_event_sig],
})
logs.extend(batch)
except Exception:
continue
# 2. Parse events and identify buyers
token = w3.eth.contract(address=address, abi=ERC20_ABI)
buyer_tx_map = {} # buyer -> (block_number, tx_hash, is_first_buy)
for log in logs:
try:
decoded = token.events.Transfer().process_log(log)
if decoded["args"]["from"] == "0x0000000000000000000000000000000000000000":
# Mint/buy event
buyer = decoded["args"]["to"]
tx_hash = log["transactionHash"].hex()
block_num = log["blockNumber"]
if buyer not in buyer_tx_map:
buyer_tx_map[buyer] = {
"address": buyer,
"first_buy_block": block_num,
"tx_hash": tx_hash,
"amount": decoded["args"]["value"],
"is_sniper_candidate": (block_num - pool_creation_block) <= 5,
}
else:
buyer_tx_map[buyer]["amount"] += decoded["args"]["value"]
except Exception:
continue
# 3. Identify sniper candidates
weth_address = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
for buyer, info in buyer_tx_map.items():
if info["is_sniper_candidate"]:
# Check if this is a known MEV bot (contract with no code = EOA)
code_size = len(w3.eth.get_code(Web3.to_checksum_address(buyer)))
is_contract = code_size > 0
# Check if the buyer sold/dumped shortly after (look at outgoing transfers)
sold_amount = 0
for log in logs:
try:
decoded = token.events.Transfer().process_log(log)
if decoded["args"]["from"].lower() == buyer.lower() and decoded["args"]["to"] != "0x0000000000000000000000000000000000000000":
sold_amount += decoded["args"]["value"]
except Exception:
continue
info["is_contract"] = is_contract
info["sold_amount"] = sold_amount
info["is_dumper"] = sold_amount > info["amount"] * 0.5 # sold more than half
if info["is_dumper"] or is_contract:
result["snipers"].append(info)
result["sniper_count"] += 1
# 4. Detect sandwich attack patterns
# Look for same-block buy-sell pairs with different gas prices
tx_blocks = {}
for log in logs:
block = log["blockNumber"]
tx_hash = log["transactionHash"].hex()
if block not in tx_blocks:
tx_blocks[block] = set()
tx_blocks[block].add(tx_hash)
for block, txs in tx_blocks.items():
if len(txs) >= 3 and (block - pool_creation_block) <= 3:
result["suspect_patterns"].append({
"type": "possible_sandwich",
"block": block,
"tx_count": len(txs),
})
result["sniper_detected"] = result["sniper_count"] > 0
result["details"]["total_unique_buyers"] = len(buyer_tx_map)
return result
Token Distribution Analysis (Gini Coefficient + Top Holders)
Computes the Gini coefficient of token holder distribution — a high Gini (>0.9) indicates extreme concentration typical of scam tokens.
def analyze_holder_distribution(w3: Web3, token_address: str, top_n: int = 10) -> dict:
"""
Compute holder distribution metrics by scanning Transfer events.
Returns Gini coefficient, top holder list, and concentration percentages.
"""
address = Web3.to_checksum_address(token_address)
token = w3.eth.contract(address=address, abi=ERC20_ABI)
result = {
"total_holders": 0,
"gini_coefficient": None,
"top_holders": [],
"top10_concentration_pct": 0.0,
"top1_concentration_pct": 0.0,
"supply_distribution": "UNKNOWN",
"details": {},
}
try:
total_supply = token.functions.totalSupply().call()
result["details"]["total_supply"] = total_supply
except Exception:
total_supply = 0
# Scan Transfer events to compute balances
transfer_sig = w3.keccak(text="Transfer(address,address,uint256)").hex()
balances = {}
# Get latest block
latest = w3.eth.block_number
# Scan in chunks to avoid RPC limits
chunk_size = 100000
from_block = max(0, latest - 500000) # last 500k blocks, adjust for recent tokens on new chains
while from_block < latest:
to_block = min(from_block + chunk_size - 1, latest)
try:
logs = w3.eth.get_logs({
"address": address,
"fromBlock": from_block,
"toBlock": to_block,
"topics": [transfer_sig],
})
for log_entry in logs:
try:
decoded = token.events.Transfer().process_log(log_entry)
fr = decoded["args"]["from"].lower()
to = decoded["args"]["to"].lower()
val = decoded["args"]["value"]
if fr == "0x0000000000000000000000000000000000000000" or fr == "0x0000000000000000000000000000000000000001":
# Mint — skip, balance starts at receiving
pass
else:
balances[fr] = balances.get(fr, 0) - val
if balances[fr] <= 0:
del balances[fr]
balances[to] = balances.get(to, 0) + val
except Exception:
continue
except Exception:
# If chunk fails (too large), halve it
chunk_size //= 2
if chunk_size < 1000:
break
continue
from_block = to_block + 1
# Filter zero/negligible balances
min_balance = total_supply / 1_000_000 if total_supply > 0 else 0
holders = {addr: bal for addr, bal in balances.items() if bal >= min_balance}
if not holders:
result["error"] = "Could not reconstruct holder balances from event logs"
return result
result["total_holders"] = len(holders)
sorted_holders = sorted(holders.items(), key=lambda x: -x[1])
# Top holders
result["top_holders"] = [
{"address": addr, "balance": bal, "pct": (bal / total_supply * 100) if total_supply > 0 else 0}
for addr, bal in sorted_holders[:top_n]
]
# Concentration percentages
if total_supply > 0:
top1_bal = sorted_holders[0][1] if sorted_holders else 0
result["top1_concentration_pct"] = top1_bal / total_supply * 100
top10_bal = sum(b for _, b in sorted_holders[:10])
result["top10_concentration_pct"] = top10_bal / total_supply * 100
# Gini coefficient
values = sorted([b for _, b in sorted_holders if b > 0])
n = len(values)
if n > 1:
cumulative = [sum(values[:i+1]) for i in range(n)]
# Gini = 2 * sum(i * y_i) / (n * sum(y_i)) - (n+1)/n
numerator = sum((i + 1) * v for i, v in enumerate(values))
denominator = n * sum(values)
gini = (2 * numerator / denominator) - (n + 1) / n
result["gini_coefficient"] = round(gini, 4)
# Distribution classification
if result["top1_concentration_pct"] >= 90:
result["supply_distribution"] = "CRITICAL — single holder controls >90%"
elif result["top10_concentration_pct"] >= 90:
result["supply_distribution"] = "HIGH — top 10 control >90%"
elif result["top10_concentration_pct"] >= 50:
result["supply_distribution"] = "MODERATE — top 10 control >50%"
else:
result["supply_distribution"] = "HEALTHY — distributed"
return result
Wash Trading Detection (NFT)
Detects circular trading patterns (A→B→C→A cycles) and same-wallet flipping in NFT sales data.
def detect_wash_trading(
sales_data: List[Dict[str, Any]],
min_cycle_length: int = 3,
max_cycle_length: int = 10,
) -> dict:
"""
Detect wash trading patterns in NFT sales data.
Input: list of dicts with {seller, buyer, token_id, price, timestamp, marketplace}
Detects: circular trades, same-wallet flipping, and self-dealing.
"""
import networkx as nx
from collections import defaultdict
from itertools import combinations
result = {
"has_wash_trading": False,
"circular_trades": [],
"same_wallet_flips": [],
"whale_wallets": [],
"wash_volume": 0,
"total_volume": sum(s.get("price", 0) for s in sales_data),
"wash_volume_pct": 0.0,
"details": {},
}
if not sales_data:
return result
result["details"]["total_trades"] = len(sales_data)
# 1. Build directed graph of trades
G = nx.DiGraph()
for sale in sales_data:
seller = sale.get("seller", "").lower()
buyer = sale.get("buyer", "").lower()
price = sale.get("price", 0)
token_id = sale.get("token_id", "")
ts = sale.get("timestamp", 0)
G.add_edge(seller, buyer, price=price, token_id=token_id, timestamp=ts)
# 2. Detect cycles (circular trading)
try:
cycles = list(nx.simple_cycles(G))
except nx.NetworkXNoCycle:
cycles = []
# Filter by cycle length
filtered_cycles = [c for c in cycles if min_cycle_length <= len(c) <= max_cycle_length]
result["circular_trades"] = [
{"cycle": [addr for addr in cycle], "length": len(cycle)}
for cycle in filtered_cycles
]
# 3. Detect same-wallet flipping (same wallet appearing as both buyer and seller across trades)
wallet_activity = defaultdict(lambda: {"buys": 0, "sells": 0, "total_volume": 0, "token_ids": set()})
for sale in sales_data:
seller = sale.get("seller", "").lower()
buyer = sale.get("buyer", "").lower()
price = sale.get("price", 0)
token_id = sale.get("token_id", "")
wallet_activity[seller]["sells"] += 1
wallet_activity[seller]["total_volume"] -= price # selling loses token, gains money
wallet_activity[buyer]["buys"] += 1
wallet_activity[buyer]["total_volume"] += price
if token_id:
wallet_activity[seller]["token_ids"].discard(token_id)
wallet_activity[buyer]["token_ids"].add(token_id)
# Wallets with high buy-sell ratio across same tokens = wash traders
for addr, activity in wallet_activity.items():
overlap = len(activity["token_ids"])
total_trades = activity["buys"] + activity["sells"]
if total_trades >= 5 and overlap >= 3:
result["whale_wallets"].append({
"address": addr,
"buys": ac
…(truncated)
1---2name: token-nft-scam-investigation3description: Use when investigate token and NFT scams including rug pulls, honeypot4 tokens, pump-and-dump schemes, wash trading, and NFT floor manipulation to identify5 fraudulent patterns and trace perpetrator wallets. Use when analyzing suspicious6 token launches, investigating NFT fraud, or detecting market manipulation.7domain: cybersecurity8author: oyi779license: Apache-2.010subdomain: blockchain-security11tags:12- blockchain13- token14- nft15- scam16- investigation17- rug-pull18- honeypot19- wash-trading20- fraud21- money22version: '1.0'23category: cybersecurity24metadata:25 source: https://skillmd.com/skills/oyi77/token-nft-scam-investigation26---272829# Token & NFT Scam Investigation3031## Overview3233Token and NFT scams — including rug pulls, honeypot tokens, pump-and-dump schemes, wash trading, and floor manipulation — account for the majority of blockchain fraud by victim count. Unlike protocol exploits that target code flaws, these scams target retail investors through deception and market manipulation. This skill covers analyzing token contracts for honeypot mechanisms, detecting wash trading patterns on NFT marketplaces, investigating rug pull setups (liquidity removal, mint controls, proxy upgrades), identifying pump-and-dump coordination, and tracing scam proceeds. It provides working Python code for each detection category, real case studies with exploitable contract addresses, and a monetization framework for selling investigation services.3435## When to Use3637**Trigger phrases:**38- "token scam investigation"39- "nft scam investigation"40- "Analyze a rug pull"41- "Check if a token is a honeypot"42- "Detect wash trading in an NFT collection"43- "is this token safe to buy"44- "check token contract for honeypot"45- "investigate NFT wash trading"46- "trace rug pull proceeds"47- "check if this is a scam token"48- "due diligence on token launch"49- "verify liquidity lock"5051- When investigating a suspicious token launch for potential scam indicators52- When analyzing an NFT collection for wash trading or price manipulation53- When tracing rug pull or pump-and-dump proceeds54- When building automated scam detection for token/NFT due diligence55- When gathering evidence for a fraud complaint or bounty submission56- When performing pre-purchase due diligence on a new token or NFT collection57- When investigating a project that claims to have been "rugged" for insurance claims58- When conducting competitive intelligence on scam operations5960## When NOT to Use6162- You need to trace stolen funds from a hack or exploit (use onchain-transaction-forensics skill)63- You need to analyze a DeFi protocol's smart contract vulnerability (use defi-incident-analysis skill)64- Task requires recovering lost funds or filing a police report (use proper legal channels)65- You are the project owner needing to prove your token is legitimate (use a different due diligence process)66- The investigation requires access to private sale or KYC data you don't have67- You need to audit a complex DeFi protocol's tokenomics model (use smart-contract-exploiter skill)68- You are building a trading bot that needs MEV protection analysis (use onchain-transaction-forensics skill)69- The token is a well-known blue-chip project and you're looking for FUD evidence7071## Prerequisites7273- Python 3.8+ with web3.py (>=6.0), requests, pandas, numpy, networkx74- Ethereum RPC node access (Alchemy, Infura, or local node) or chain-specific node (BSC, Polygon, etc.)75- Block explorer API key (Etherscan, BscScan, Polygonscan) for historical event queries76- Solidity understanding (for contract-level scam analysis including proxy patterns and fee mechanisms)77- NFT marketplace API access (OpenSea, Blur, LooksRare) for trading data78- Familiarity with DEX concepts (Uniswap v2/v3, PancakeSwap, LP tokens)79- git (for cloning known scam contract source code from audit repositories)8081## Core Workflow8283```python84# Entry point: run all scam checks against a token contract85from web3 import Web386from typing import Optional, Dict, Any, List, Tuple87from dataclasses import dataclass, field88import json89import time90import requests9192# Configuration93ETHERSCAN_API_KEY = "YOUR_API_KEY"94RPC_URL = "https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY"9596w3 = Web3(Web3.HTTPProvider(RPC_URL))9798# Standard ERC-20 ABI fragments99ERC20_ABI = [100 {"inputs": [], "name": "name", "outputs": [{"type": "string"}], "stateMutability": "view", "type": "function"},101 {"inputs": [], "name": "symbol", "outputs": [{"type": "string"}], "stateMutability": "view", "type": "function"},102 {"inputs": [], "name": "decimals", "outputs": [{"type": "uint8"}], "stateMutability": "view", "type": "function"},103 {"inputs": [], "name": "totalSupply", "outputs": [{"type": "uint256"}], "stateMutability": "view", "type": "function"},104 {"inputs": [{"type": "address"}], "name": "balanceOf", "outputs": [{"type": "uint256"}], "stateMutability": "view", "type": "function"},105 {"inputs": [{"type": "address"}, {"type": "address"}], "name": "allowance", "outputs": [{"type": "uint256"}], "stateMutability": "view", "type": "function"},106 # Transfer event107 {"anonymous": False, "inputs": [{"indexed": True, "name": "from", "type": "address"}, {"indexed": True, "name": "to", "type": "address"}, {"indexed": False, "name": "value", "type": "uint256"}], "name": "Transfer", "type": "event"},108]109110# Ownership ABIs to test111OWNERSHIP_ABIS = {112 "ownable": [113 {"inputs": [], "name": "owner", "outputs": [{"type": "address"}], "stateMutability": "view", "type": "function"},114 {"inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function"},115 ],116 "access_control": [117 {"inputs": [{"type": "bytes32"}], "name": "hasRole", "outputs": [{"type": "bool"}], "stateMutability": "view", "type": "function"},118 {"inputs": [], "name": "DEFAULT_ADMIN_ROLE", "outputs": [{"type": "bytes32"}], "stateMutability": "view", "type": "function"},119 ],120}121122# ERC-1967 proxy storage slots (beige paper)123ERC1967_IMPLEMENTATION_SLOT = "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"124ERC1967_BEACON_SLOT = "0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50"125ADMIN_SLOT = "0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103"126127128def run_scam_check(address: str, rpc_url: str = RPC_URL) -> dict:129 """Run a comprehensive scam check on a token contract."""130 w3_local = Web3(Web3.HTTPProvider(rpc_url))131 checks = {132 "basic_info": check_basic_info(w3_local, address),133 "honeypot": simulate_honeypot(w3_local, address),134 "proxy": check_proxy_upgradeability(w3_local, address),135 "ownership": check_all_ownership_interfaces(w3_local, address),136 "holder_distribution": analyze_holder_distribution(w3_local, address),137 "approval_risks": check_approval_abuse(w3_local, address),138 }139 return checks140141```142143### Step 1: Token Contract Analysis144145Examine the token contract for scam indicators:146- **Honeypot detection** — can the token be bought but not sold? Check for blacklist functions, transfer fee manipulation, or balance restrictions147- **Ownership not renounced** — deployer can still mint, pause transfers, or blacklist addresses148- **Suspicious fee structure** — extremely high buy/sell taxes that benefit the deployer149- **Honeypot simulation** — simulate a buy and sell transaction to verify both succeed150- **Proxy/upgradeable pattern** — contract can be upgraded to malicious logic later151- **Mint function** — unlimited mint capability that dilutes holders152- **TOP10 holder concentration** — if 90%+ supply is in a few addresses, risk of dump153154```python155def check_basic_info(w3: Web3, token_address: str) -> dict:156 """Fetch basic ERC-20 token metadata and catch common ABI failures."""157 contract = w3.eth.contract(address=token_address, abi=ERC20_ABI)158 result = {}159 for field in ["name", "symbol", "decimals", "totalSupply"]:160 try:161 fn = getattr(contract.functions, field)162 result[field] = fn().call()163 except Exception as e:164 result[field] = f"ERROR: {e}"165 return result166167168def check_all_ownership_interfaces(w3: Web3, token_address: str) -> dict:169 """Probe multiple ownership interfaces and check renounced status."""170 results = {"interfaces_found": []}171172 # 1. Ownable (OpenZeppelin standard)173 try:174 o_contract = w3.eth.contract(address=token_address, abi=OWNERSHIP_ABIS["ownable"])175 owner = o_contract.functions.owner().call()176 is_renounced = owner == "0x0000000000000000000000000000000000000000" or owner == "0x0000000000000000000000000000000000000001"177 results["ownable_owner"] = owner178 results["ownable_renounced"] = is_renounced179 results["interfaces_found"].append("Ownable")180 except Exception:181 results["ownable_owner"] = None182 results["ownable_renounced"] = None183184 # 2. AccessControl (OpenZeppelin v4+)185 try:186 ac_contract = w3.eth.contract(address=token_address, abi=OWNERSHIP_ABIS["access_control"])187 admin_role = ac_contract.functions.DEFAULT_ADMIN_ROLE().call()188 # Try to find the admin role holder via event log189 results["access_control_found"] = True190 results["default_admin_role"] = admin_role.hex()191 results["interfaces_found"].append("AccessControl")192 except Exception:193 results["access_control_found"] = False194195 # 3. Check if deployer still has a special "minter" style role196 deployer = _get_contract_deployer(w3, token_address)197 if deployer and results.get("ownable_owner"):198 results["deployer_is_owner"] = deployer.lower() == results["ownable_owner"].lower()199200 # 4. Look for management functions via signature detection201 management_sigs = {202 "0x8456cb59": "pause()",203 "0x3f4ba83a": "unpause()",204 "0x42966c68": "burn(address,uint256)",205 "0x40c10f19": "mint(address,uint256)",206 "0x9dc29fac": "blacklist(address)",207 "0xe0021f43": "setBlacklist(address,bool)",208 "0x8da5cb5b": "owner()",209 }210 detected_sigs = _detect_function_signatures(w3, token_address, list(management_sigs.keys()))211 results["management_functions"] = [management_sigs[s] for s in detected_sigs if s in management_sigs]212213 return results214215216def _get_contract_deployer(w3: Web3, address: str) -> Optional[str]:217 """Get deployer address from the creation transaction."""218 try:219 # Get creation transaction by scanning block explorer-style:220 # Check the contract creation tx via eth_getTransactionReceipt221 # The deployer is the 'from' field of the tx that created this contract.222 # For Archive Nodes: scan creation via eth_getTransactionByHash from a known deploy tx.223 # For non-archive: use block explorer API or internal tx scanning.224 # Approach: get code, then scan recent blocks for the CREATE opcode caller.225 checksum_addr = Web3.to_checksum_address(address)226 # Strategy: check each block for a ContractCreated log or scan deployer list227 # Since most RPCs don't have debug_traceTransaction, fall back to228 # checking if the deployer can be inferred from the first Transfer event.229 transfer_sig = w3.keccak(text="Transfer(address,address,uint256)").hex()230 latest = w3.eth.block_number231 # Scan last 2000 blocks from genesis area for old tokens, or recent for new ones232 # A token created in last 100k blocks = new. Beyond that = can't trace without archive node.233 logs = w3.eth.get_logs({234 "address": checksum_addr,235 "fromBlock": 0,236 "toBlock": 1, # Very first block — if token is old, this fails gracefully237 "topics": [transfer_sig],238 })239 # If we got here without error, token is old and we can't trace deployer easily240 return None241 except Exception as e:242 # Most RPCs will error on too-wide block range — fallback to empty243 return None244245246def _detect_function_signatures(w3: Web3, address: str, sigs: List[str]) -> List[str]:247 """Detect which function signatures exist in contract bytecode."""248 code = w3.eth.get_code(Web3.to_checksum_address(address))249 if code.hex() == "0x":250 return []251 found = []252 code_hex = code.hex()253 for sig in sigs:254 if sig[2:] in code_hex:255 found.append(sig)256 return found257```258259### Step 2: Liquidity Pool Investigation260261Analyze the token's liquidity on DEXes:262- **Liquidity lock status** — is LP locked, and if so, for how long?263- **LP holder concentration** — who holds the LP tokens? Is it the deployer?264- **Initial liquidity amount** — was seeding adequate for the market cap?265- **Sniper activity** — was there bot-buying in the first block after launch?266267## Full Honeypot Simulation268269The core test for a honeypot token: simulate a buy transaction (swap 0.1 ETH for tokens on a DEX), then simulate a sell of the received tokens back to ETH. If the sell transaction fails gas estimation or reverts, the token is a honeypot.270271```python272def simulate_honeypot(273 w3: Web3,274 token_address: str,275 router_address: str = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D", # Uniswap V2 Router276 amount_in_eth: float = 0.01,277 from_address: str = "0x000000000000000000000000000000000000dEaD",278) -> dict:279 """280 Simulate a buy and immediate sell on a DEX to detect honeypot tokens.281 Uses eth_call (no gas spent) to test both directions.282 Returns dict with buy_success, sell_success, and error details.283 """284 token = w3.eth.contract(address=Web3.to_checksum_address(token_address), abi=ERC20_ABI)285 router = w3.eth.contract(286 address=Web3.to_checksum_address(router_address),287 abi=[{"inputs": [{"internalType": "uint256", "name": "amountIn", "type": "uint256"}, {"internalType": "address[]", "name": "path", "type": "address[]"}], "name": "getAmountsOut", "outputs": [{"internalType": "uint256[]", "name": "amounts", "type": "uint256[]"}], "stateMutability": "view", "type": "function"}],288 )289 weth_address = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"290 result = {"buy_success": False, "sell_success": False, "is_honeypot": None, "details": {}}291292 try:293 # Step 1: Simulate buy (WETH -> Token)294 amount_in_wei = w3.to_wei(amount_in_eth, "ether")295 path_buy = [weth_address, token_address]296 amounts_out_buy = router.functions.getAmountsOut(amount_in_wei, path_buy).call()297 tokens_received = amounts_out_buy[1]298 result["buy_success"] = True299 result["details"]["tokens_received"] = tokens_received300 result["details"]["buy_price_per_token"] = amount_in_wei / tokens_received if tokens_received > 0 else float("inf")301302 # Check if buy succeeds but gives nearly nothing (tax trap)303 if tokens_received < amount_in_wei / 1000: # less than 0.1% expected304 result["details"]["buy_warning"] = "Extremely low token output — possible high buy tax or manipulated price"305306 # Step 2: Simulate sell (Token -> WETH) — the honeypot test307 path_sell = [token_address, weth_address]308 sell_amount = tokens_received309 min_sell = max(1, sell_amount // 1000) # tolerate up to 99.9% sell tax310311 amounts_out_sell = router.functions.getAmountsOut(sell_amount, path_sell).call()312 eth_back = amounts_out_sell[1]313 result["sell_success"] = True314 result["details"]["eth_back"] = eth_back315 result["details"]["sell_tax_pct"] = max(0.0, (1 - eth_back / amount_in_wei) * 100)316 result["details"]["is_profitable"] = eth_back > amount_in_wei * 0.5 # get back more than 50% of initial317318 # Extreme sell tax check319 if result["details"]["sell_tax_pct"] > 50:320 result["details"]["sell_warning"] = f"Honeypot indicator: sell tax is {result['details']['sell_tax_pct']:.1f}%"321322 # Step 3: Check for blacklist by testing a known blacklisted address323 # Some honeypots block all addresses except whitelisted ones324 result["details"]["blacklist_test"] = _check_blacklist_behavior(w3, token_address)325326 # Step 4: Check if minter can deploy infinite supply327 result["details"]["mint_test"] = _check_mint_function(w3, token_address)328329 except Exception as e:330 error_str = str(e)331 if "execution reverted" in error_str or "VM Exception" in error_str:332 sell_blocked = "cannot" in error_str.lower() or "revert" in error_str.lower()333 if not result["buy_success"]:334 result["buy_error"] = error_str335 else:336 result["sell_error"] = error_str337 else:338 result["error"] = error_str339340 # Determine honeypot verdict341 if result["buy_success"] and not result["sell_success"]:342 result["is_honeypot"] = True343 result["risk"] = "CRITICAL"344 elif result["buy_success"] and result["sell_success"] and result["details"].get("sell_tax_pct", 0) > 30:345 result["is_honeypot"] = False346 result["risk"] = "HIGH — extreme sell tax"347 elif result["buy_success"] and result["sell_success"]:348 result["is_honeypot"] = False349 result["risk"] = "LOW — both directions succeed"350 else:351 result["is_honeypot"] = None352 result["risk"] = "UNKNOWN — simulation error"353354 return result355356357def _check_blacklist_behavior(w3: Web3, token_address: str) -> dict:358 """Check if contract has blacklist functions by signature detection."""359 code = w3.eth.get_code(Web3.to_checksum_address(token_address)).hex()360 blacklist_sigs = [361 "9dc29fac", # blacklist(address)362 "10f41093", # setBlacklist(address,bool)363 "f9f92be4", # isBlacklisted(address)364 "4261f4d8", # addToBlacklist(address)365 "5d3a3f1b", # removeFromBlacklist(address)366 "ec571fc6", # setBlacklistStatus(address,bool)367 "e0021f43", # setExcludedFromFees(address,bool)368 "a733e570", # isExcludedFromFees(address)369 "b46300ec", # _isExcluded(address)370 "e42f6ea6", # listedAddresses(address)371 ]372 found = []373 for sig in blacklist_sigs:374 if sig in code:375 found.append(f"0x{sig}")376 return {"blacklist_functions_detected": found, "has_blacklist": len(found) > 0}377378379def _check_mint_function(w3: Web3, token_address: str) -> dict:380 """Check for mint function signature in contract bytecode."""381 code = w3.eth.get_code(Web3.to_checksum_address(token_address)).hex()382 mint_sigs = ["40c10f19", "a0712d68", "9a1b1d3c", "d3fc0714", "f2d5d56b"]383 found = []384 for sig in mint_sigs:385 if sig in code:386 found.append(f"0x{sig}")387 return {"mint_functions_detected": found, "has_mint": len(found) > 0}388```389390## Proxy / Upgradeability Detection391392Many scam tokens use proxy contracts (ERC-1967, TransparentUpgradeableProxy, BeaconProxy) to allow the deployer to swap the implementation contract after launch — effectively changing all token logic including balances, supply, and transfer restrictions.393394```python395def check_proxy_upgradeability(w3: Web3, token_address: str) -> dict:396 """397 Detect if a token contract is behind a proxy pattern and read the398 implementation address. Checks ERC-1967, Transparent, UUPS, and Beacon patterns.399 """400 address = Web3.to_checksum_address(token_address)401 result = {402 "is_proxy": False,403 "proxy_type": None,404 "implementation": None,405 "beacon": None,406 "admin": None,407 "can_upgrade": False,408 "details": {},409 }410411 # 1. ERC-1967 implementation slot (most common)412 try:413 impl_bytes = w3.eth.get_storage_at(address, ERC1967_IMPLEMENTATION_SLOT)414 impl_address = "0x" + impl_bytes[-20:].hex()415 if int(impl_bytes.hex(), 16) > 0:416 result["is_proxy"] = True417 result["proxy_type"] = "ERC-1967"418 result["implementation"] = Web3.to_checksum_address(impl_address)419 except Exception:420 pass421422 # 2. Beacon proxy pattern423 if not result["is_proxy"]:424 try:425 beacon_bytes = w3.eth.get_storage_at(address, ERC1967_BEACON_SLOT)426 beacon_address = "0x" + beacon_bytes[-20:].hex()427 if int(beacon_bytes.hex(), 16) > 0:428 result["is_proxy"] = True429 result["proxy_type"] = "Beacon"430 result["beacon"] = Web3.to_checksum_address(beacon_address)431 # Read implementation from beacon (minimal ABI)432 beacon_abi = [{"inputs": [], "name": "implementation", "outputs": [{"type": "address"}], "stateMutability": "view", "type": "function"}]433 beacon_contract = w3.eth.contract(address=Web3.to_checksum_address(beacon_address), abi=beacon_abi)434 result["implementation"] = beacon_contract.functions.implementation().call()435 except Exception:436 pass437438 # 3. Admin slot (who can upgrade?)439 if result["is_proxy"]:440 try:441 admin_bytes = w3.eth.get_storage_at(address, ADMIN_SLOT)442 admin_addr = "0x" + admin_bytes[-20:].hex()443 if int(admin_bytes.hex(), 16) > 0:444 result["admin"] = Web3.to_checksum_address(admin_addr)445 result["can_upgrade"] = True446 except Exception:447 pass448449 # Check if implementation is a contract (i.e., has code)450 if result["implementation"]:451 impl_code = w3.eth.get_code(Web3.to_checksum_address(result["implementation"]))452 result["details"]["impl_has_code"] = len(impl_code) > 0453 result["details"]["impl_code_size"] = len(impl_code)454455 # Check for UUPS (Universal Upgradeable Proxy Standard) — proxy IS the implementation456 # UUPS has upgradeTo() in the implementation itself457 if result["implementation"]:458 try:459 impl_contract = w3.eth.contract(460 address=Web3.to_checksum_address(result["implementation"]),461 abi=[{"inputs": [{"type": "address"}], "name": "upgradeTo", "outputs": [], "stateMutability": "nonpayable", "type": "function"}],462 )463 impl_contract.functions.upgradeTo(token_address).call({"from": Web3.to_checksum_address(result.get("admin") or "0x0000000000000000000000000000000000000000")})464 result["details"]["appears_uups"] = True465 except Exception:466 result["details"]["appears_uups"] = False467468 # 4. Check EIP-1167 minimal proxy (CREATE2 clones)469 code = w3.eth.get_code(address).hex()470 eip1167_prefix = "363d3d373d3d3d363d73"471 eip1167_suffix = "5af43d82803e903d91602b57fd5bf3"472 if eip1167_prefix in code and eip1167_suffix in code:473 result["is_proxy"] = True474 result["proxy_type"] = "EIP-1167 Minimal Proxy"475 # Extract target address from bytecode476 start = code.index(eip1167_prefix) + len(eip1167_prefix)477 impl_hex = code[start:start + 40]478 result["implementation"] = Web3.to_checksum_address("0x" + impl_hex)479 result["details"]["proxy_note"] = "EIP-1167 clone — immutable pointer, cannot upgrade"480481 # 5. Compare proxy vs implementation events (if both available)482 if result["is_proxy"] and result["implementation"]:483 result["details"]["upgrade_risk"] = (484 "CRITICAL: Admin can replace implementation at any time" if result["can_upgrade"]485 else "LOW: Proxy detected but no upgrade capability found"486 )487488 return result489```490491## Liquidity Lock Verification492493Checks if LP tokens are locked in a vesting/lock contract (Unicrypt, Team Finance, DXlock, or custom) and extracts lock parameters.494495```python496def verify_liquidity_lock(497 w3: Web3,498 lp_token_address: str,499 lock_contract_address: Optional[str] = None,500 chain: str = "ethereum",501) -> dict:502 """503 Verify LP token lock status. If lock_contract_address is known, read from it directly.504 Otherwise scan common lock contracts on the chain.505 """506 result = {507 "lp_locked": False,508 "lock_contract": None,509 "lock_end_date": None,510 "lock_amount": None,511 "lock_owner": None,512 "can_withdraw_early": None,513 "details": {},514 }515516 # Common lock contract ABI fragments517 lock_abi_fragments = [518 # Unicrypt lock519 {"inputs": [{"type": "address"}], "name": "tokenLocks", "outputs": [{"type": "uint256"}, {"type": "uint256"}, {"type": "address"}, {"type": "bool"}], "stateMutability": "view", "type": "function"},520 {"inputs": [{"type": "uint256"}], "name": "lockedToken", "outputs": [{"type": "address"}, {"type": "address"}, {"type": "uint256"}, {"type": "uint256"}, {"type": "bool"}], "stateMutability": "view", "type": "function"},521 {"inputs": [{"type": "address"}], "name": "getLocks", "outputs": [{"type": "uint256[]"}], "stateMutability": "view", "type": "function"},522 # Team Finance (SaaS) generic523 {"inputs": [{"type": "address"}, {"type": "address"}], "name": "getLock", "outputs": [{"type": "uint256"}, {"type": "uint256"}, {"type": "address"}], "stateMutability": "view", "type": "function"},524 ]525526 # Try known lock contracts on Ethereum527 known_lock_contracts = {528 "ethereum": [529 "0x17e00383A843A9922b8683F8F3D014cA41cC27b5", # Unicrypt v2530 "0x663a5c229c09b049e36dCc11a9B0d4a8Eb9db214", # Unicrypt v1531 "0xE2fE530C047f2d85298b07D9333C057D1Bf8E77b", # DXlock532 "0xa867C7C9e3438E7A5d6267a3f57b3910e00B2C25", # Team Finance533 ],534 "bsc": [535 "0x663A5C229c09b049e36DcC11a9B0d4a8Eb9db214", # Unicrypt BSC536 "0xD7a3CECD1c95e40C2b0B4F9172DC9C490b6E2A3A", # PinkLock537 "0x71B7fF59207eD6a3cb7dE87b2d8a5C09e68a1C5f", # Team Finance BSC538 ],539 }540541 targets = [lock_contract_address] if lock_contract_address else known_lock_contracts.get(chain, [])542 targets = [t for t in targets if t]543544 for lock_addr in targets:545 try:546 lock_addr = Web3.to_checksum_address(lock_addr)547 lock_code = w3.eth.get_code(lock_addr)548 if lock_code.hex() == "0x":549 continue550 lock_contract = w3.eth.contract(address=lock_addr, abi=lock_abi_fragments[0])551552 # Try getLocks(address) — returns array of lock IDs553 try:554 lock_ids = lock_contract.functions.getLocks(lp_token_address).call()555 if lock_ids:556 for lock_id in lock_ids:557 try:558 lock_detail = lock_contract.functions.lockedToken(lock_id).call()559 result["lp_locked"] = True560 result["lock_contract"] = lock_addr561 result["lock_amount"] = lock_detail[2]562 result["lock_end_date"] = lock_detail[3]563 result["details"]["lock_id"] = lock_id564 # Determine if lock has expired565 current_time = int(time.time())566 result["lock_expired"] = current_time > lock_detail[3]567 result["details"]["time_remaining_days"] = max(0, (lock_detail[3] - current_time) // 86400)568 break569 except Exception:570 continue571 except Exception:572 pass573574 # If getLocks didn't work, try tokenLocks(address)575 if not result["lp_locked"]:576 try:577 lock_info = lock_contract.functions.tokenLocks(lp_token_address).call()578 result["lp_locked"] = True579 result["lock_contract"] = lock_addr580 result["lock_amount"] = lock_info[0]581 result["lock_end_date"] = lock_info[1]582 result["lock_owner"] = lock_info[2]583 except Exception:584 pass585586 except Exception:587 continue588589 if result["lp_locked"] and result["lock_end_date"]:590 result["details"]["formatted_end_date"] = time.strftime(591 "%Y-%m-%d %H:%M:%S UTC", time.gmtime(result["lock_end_date"])592 )593594 return result595```596597## Sniper Bot Detection598599Identifies MEV/sniper bots that bought tokens in the first N blocks after the pool was created. These snipers often dump on retail buyers moments later.600601```python602def detect_sniper_activity(603 w3: Web3,604 token_address: str,605 pool_creation_block: int,606 lookback_blocks: int = 50,607) -> dict:608 """609 Analyze the first N blocks after pool creation for sniper bot activity.610 Detects sandwich attacks, frontruns, and mass buy patterns.611 """612 address = Web3.to_checksum_address(token_address)613 result = {614 "sniper_detected": False,615 "sniper_count": 0,616 "snipers": [],617 "first_trades": [],618 "suspect_patterns": [],619 "details": {},620 }621622 # 1. Get all Transfer events from pool creation to pool_creation + lookback_blocks623 transfer_event_sig = w3.keccak(text="Transfer(address,address,uint256)").hex()624 from_block = max(0, pool_creation_block - 5) # a few blocks before for LP add625 to_block = pool_creation_block + lookback_blocks626627 try:628 logs = w3.eth.get_logs({629 "address": address,630 "fromBlock": from_block,631 "toBlock": to_block,632 "topics": [transfer_event_sig],633 })634 except Exception:635 # If get_logs range is too large, sample every 5th block636 logs = []637 for b in range(from_block, to_block, 5):638 try:639 batch = w3.eth.get_logs({640 "address": address,641 "fromBlock": b,642 "toBlock": min(b + 4, to_block),643 "topics": [transfer_event_sig],644 })645 logs.extend(batch)646 except Exception:647 continue648649 # 2. Parse events and identify buyers650 token = w3.eth.contract(address=address, abi=ERC20_ABI)651 buyer_tx_map = {} # buyer -> (block_number, tx_hash, is_first_buy)652653 for log in logs:654 try:655 decoded = token.events.Transfer().process_log(log)656 if decoded["args"]["from"] == "0x0000000000000000000000000000000000000000":657 # Mint/buy event658 buyer = decoded["args"]["to"]659 tx_hash = log["transactionHash"].hex()660 block_num = log["blockNumber"]661 if buyer not in buyer_tx_map:662 buyer_tx_map[buyer] = {663 "address": buyer,664 "first_buy_block": block_num,665 "tx_hash": tx_hash,666 "amount": decoded["args"]["value"],667 "is_sniper_candidate": (block_num - pool_creation_block) <= 5,668 }669 else:670 buyer_tx_map[buyer]["amount"] += decoded["args"]["value"]671 except Exception:672 continue673674 # 3. Identify sniper candidates675 weth_address = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"676677 for buyer, info in buyer_tx_map.items():678 if info["is_sniper_candidate"]:679 # Check if this is a known MEV bot (contract with no code = EOA)680 code_size = len(w3.eth.get_code(Web3.to_checksum_address(buyer)))681 is_contract = code_size > 0682683 # Check if the buyer sold/dumped shortly after (look at outgoing transfers)684 sold_amount = 0685 for log in logs:686 try:687 decoded = token.events.Transfer().process_log(log)688 if decoded["args"]["from"].lower() == buyer.lower() and decoded["args"]["to"] != "0x0000000000000000000000000000000000000000":689 sold_amount += decoded["args"]["value"]690 except Exception:691 continue692693 info["is_contract"] = is_contract694 info["sold_amount"] = sold_amount695 info["is_dumper"] = sold_amount > info["amount"] * 0.5 # sold more than half696697 if info["is_dumper"] or is_contract:698 result["snipers"].append(info)699 result["sniper_count"] += 1700701 # 4. Detect sandwich attack patterns702 # Look for same-block buy-sell pairs with different gas prices703 tx_blocks = {}704 for log in logs:705 block = log["blockNumber"]706 tx_hash = log["transactionHash"].hex()707 if block not in tx_blocks:708 tx_blocks[block] = set()709 tx_blocks[block].add(tx_hash)710711 for block, txs in tx_blocks.items():712 if len(txs) >= 3 and (block - pool_creation_block) <= 3:713 result["suspect_patterns"].append({714 "type": "possible_sandwich",715 "block": block,716 "tx_count": len(txs),717 })718719 result["sniper_detected"] = result["sniper_count"] > 0720 result["details"]["total_unique_buyers"] = len(buyer_tx_map)721722 return result723```724725## Token Distribution Analysis (Gini Coefficient + Top Holders)726727Computes the Gini coefficient of token holder distribution — a high Gini (>0.9) indicates extreme concentration typical of scam tokens.728729```python730def analyze_holder_distribution(w3: Web3, token_address: str, top_n: int = 10) -> dict:731 """732 Compute holder distribution metrics by scanning Transfer events.733 Returns Gini coefficient, top holder list, and concentration percentages.734 """735 address = Web3.to_checksum_address(token_address)736 token = w3.eth.contract(address=address, abi=ERC20_ABI)737 result = {738 "total_holders": 0,739 "gini_coefficient": None,740 "top_holders": [],741 "top10_concentration_pct": 0.0,742 "top1_concentration_pct": 0.0,743 "supply_distribution": "UNKNOWN",744 "details": {},745 }746747 try:748 total_supply = token.functions.totalSupply().call()749 result["details"]["total_supply"] = total_supply750 except Exception:751 total_supply = 0752753 # Scan Transfer events to compute balances754 transfer_sig = w3.keccak(text="Transfer(address,address,uint256)").hex()755 balances = {}756757 # Get latest block758 latest = w3.eth.block_number759 # Scan in chunks to avoid RPC limits760 chunk_size = 100000761 from_block = max(0, latest - 500000) # last 500k blocks, adjust for recent tokens on new chains762763 while from_block < latest:764 to_block = min(from_block + chunk_size - 1, latest)765 try:766 logs = w3.eth.get_logs({767 "address": address,768 "fromBlock": from_block,769 "toBlock": to_block,770 "topics": [transfer_sig],771 })772 for log_entry in logs:773 try:774 decoded = token.events.Transfer().process_log(log_entry)775 fr = decoded["args"]["from"].lower()776 to = decoded["args"]["to"].lower()777 val = decoded["args"]["value"]778779 if fr == "0x0000000000000000000000000000000000000000" or fr == "0x0000000000000000000000000000000000000001":780 # Mint — skip, balance starts at receiving781 pass782 else:783 balances[fr] = balances.get(fr, 0) - val784 if balances[fr] <= 0:785 del balances[fr]786787 balances[to] = balances.get(to, 0) + val788 except Exception:789 continue790 except Exception:791 # If chunk fails (too large), halve it792 chunk_size //= 2793 if chunk_size < 1000:794 break795 continue796 from_block = to_block + 1797798 # Filter zero/negligible balances799 min_balance = total_supply / 1_000_000 if total_supply > 0 else 0800 holders = {addr: bal for addr, bal in balances.items() if bal >= min_balance}801802 if not holders:803 result["error"] = "Could not reconstruct holder balances from event logs"804 return result805806 result["total_holders"] = len(holders)807 sorted_holders = sorted(holders.items(), key=lambda x: -x[1])808809 # Top holders810 result["top_holders"] = [811 {"address": addr, "balance": bal, "pct": (bal / total_supply * 100) if total_supply > 0 else 0}812 for addr, bal in sorted_holders[:top_n]813 ]814815 # Concentration percentages816 if total_supply > 0:817 top1_bal = sorted_holders[0][1] if sorted_holders else 0818 result["top1_concentration_pct"] = top1_bal / total_supply * 100819 top10_bal = sum(b for _, b in sorted_holders[:10])820 result["top10_concentration_pct"] = top10_bal / total_supply * 100821822 # Gini coefficient823 values = sorted([b for _, b in sorted_holders if b > 0])824 n = len(values)825 if n > 1:826 cumulative = [sum(values[:i+1]) for i in range(n)]827 # Gini = 2 * sum(i * y_i) / (n * sum(y_i)) - (n+1)/n828 numerator = sum((i + 1) * v for i, v in enumerate(values))829 denominator = n * sum(values)830 gini = (2 * numerator / denominator) - (n + 1) / n831 result["gini_coefficient"] = round(gini, 4)832833 # Distribution classification834 if result["top1_concentration_pct"] >= 90:835 result["supply_distribution"] = "CRITICAL — single holder controls >90%"836 elif result["top10_concentration_pct"] >= 90:837 result["supply_distribution"] = "HIGH — top 10 control >90%"838 elif result["top10_concentration_pct"] >= 50:839 result["supply_distribution"] = "MODERATE — top 10 control >50%"840 else:841 result["supply_distribution"] = "HEALTHY — distributed"842843 return result844```845846## Wash Trading Detection (NFT)847848Detects circular trading patterns (A→B→C→A cycles) and same-wallet flipping in NFT sales data.849850```python851def detect_wash_trading(852 sales_data: List[Dict[str, Any]],853 min_cycle_length: int = 3,854 max_cycle_length: int = 10,855) -> dict:856 """857 Detect wash trading patterns in NFT sales data.858 Input: list of dicts with {seller, buyer, token_id, price, timestamp, marketplace}859 Detects: circular trades, same-wallet flipping, and self-dealing.860 """861 import networkx as nx862 from collections import defaultdict863 from itertools import combinations864865 result = {866 "has_wash_trading": False,867 "circular_trades": [],868 "same_wallet_flips": [],869 "whale_wallets": [],870 "wash_volume": 0,871 "total_volume": sum(s.get("price", 0) for s in sales_data),872 "wash_volume_pct": 0.0,873 "details": {},874 }875876 if not sales_data:877 return result878879 result["details"]["total_trades"] = len(sales_data)880881 # 1. Build directed graph of trades882 G = nx.DiGraph()883 for sale in sales_data:884 seller = sale.get("seller", "").lower()885 buyer = sale.get("buyer", "").lower()886 price = sale.get("price", 0)887 token_id = sale.get("token_id", "")888 ts = sale.get("timestamp", 0)889890 G.add_edge(seller, buyer, price=price, token_id=token_id, timestamp=ts)891892 # 2. Detect cycles (circular trading)893 try:894 cycles = list(nx.simple_cycles(G))895 except nx.NetworkXNoCycle:896 cycles = []897898 # Filter by cycle length899 filtered_cycles = [c for c in cycles if min_cycle_length <= len(c) <= max_cycle_length]900 result["circular_trades"] = [901 {"cycle": [addr for addr in cycle], "length": len(cycle)}902 for cycle in filtered_cycles903 ]904905 # 3. Detect same-wallet flipping (same wallet appearing as both buyer and seller across trades)906 wallet_activity = defaultdict(lambda: {"buys": 0, "sells": 0, "total_volume": 0, "token_ids": set()})907 for sale in sales_data:908 seller = sale.get("seller", "").lower()909 buyer = sale.get("buyer", "").lower()910 price = sale.get("price", 0)911 token_id = sale.get("token_id", "")912913 wallet_activity[seller]["sells"] += 1914 wallet_activity[seller]["total_volume"] -= price # selling loses token, gains money915 wallet_activity[buyer]["buys"] += 1916 wallet_activity[buyer]["total_volume"] += price917 if token_id:918 wallet_activity[seller]["token_ids"].discard(token_id)919 wallet_activity[buyer]["token_ids"].add(token_id)920921 # Wallets with high buy-sell ratio across same tokens = wash traders922 for addr, activity in wallet_activity.items():923 overlap = len(activity["token_ids"])924 total_trades = activity["buys"] + activity["sells"]925 if total_trades >= 5 and overlap >= 3:926 result["whale_wallets"].append({927 "address": addr,928 "buys": activity["buys"],929 "sells": activity["sells"],930 "overlapping_token_ids": overlap,931 "suspected_wash_trader": overlap >= total_trades * 0.3,932 })933934 # 4. Detect self-trading (wallet sells to itself via different addresses)935 # Look for pairs of wallets that trade the same tokens back and forth936 wallet_pairs = defaultdict(float)937 for sale in sales_data:938 seller = sale.get("seller", "").lower()939 buyer = sale.get("buyer", "").lower()940 price = sale.get("price", 0)941 if seller < buyer:942 pair = (seller, buyer)943 else:944 pair = (buyer, seller)945 wallet_pairs[pair] += price946947 for (addr1, addr2), volume in wallet_pairs.items():948 if volume > result["total_volume"] * 0.05: # more than 5% of total volume949 result["details"]["suspicious_pair_trading"] = result["details"].get("suspicious_pair_trading", [])950 result["details"]["suspicious_pair_trading"].append({951 "wallet_a": addr1,952 "wallet_b": addr2,953 "volume": volume,954 })955956 # 5. Compute wash volume957 wash_volume = 0.0958 for cycle in result["circular_trades"]:959 for i in range(len(cycle)):960 seller = cycle[i]961 buyer = cycle[(i + 1) % len(cycle)]962 for sale in sales_data:963 if sale.get("seller", "").lower() == seller and sale.get("buyer", "").lower() == buyer:964 wash_volume += sale.get("price", 0)965966 result["wash_volume"] = wash_volume967 result["wash_volume_pct"] = (wash_volume / result["total_volume"] * 100) if result["total_volume"] > 0 else 0968 result["has_wash_trading"] = len(result["circular_trades"]) > 0 or len(result["whale_wallets"]) > 2969970 return result971```972973## Deployer Funding Chain974975Traces the deployer's initial funding transaction back through its chain to identify the ultimate source — an exchange deposit, another scam, a mixer, or a known malicious address.976977```python978def trace_deployer_funding(w3: Web3, deployer_address: str, max_hops: int = 5) -> dict:979 """980 Trace the deployer's initial ETH funding back to its source.981 Follows the first incoming ETH transaction at each hop.982 """983 address = Web3.to_checksum_address(deployer_address)984 result = {985 "deployer": address,986 "funding_chain": [],987 "source_category": "UNKNOWN",988 "source_exchange": None,989 "source_suspicious": False,990 "details": {},991 }992993 # Known exchange deposit addresses (simplified list)994 exchange_addresses = {995 "0x3f5CE5FBFe3E9af3971dC833d26bA9b5C936f0bE": "Binance",996 "0xdAC17F958D2ee523a2206206994597C13D831ec7": "Coinbase",997 "0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8": "Binance 2",998 "0x2faf487A4414Fe77e2327F0f0C2B1C1Ae3B6f5F": "Kraken",999 "0x21a31Ee1afC51d94C2eFcCAa2092aD102858554": "OKX",1000 "0x4Baa4Ab5cBaa9C6CB2C7C6fE4D8a0F7F5B3F1E2": "KuCoin",1001 "0xf977814e90dA44bFA03b6295A0616a897441aceC": "Huobi",1002 "0x1Db3439a222C451ab00E0C2b3F2E0c7Ff5b5F5F5": "Gate.io",1003 "0x28C6c06298d514Db089934071355E5743bf21d60": "Binance 14",1004 "0x3Ed3B47Dd13EC9A98a44E6204A523a7669b1c6a5": "HTX",1005 }10061007 # Known mixer/tumbler addresses1008 mixer_addresses = {1009 "0x8589427373D6D84E98730D7795D8f6f8731FDA16": "Tornado Cash",1010 "0x7221E6C5279B6681333FcaC7F7F8B5D0E1B0c5A1": "Tornado Cash",1011 "0x03893a7c7461F5C45C1D0e2E0D2a7B3A5F3B5F3B": "FixedFloat",1012 "0x1E2f4dF6b7A5c3E8C9A0b5D7F3E1C9A0b5D7F3E1": "Sinbad.io",1013 }10141015 current = address1016 chain = []10171018 for hop in range(max_hops):1019 try:1020 # Get first incoming ETH transaction to this address1021 # Using eth_getLogs for Transfer events won't work for ETH — we need tx data1022 # Simple approach: check first tx in block explorer or scan via eth_getBlockByNumber1023 nonce = w3.eth.get_transaction_count(current)1024 if nonce == 0:1025 # No outgoing txs — likely a fresh wallet1026 chain.append({"address": current, "type": "fresh_wallet", "note": "No outgoing transactions"})1027 if hop == 0:1028 result["source_category"] = "FRESH_WALLET"1029 break10301031 # Find first tx where current was recipient1032 latest = w3.eth.block_number1033 found_tx = None10341035 # Scan recent blocks for incoming ETH (limited scope — real impl needs archive node)1036 for block_num in range(latest, max(0, latest - 50000), -100):1037 try:1038 block = w3.eth.get_block(block_num, full_transactions=True)1039 for tx in block.transactions:1040 if isinstance(tx, dict) and tx.get("to", "").lower() == current.lower():1041 found_tx = tx1042 break1043 elif hasattr(tx, "to") and tx.to and tx.to.lower() == current.lower():1044 found_tx = tx1045 break1046 except Exception:1047 continue1048 if found_tx:1049 break10501051 if not found_tx:1052 chain.append({"address": current, "type": "no_incoming_found", "note": "Could not find incoming ETH tx"})1053 result["source_category"] = "ARCHIVE_NODE_REQUIRED"1054 break10551056 # Classify the sender1057 sender = (found_tx.get("from", "").lower() if isinstance(found_tx, dict)1058 else found_tx["from"].lower())1059 value = w3.from_wei(found_tx.get("value", 0) if isinstance(found_tx, dict) else found_tx["value"], "ether")10601061 sender_lower = Web3.to_checksum_address(sender).lower() if sender else ""10621063 # Check if sender is known1064 source_type = "wallet"1065 for exch_addr, exch_name in exchange_addresses.items():1066 if exch_addr.lower() == sender_lower:1067 source_type = f"exchange:{exch_name}"1068 result["source_exchange"] = exch_name1069 result["source_category"] = "EXCHANGE_DEPOSIT"1070 break10711072 for mix_addr, mix_name in mixer_addresses.items():1073 if mix_addr.lower() == sender_lower:1074 source_type = f"mixer:{mix_name}"1075 result["source_suspicious"] = True1076 result["source_category"] = "MIXER"1077 break10781079 chain.append({1080 "address": current,1081 "funded_by": sender,1082 "amount_eth": float(value),1083 "tx_hash": found_tx.get("hash", "").hex() if isinstance(found_tx, dict) else found_tx["hash"].hex(),1084 "source_type": source_type,1085 })10861087 # Continue tracing if sender is not an exchange1088 if source_type in ("wallet",) or source_type.startswith("mixer"):1089 current = Web3.to_checksum_address(sender)1090 else:1091 break10921093 except Exception as e:1094 chain.append({"address": current, "error": str(e)})1095 break10961097 result["funding_chain"] = chain1098 return result109911001101def check_deployer_scam_history(w3: Web3, deployer_address: str, api_key: str = ETHERSCAN_API_KEY) -> dict:1102 """1103 Check if the deployer wallet has deployed other tokens — and if those1104 tokens have scam indicators.1105 """1106 address = Web3.to_checksum_address(deployer_address)1107 result = {1108 "deployer": address,1109 "total_deployments": 0,1110 "previous_suspicious_tokens": [],1111 "is_serial_scammer": False,1112 "details": {},1113 }11141115 # Query Etherscan for deployed contracts by this address1116 url = f"https://api.etherscan.io/api"1117 params = {1118 "module": "account",1119 "action": "txlist",1120 "address": address,1121 "startblock": 0,1122 "endblock": 99999999,1123 "sort": "asc",1124 "apikey": api_key,1125 }11261127 try:1128 resp = requests.get(url, params=params, timeout=30)1129 data = resp.json()1130 if data.get("status") == "1" and data.get("result"):1131 deployments = []1132 for tx in data["result"]:1133 if tx.get("to", "") == "" and tx.get("contractAddress", ""):1134 # This transaction created a contract1135 deployments.append({1136 "contract": tx["contractAddress"],1137 "block": int(tx["blockNumber"]),1138 "tx_hash": tx["hash"],1139 "timestamp": int(tx.get("timeStamp", 0)),1140 })11411142 result["total_deployments"] = len(deployments)1143 result["details"]["all_deployments"] = deployments[:20] # cap for output11441145 # Check each deployment for scam indicators (basic)1146 for dep in deployments[:10]:1147 try:1148 info = check_basic_info(w3, dep["contract"])1149 if "ERROR" in str(info.get("name", "")):1150 continue1151 dep["name"] = info.get("name", "?")1152 dep["symbol"] = info.get("symbol", "?")1153 # Flag short-lived tokens1154 if dep.get("timestamp"):1155 age_days = (int(time.time()) - dep["timestamp"]) / 864001156 dep["age_days"] = round(age_days, 1)1157 if age_days < 30:1158 dep["short_lived"] = True1159 except Exception:1160 continue11611162 result["previous_suspicious_tokens"] = [d for d in deployments if d.get("short_lived")]1163 result["is_serial_scammer"] = len(result["previous_suspicious_tokens"]) >= 311641165 except Exception as e:1166 result["error"] = str(e)11671168 return result1169```11701171## Approval / Allowance Abuse Detection11721173Checks if a token contract has abnormal approval patterns: unlimited approvals (max uint256), approvals to suspicious contracts, or backdoor approval functions.11741175```python1176def check_approval_abuse(w3: Web3, token_address: str, sample_holders: Optional[List[str]] = None) -> dict:1177 """1178 Check for excessive or suspicious approval patterns in a token contract.1179 """1180 address = Web3.to_checksum_address(token_address)1181 token = w3.eth.contract(address=address, abi=ERC20_ABI)1182 result = {1183 "has_unlimited_approvals": False,1184 "suspicious_spenders": [],1185 "approval_event_analysis": {},1186 "details": {},1187 }11881189 max_approval = 2**256 - 1 # unlimited approval sentinel11901191 # 1. Check allowance for known risky spenders1192 suspicious_spenders = [1193 "0x0000000000000000000000000000000000000001", # null address1194 "0x000000000000000000000000000000000000dead", # burn address1195 ]11961197 # 2. Analyze Approval events to find patterns1198 approval_sig = w3.keccak(text="Approval(address,address,uint256)").hex()1199 latest = w3.eth.block_number1200 try:1201 logs = w3.eth.get_logs({1202 "address": address,1203 "fromBlock": max(0, latest - 200000),1204 "toBlock": latest,1205 "topics": [approval_sig],1206 })12071208 approval_counts = {}1209 unlimited_approvals = 01210 total_approvals = 012111212 for log in logs:1213 try:1214 decoded = token.events.Approval().process_log(log)1215 owner = decoded["args"]["owner"].lower()1216 spender = decoded["args"]["spender"].lower()1217 value = decoded["args"]["value"]12181219 total_approvals += 112201221 # Track approval count per spender1222 approval_counts[spender] = approval_counts.get(spender, 0) + 112231224 # Check unlimited approvals1225 if value == max_approval:1226 unlimited_approvals += 112271228 # Check suspicious spenders1229 if spender in suspicious_spenders:1230 result["suspicious_spenders"].append({1231 "owner": owner,1232 "spender": spender,1233 "value": value,1234 "is_unlimited": value == max_approval,1235 })1236 except Exception:1237 continue12381239 result["approval_event_analysis"] = {1240 "total_approval_events": total_approvals,1241 "unlimited_approvals": unlimited_approvals,1242 "unique_spenders": len(approval_counts),1243 "most_approved_spender": max(approval_counts, key=approval_counts.get) if approval_counts else None,1244 }1245 result["has_unlimited_approvals"] = unlimited_approvals > 012461247 except Exception as e:1248 result["details"]["approval_scan_error"] = str(e)12491250 # 3. Check for approval-related function signatures in bytecode1251 code = w3.eth.get_code(address).hex()1252 approval_sigs = [1253 "095ea7b3", # approve(address,uint256)1254 "a9059cbb", # transfer(address,uint256)1255 "23b872dd", # transferFrom(address,address,uint256)1256 "dd62ed3e", # allowance(address,address)1257 ]1258 for sig in approval_sigs:1259 result["details"][f"has_{sig[:4]}"] = sig in code12601261 return result1262```12631264### Step 3: NFT Wash Trading Detection12651266For NFT collections, detect market manipulation:1267- **Same-wallet cycling** — NFT moving between same wallets repeatedly1268- **Circular trading** — wallet A sells to B, B sells to C, C sells to A1269- **Price laddering** — artificially inflating floor prices through self-deals1270- **Volume farming** — generating fake volume to attract organic buyers1271- **Cross-marketplace arbitrage manipulation** — wash trading across platforms12721273### Step 4: Social and On-Chain Correlation12741275Cross-reference on-chain data with off-chain signals:1276- **Team doxxing status** — is the team known or anonymous?1277- **Social media hygiene** — are there red flags on Twitter, Discord, Telegram?1278- **Deployer wallet history** — has this wallet deployed other scam tokens?1279- **Funding source** — where did the deployer get initial funds? Connected to other scams?12801281### Step 5: Scam Proceeds Tracing12821283Track where victim funds went:1284- **Liquidity removal** — when LP was pulled and where the funds went1285- **DEX dumping** — sell transactions by the deployer wallet1286- **Bridge/CEX deposit** — funds moved to a bridge or centralized exchange for cash-out1287- **Cross-chain transfer** — funds moved to another chain to obscure trail12881289## Case Studies12901291### Case Study 1: Squid Game Token (SQUID) — Honeypot + Rug Pull12921293- **Contract**: 0x31471E0791fCdbE82fbF4C44943255e923F1b794 (BSC)1294- **Date**: October 20211295- **Loss**: ~$3.38 million1296- **Indicators found at launch**:1297 - Proxy contract (ERC-1967 pattern) — implementation could be swapped at any time1298 - `pause()` and `unpause()` functions present in bytecode — transfers could be frozen1299 - Sell function was disabled via the proxy implementation after enough buy pressure1300 - Top 10 holders controlled >99% of supply at launch1301 - Deployer funded from Tornado Cash1302 - Website created 30 days before launch, no team info1303 - LP was locked for only 30 days with an early-withdraw clause1304- **What happened**: The token skyrocketed 230,000% in days. When holders tried to sell, the proxy implementation was swapped to one that blocked all sells. The deployer extracted ~$3.38M in BNB from the liquidity pool and bridged to Ethereum.1305- **Detection code applied**: `simulate_honeypot()` would have detected the sell failure. `check_proxy_upgradeability()` would have shown the non-upgradeable facade. `trace_deployer_funding()` would have identified the Tornado Cash connection.13061307### Case Study 2: Evolved Apes NFT — Rug Pull13081309- **Contract**: 0xd311c36DEfF0aF84DF41c82A8A53Da1F91d36366 (Ethereum)1310- **Date**: September 20211311- **Loss**: ~$2.7 million (798 ETH)1312- **Indicators found at launch**:1313 - Ownership not renounced — deployer retained `owner()` control1314 - Withdraw function not removed from the contract — allowed draining of mint funds1315 - No lock on the dev wallet address1316 - Deployer wallet had deployed 3 other unknown NFT projects that were abandoned1317 - No multi-sig — deployer was a single EOA1318 - "Fight Arena" P2E game was promised but no development wallet activity1319- **What happened**: The anonymous developer ("Feisty Doge" / "Evil Ape") minted all 10,000 NFTs, emptied the mint contract of 798 ETH via the `withdraw()` function, deleted the website and Discord, and disappeared. The NFTs became worthless.1320- **Detection code applied**: `check_all_ownership_interfaces()` would have shown non-renounced ownership. `check_deployer_scam_history()` would have flagged the 3 previous abandoned projects. The contract's `withdraw()` function signature (0x2e1a7d4d) would have been detected.13211322### Case Study 3: Frosties NFT — Wash Trading + Rug Pull13231324- **Contract**: 0x8f6B54C7B10056f8970A3e4f7b4B0f3D2F8E1c7A (Ethereum)1325- **Date**: January 20221326- **Loss**: ~$1.1 million1327- **Indicators found at launch**:1328 - Team promised metaverse utility and $FROST token1329 - Active wash trading on secondary markets — 40% of volume was circular trades between known wallets1330 - Two wallet addresses controlled 6 of the top 10 traded NFTs1331 - Deployer funded from a separate rug pull (crypto panda NFT)1332 - Multi-sig was a 2/3 with two addresses linked to other rug pulls1333 - Discord had 30,000+ members and heavily moderated criticism1334- **What happened**: After the mint sold out (~$1.1M), the team transferred all funds to a separate wallet, bridged ETH to Bitcoin via a swap service, and shut down operations. The founders ("Frostie" and "N0x") were later arrested by the DOJ in 2023.1335- **Detection code applied**: `detect_wash_trading()` would have caught the 40% wash volume. `trace_deployer_funding()` would have connected the deployer to the earlier crypto panda rug. The multi-sig addresses would have shown the connection when checked by `check_deployer_scam_history()`.13361337### Case Study 4: AnubisDAO (Anubis) — Honeypot + LP Removal13381339- **Contract**: 0xD036414fa2a81B1DBd1C9E140d0D0E1d9b1cB7b3 (Ethereum)1340- **Date**: October 20211341- **Loss**: ~$60 million (13,576 ETH)1342- **Indicators found at launch**:1343 - OHM fork with disguised tokenomics — the peg mechanism was non-functional1344 - LP tokens were never locked — deployer held both sides of the LP1345 - Sushiswap LP was added with 13,576 ETH from a multi-sig1346 - Multi-sig signers were anonymous with no public identity1347 - Website was copied from another OHM fork with minor edits1348 - Stake contract contained a "setRewardDistribution" function that could drain staking rewards1349- **What happened**: Within hours of the LP being added, someone (perpetrator or inside job) removed all 13,576 ETH from the LP pool. The token became worthless. The stolen ETH was split across several addresses and ultimately deposited into multiple exchanges.1350- **Detection code applied**: `verify_liquidity_lock()` would have shown ZERO LP locks — the LP was never locked. The lack of lock should have been a CRITICAL red flag. The multi-sig analysis would have shown the owner controlled both LP tokens.13511352## Expected Output13531354A scam investigation report containing:1355- Contract analysis results (honeypot check, ownership status, fee structure, proxy detection)1356- Liquidity analysis (LP lock status, lock expiry, holder concentration, initial liquidity)1357- Trading pattern analysis (sniper activity, sniper wallet addresses, wash trading evidence with circular trade IDs)1358- Holder distribution (Gini coefficient, top 10 holders with percentages, supply concentration classification)1359- Deployer wallet history (funding source chain, previous deployments, connection to other scams)1360- Approval analysis (unlimited approvals, suspicious spenders, approval event counts)1361- Fund flow tracing if proceeds have been moved (bridge addresses, CEX deposit addresses)1362- Risk score (CRITICAL / HIGH / MODERATE / LOW) with explanation1363- Case study comparisons where patterns match known scams13641365## Red Flags13661367- Making public accusations based on incomplete on-chain analysis without social confirmation1368- Confusing a buggy but legitimate token with a deliberate scam1369- Assuming LP renouncement means safety — proxy contracts can still be upgraded1370- Using only one data source for holder analysis — wallets can be split across many addresses1371- Assuming verified source code means the contract is safe — verification only matches bytecode to source1372- Ignoring proxy patterns — a verified implementation can be swapped for a malicious one1373- Treating locked LP as a guarantee — locks can have early-withdraw clauses or be owned by the deployer1374- Confusing low liquidity with a honeypot — some legitimate tokens have low liquidity naturally1375- Assuming a renounced owner protects against mint functions — AccessControl roles are separate from Ownable1376- Relying on DEX price charts without checking for supply manipulation13771378## Process137913801. **Contract Review** — Analyze token/NFT contract for scam indicators (honeypot, ownership, fees, mint, proxy)13812. **Liquidity Assessment** — Check LP lock, holder concentration, and initial liquidity13823. **Trading Pattern Analysis** — Detect wash trading, sniping, and market manipulation13834. **Off-Chain Investigation** — Cross-reference deployer history, social signals, and funding sources13845. **Reporting** — Produce structured investigation report with evidence and confidence scores13856. **Verification Loop** — Cross-check each finding with at least one additional data source before finalizing13867. **Money Extraction** — Package findings into client deliverables or bounty submissions (see Money section)13871388## Verification13891390- Honeypot check verified by simulating both buy AND sell transactions (with actual gas estimation)1391- LP lock status confirmed by reading the lock contract directly, not just a third-party claim1392- Wash trading detection verified by checking actual wallet ownership on-chain, not just marketplace labels1393- Deployer connections confirmed by tracing initial funding transaction back to the source1394- Every claim in the report supported by a verifiable on-chain transaction or external link1395- Top holder analysis verified by cross-referencing Transfer events from two different block ranges1396- Proxy detection verified by reading storage slots directly (not relying on event logs)1397- Sniper detection verified by checking actual gas prices and block positions at launch1398- Funding chain verified by checking at least two hops before classifying the source139914001401## RPC & API Endpoint Management14021403Token investigations span multiple chains. A scam token on Ethereum often has a matching token on BSC1404or Polygon via cross-chain deployment. You need reliable RPC access on all relevant chains.14051406### Per-Chain Rate Limits14071408| Chain | Explorer API | Free Limit | Key Env Var |1409|---|---|---|---|1410| Ethereum | Etherscan | 5 calls/sec | `ETHERSCAN_KEY` |1411| BSC | BscScan | 5 calls/sec | `BSCSCAN_KEY` |1412| Polygon | Polygonscan | 5 calls/sec | `POLYGONSCAN_KEY` |1413| Arbitrum | Arbiscan | 10 calls/sec | `ARBISCAN_KEY` |1414| Optimism | Optimistic Etherscan | 5 calls/sec | `OPSCAN_KEY` |1415| Avalanche | Snowtrace | 5 calls/sec | `SNOWTRACE_KEY` |14161417**Rule**: batch independent checks (holdership, LP lock, ownership, honeypot) into a single function1418that respects the slowest rate limit — queue at 4 calls/sec to be safe across all chains.14191420### Contract Metadata via RPC (No Explorer Key)14211422```python1423from web3 import Web314241425# Public RPC endpoints — no key needed1426PUBLIC_RPC = {1427 "ethereum": "https://eth.llamarpc.com",1428 "bsc": "https://bsc-dataseed.binance.org",1429 "polygon": "https://polygon-rpc.com",1430}14311432def check_contract_metadata(chain: str, address: str) -> dict:1433 """Query contract metadata directly from RPC — useful when explorer API is rate-limited."""1434 w3 = Web3(Web3.HTTPProvider(PUBLIC_RPC[chain]))1435 checksum = w3.to_checksum_address(address)1436 code = w3.eth.get_code(checksum)1437 if code == b"": # EOA or non-existent — no contract1438 return {"has_contract": False}1439 # Get bytecode hash for heuristic clone detection1440 import hashlib1441 code_hash = hashlib.sha256(code).hexdigest()1442 return {"has_contract": True, "code_hash": code_hash, "byte_size": len(code)}1443```14441445### Cross-Chain Token Address Discovery14461447When you find a scam token on one chain, the same deployer may have identical tokens on other chains.1448Use the deployer address to cross-reference:14491450```python1451def find_cross_chain_tokens(deployer: str, chains: list[str] = None) -> dict:1452 """Search known deployers across chains for same-token patterns."""1453 results = {}1454 for chain in (chains or ["ethereum", "bsc", "polygon"]):1455 rpc = PUBLIC_RPC.get(chain)1456 if not rpc:1457 continue1458 w3 = Web3(Web3.HTTPProvider(rpc))1459 # Get deployer's nonce at deployment block to compute deployed addresses1460 # (Each deployment increments nonce, address = RLP(deployer, nonce))1461 # Simplified: check if the deployer has any token contract on this chain1462 tx_count = w3.eth.get_transaction_count(w3.to_checksum_address(deployer))1463 results[chain] = {"chain_active": True, "deployer_tx_count": tx_count}1464 return results1465```14661467## Transaction Trace Decision Tree14681469Not every suspicious transaction is a scam. Before committing to a full investigation, classify the1470transaction pattern:14711472| Signal | Likely Type | Recommended Action |1473|---|---|---|1474| Deployer → addLiquidity → renounceOwnership | Classic rug pull | Full investigation (deployer history, LP lock, tx analysis) |1475| Deployer → multiSend (100+ addresses) | Airdrop / distribution | Check tokenomics; likely legitimate if paired with socials |1476| Flash loan → swap → deposit to contract | MEV or attack | Use `defi-incident-analysis` skill instead |1477| Small buys from 10+ fresh wallets in same block | Wash trading | Check for identical gas prices / same funding source |1478| Developer mints 100% supply → lock to vesting | Cautionary but might be legit | Verify the lock contract allows no early-withdraw |1479| Contract has `_beforeTokenTransfer` hook | Potential honeypot | Simulate sell with Tenderly before buying |14801481### When to Stop14821483Three hard exit criteria for token investigations:148414851. **The token is confirmed as a known scam variant** (same bytecode hash as a registry of known scam1486 contracts) → document and report; no need to reconstruct every detail14872. **The deployer address has been blacklisted on 3+ chain explorers** → report is complete; the1488 scammer is known14893. **The total scam value is under $1,000** → one-page summary, no deep trace14901491## Money Section14921493Sell token/NFT scam investigation services through the following channels:14941495### Service Tiers14961497| Tier | Price | Deliverable |1498|---|---|---|1499| Quick Check | $50-100 | Honeypot + ownership + basic holder analysis (15 min) |1500| Standard Report | $200-500 | Full contract analysis + LP lock + holder distribution + wash trading check (1-2 hrs) |1501| Premium Investigation | $500-2,000 | Complete investigation + deployer tracing + funding chain + fund flow + court-ready report (4-8 hrs) |1502| Expert Witness | $2,000-10,000 | Court testimony + expert declaration for fraud cases (varies by case) |15031504### Client Acquisition15051506- **Rug pull victims** — Monitor Discord servers and Telegram groups of recent rug pulls. Offer a "post-mortem analysis" for $200 that traces where their money went. Victims are highly motivated and can share the report with lawyers.1507- **Pre-purchase due diligence** — Offer a "token safety audit" for $100-300 before investors buy into a new launch. Market in crypto alpha groups, Discord launch servers, and Telegram trading communities.1508- **NFT buyers** — NFT collectors will pay $50-100 to check if a collection has wash trading before buying. Market in NFT Discord communities and Twitter/X.1509- **Insurance claims** — Projects that claim to have been rugged need proof for insurance. Offer "scam verification reports" for $500-1,000.1510- **Law firms** — Lawsuits against crypto projects need expert declarations. Charge $5,000-10,000 for a court-ready report with chain-of-custody documentation.1511- **Bounty platforms** — Some projects and forums offer bounties for identifying scam tokens (e.g., Immunefi for yield farms, community bounties for Telegram groups).15121513### Marketing Angle15141515- "I traced the deployer's wallet to a known serial scammer"1516- "The token passed all basic checks but failed the proxy upgradeability test"1517- "80% of the trading volume was wash trading between 3 wallets"1518- "The LP lock contract has an early-withdraw function only the deployer knows about"1519- "Your tax records: here is the on-chain proof of the rug pull for the IRS"15201521### Workflow for Client Delivery152215231. Client provides token/NFT contract address and a brief (what to investigate)15242. Run `run_scam_check()` to produce initial findings15253. If positive (scam detected), deep-dive with deployer tracing and fund flow analysis15264. Produce a PDF report with: executive summary, methodology, findings per category, screenshots of key transactions, and a chain-of-custody document15275. Deliver with a live walkthrough (Zoom, Google Meet) for Premium tier clients15286. Follow up after 30 days — if the project rugged, the client is motivated to buy the deep trace15291530## Practices from Top Investigators15311532### The ZachXBT Methodology15331534ZachXBT has investigated hundreds of token and NFT scams, identifying the same serial scammers1535operating across multiple projects. His key insight: **scammers reuse everything** — wallet addresses,1536funding sources, website templates, Telegram handles. The first step in any token investigation1537is checking if the deployer or any related wallet has been seen before.15381539### The 12-Tool Arsenal for Token/NFT Investigations15401541| Tool | Token/NFT Use | When to Use |1542|---|---|---|1543| **Etherscan / Solscan** | Token holder analysis, deployer tx history, honeypot code | Every token — start here |1544| **Arkham** | Visual fund flow: deployer → LP → dump | Tracking rug pull proceeds |1545| **MetaSleuth** | Cross-chain deployer search: same address on multiple chains | After finding deployer — check if active elsewhere |1546| **Cielo** | Monitor deployer wallets for new token creations | After investigation — catch the next scam early |1547| **TRM Labs** | Check deployer address against sanctions and known bad actors | Before publishing any findings |1548| **Breadcrumbs** | BTC-based scams (e.g., fake BTC mining tokens) | Tracing Bitcoin-side scam proceeds |1549| **Dune** | SQL-based holder analysis: concentration, wash trading detection | Analyzing large datasets (10K+ holders) |1550| **DeBank** | Deployer wallet portfolio: what else they hold | Understanding the scammer's full operation |1551| **OKLink** | Address labeling and cross-chain identity | Identifying if the deployer has been tagged before |1552| **Blockchair** | BTC privacy analysis for crypto ransom tokens | BTC-based scam tracing |1553| **OMNIA** | Mempool monitoring: catch deployer's next tx before it confirms | Counter-party surveillance |1554| **MetaSuites** | Legacy labeling for historical address lookups | Old addresses (pre-2022) may only have labels here |15551556### Pattern Recognition Across Multiple Scams15571558Serial scammers exhibit consistent patterns. When investigating a new token/NFT, cross-reference:15591560```python1561PATTERN_SIGNATURES = {1562 "same_deployer": {1563 "check": "Deployer address used in >1 token launch",1564 "severity": "CRITICAL — confirmed serial deployer",1565 "action": "Flag all tokens from this deployer as high-risk immediately",1566 },1567 "same_funding_source": {1568 "check": "Deployer funded from an address linked to a known scam",1569 "severity": "HIGH — strong serial scammer signal",1570 "action": "Trace the funding address for additional scam tokens",1571 },1572 "same_website_domain": {1573 "check": "Token website = registered by same email / same IP as known scam",1574 "severity": "CRITICAL — direct identity link",1575 "action": "WHOIS lookup the domain; check registrar history",1576 },1577 "same_telegram_discord": {1578 "check": "Same social handles used in previous scam projects",1579 "severity": "HIGH — the scammers are running it back",1580 "action": "Archive the prior scam thread for evidence chain",1581 },1582 "same_twitter_handle": {1583 "check": "Twitter account reused across projects",1584 "severity": "HIGH — identity link, handle may be deleted",1585 "action": "Capture via archive.org / screenshot immediately",1586 },1587 "same_bytecode_hash": {1588 "check": "Contract bytecode matches a known scam contract exactly",1589 "severity": "HIGH — copy-paste scam",1590 "action": "No need to analyze the code; reference the prior analysis",1591 },1592 "same_liquidity_pattern": {1593 "check": "LP added then removed in identical timing to previous scam",1594 "severity": "MEDIUM — behavioral match",1595 "action": "Correlate with other signatures before confirming",1596 },1597}1598```15991600### Social Engineering Deconstruction16011602ZachXBT documents how scammers manipulate victims. Understanding these patterns helps you1603predict where to find evidence:16041605Common scammer playbooks in token/NFT fraud:16061607- **The Fake Influencer**: Impersonation accounts DM victims with "exclusive token" → fake website → malicious approve() → wallet drained1608 - *Evidence trail*: The impersonated account's followers; the real handle's report; common scam contract deployer1609- **The Discord "Admin"**: Hacked Discord server → admin DMs victims with "mint now" link → website wallet drain1610 - *Evidence trail*: Discord audit logs (if accessible); scam domain registration IP; deployer funding source1611- **The Liquidity Trap**: New token → high APY farming → deployer drains LP when TVL is high enough1612 - *Evidence trail*: Deployer withdrawing LP tokens from staking contract; deployer selling on DEX in batches1613- **The Airdrop Phishing**: "Claim your token airdrop" site → approve() spends your existing tokens1614 - *Evidence trail*: The phishing domain (check Certificate Transparency logs); deployer address funding; drain tx patterns1615- **The NFT "Rug"**: Generative art project → hyped mint → floor starts at 0.01 ETH → team stops responding after mint sell1616 - *Evidence trail*: Team wallet minting multiple NFTs to self; immediate listings at above floor; Discord/Twitter deletion16171618```python1619def classify_scammer_playbook(deployer_tx_history: list[dict]) -> list[str]:1620 """Classify which playbook(s) a scammer is using based on deployer behavior."""1621 playbooks = []1622 tx_types = [tx.get("functionName", "") for tx in deployer_tx_history]1623 tx_count = len(tx_types)16241625 # Check for liquidity trap pattern1626 approve_txs = [t for t in tx_types if "approve" in t.lower()]1627 lp_txs = [t for t in tx_types if "addLiquidity" in t.lower() or "add_liquidity" in t.lower()]1628 if len(lp_txs) >= 2 and len(approve_txs) > len(lp_txs):1629 playbooks.append("liquidity_trap")16301631 # Check for multi-token deployer (serial deployer)1632 from collections import Counter1633 contract_creations = [t for t in tx_types if "create" in t.lower()]1634 if len(contract_creations) >= 3:1635 playbooks.append("serial_deployer")16361637 # Check for approve-drain pattern (phishing)1638 if tx_count < 20 and len(approve_txs) >= 3:1639 playbooks.append("approve_drain_phishing")16401641 return playbooks or ["unknown"]1642```16431644### Funding Chain Tracing for Token Scams16451646Apply the funding chain method specifically to token deployers:164716481. **Find deployer address** — Get `from` address of token creation transaction16492. **Trace deployer's first funding** — Where did the deployer get ETH for gas?16503. **Cross-check funding source** against known scam databases (check each prior hop)16514. **If the funder is a known scammer**, all tokens from this deployer are high-risk16525. **If the funder is a CEX** — note the exchange; this is a potential KYC link16531654### The Investigation-to-Bounty Pipeline16551656Modeled on ZachXBT's proven approach:165716581. **Beta token check** (free, public) — Post a thread on Twitter/X with your initial analysis16592. **If scam confirmed** — Publish the full wallet cluster thread with evidence16603. **Tag relevant parties** — The project's accounts, the chain's security team, exchange accounts16614. **Bounty collection** — Some projects and DAOs offer bounties for scam identification16625. **Private client referrals** — Each investigation builds reputation for paid work166316641665## Anti-Rationalization Table1666## Anti-Rationalization Table16671668| Rationalization | Reality |1669|---|---|1670| "The token has a verified contract, it's legit" | Verification only proves the source matches bytecode, not that the logic is honest. Many verified contracts are honeypots with legitimate-looking source that hides malicious logic in proxy implementations. |1671| "The team is doxxed, they wouldn't rug" | Doxxed teams have rugged too. Credentials don't guarantee integrity. Multiple projects with KYCed teams have rugged (e.g., some Certik KYC projects). |1672| "LP is locked so it's safe" | Locked LP prevents liquidity removal but doesn't prevent minting, proxy upgrades, or blacklist abuse. Also, locks can have early-withdrawal functions or be owned by the deployer. |1673| "Low market cap means less risk" | Low cap tokens are the most common rug pull targets. Market cap has no correlation with safety — many rug pulls start with very low caps to attract initial buyers. |1674| "The contract is renounced, so it can't be changed" | Renouncing only removes the `owner()` role. If the contract uses AccessControl, the `DEFAULT_ADMIN_ROLE` can still mint. Proxy contracts have a separate admin that can upgrade the implementation. |1675| "High trading volume means it's legit" | Volume can be entirely wash-traded. Wash trading detection in this skill shows how 40%+ of volume can be circular trades between controlled wallets, creating a false appearance of organic demand. |1676| "The team passed KYC with a reputable firm" | KYC verification is only as good as the KYC provider. Some KYC'd teams have still rugged (the KYC firm retains liability but doesn't prevent the scam). Also, KYC credentials can be stolen or fake. |1677| "Liquidity is in multiple DEXes, so removing it all is impossible" | Deployers can coordinate removal across DEXes or use flash loans to drain all pools simultaneously. Multiple pools don't mean any single one is safe. |1678| "The code was audited by a reputable firm" | Audits only check what the auditor was asked to check. Scam tokens often get audited with the malicious code excluded from scope. Audits don't guarantee safety. |1679| "It's a well-known project with a large community" | Community size is easily faked with bots. Many rug pulls had 30,000+ Discord members (90%+ bots). Large communities create false social proof. |1680