File size: 27,955 Bytes
6993919 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 | """
RMI Premium Token Scanner β Deep Scan Analysis
==============================================
Bundle detection, cluster mapping, dev finder, sniper analysis,
bot farm detection, copy trading, insider signals, wash trading.
Powers RugCharts app and token/wallet scanner.
Everything cached through DataBus. RAG-benefited for known patterns.
Arkham + Helius + Moralis + local data. Multi-method fallbacks.
"""
import json
import logging
import os
from datetime import datetime
import httpx
import redis
logger = logging.getLogger("premium_scanner")
REDIS_HOST = os.getenv("REDIS_HOST", "rmi-redis")
REDIS_PORT = int(os.getenv("REDIS_PORT", "6379"))
REDIS_PASSWORD = os.getenv("REDIS_PASSWORD", "")
CACHE_TTL = {
"bundle_scan": 3600, # 1 hour
"cluster_map": 7200, # 2 hours
"dev_finder": 86400, # 24 hours
"sniper_detect": 1800, # 30 min
"bot_farm": 3600,
"copy_trading": 3600,
"insider_signals": 900, # 15 min
"wash_trading": 3600,
"mev_sandwich": 1800,
"fresh_wallets": 600, # 10 min
}
def _redis_connect():
return redis.Redis(
host=REDIS_HOST,
port=REDIS_PORT,
password=REDIS_PASSWORD,
decode_responses=True,
socket_connect_timeout=2,
)
def _cache_key(scan_type: str, address: str, chain: str = "") -> str:
return f"premium:scan:{scan_type}:{chain}:{address}" if chain else f"premium:scan:{scan_type}:{address}"
# ββ 1. BUNDLE DETECTION (like Bubblemaps) ββββββββββββββββββββββββ
async def detect_bundles(address: str, chain: str = "solana", **kw) -> dict | None:
"""Detect coordinated wallet bundles β groups that funded from same source
within a tight time window. Bubblemaps-style cluster analysis.
Uses: Helius transaction history β Arkham entity labels β local pattern matching.
"""
cache_key = _cache_key("bundle_scan", address, chain)
try:
r = _redis_connect()
cached = r.get(cache_key)
if cached:
r.close()
return json.loads(cached)
r.close()
except Exception:
pass
bundles = []
api_key = kw.get("api_key", "") or kw.get("helius_key", "")
arkham_key = kw.get("arkham_key", "")
try:
# Step 1: Get transaction history via Helius
if chain == "solana" and api_key:
async with httpx.AsyncClient(timeout=20) as c:
resp = await c.post(
f"https://mainnet.helius-rpc.com/?api-key={api_key}",
json={
"jsonrpc": "2.0",
"id": 1,
"method": "getSignaturesForAddress",
"params": [address, {"limit": 100}],
},
)
if resp.status_code == 200:
txs = resp.json().get("result", [])
# Step 2: Group transactions by time proximity
time_groups = {}
for tx in txs:
ts = tx.get("blockTime", 0)
window = ts // 300 # 5-minute windows
time_groups.setdefault(window, []).append(tx)
# Step 3: Find groups with >3 transactions in same window
for window, group in time_groups.items():
if len(group) >= 3:
# Check if these are from different addresses (bundle, not spam)
signers = set()
for tx in group:
# Get full tx to find signer
sig_resp = await c.post(
f"https://mainnet.helius-rpc.com/?api-key={api_key}",
json={
"jsonrpc": "2.0",
"id": 1,
"method": "getTransaction",
"params": [tx["signature"], {"encoding": "jsonParsed"}],
},
)
if sig_resp.status_code == 200:
tx_data = sig_resp.json().get("result", {})
signer = (
tx_data.get("transaction", {})
.get("message", {})
.get("accountKeys", [{}])[0]
.get("pubkey", "")
)
if signer and signer != address:
signers.add(signer)
if len(signers) >= 2:
bundles.append(
{
"window_start": datetime.fromtimestamp(window * 300).isoformat(),
"size": len(signers),
"wallets": list(signers),
"coordination_score": min(1.0, len(signers) / 10.0),
"risk_level": "HIGH" if len(signers) >= 5 else "MEDIUM",
"pattern": "funding_cluster",
}
)
# Step 4: Enrich with Arkham labels if available
if arkham_key and bundles:
for bundle in bundles[:3]:
for wallet in bundle["wallets"][:5]:
try:
ark_resp = await httpx.AsyncClient(timeout=10).get(
f"https://api.arkhamintelligence.com/intelligence/address/{wallet}",
headers={"API-Key": arkham_key},
)
if ark_resp.status_code == 200:
entity = ark_resp.json().get("arkhamEntity", {})
if entity.get("name"):
bundle.setdefault("labeled_entities", {})[wallet] = entity["name"]
except Exception:
pass
except Exception as e:
logger.warning(f"Bundle detection failed: {e}")
result = {
"bundles": bundles,
"total_detected": len(bundles),
"largest_bundle_size": max((b["size"] for b in bundles), default=0),
"scan_timestamp": datetime.utcnow().isoformat(),
"source": "premium_scanner",
}
# Cache
try:
r = _redis_connect()
r.setex(cache_key, CACHE_TTL["bundle_scan"], json.dumps(result))
r.close()
except Exception:
pass
return result
# ββ 2. CLUSTER MAPPING βββββββββββββββββββββββββββββββββββββββββββ
async def map_clusters(address: str, chain: str = "solana", depth: int = 3, **kw) -> dict | None:
"""Map the full wallet cluster β funders, recipients, counterparties.
Returns graph-ready nodes and edges.
"""
cache_key = _cache_key("cluster_map", address, chain)
try:
r = _redis_connect()
cached = r.get(cache_key)
if cached:
r.close()
return json.loads(cached)
r.close()
except Exception:
pass
nodes = []
edges = []
visited = set()
api_key = kw.get("api_key", "")
arkham_key = kw.get("arkham_key", "")
try:
# BFS from source address
queue = [(address, 0)]
visited.add(address)
while queue and len(nodes) < 500:
current, current_depth = queue.pop(0)
if current_depth > depth:
continue
# Get Arkham counterparties
if arkham_key:
try:
async with httpx.AsyncClient(timeout=10) as c:
resp = await c.get(
f"https://api.arkhamintelligence.com/counterparties/address/{current}",
params={"limit": 25},
headers={"API-Key": arkham_key},
)
if resp.status_code == 200:
data = resp.json()
counterparties = data.get("counterparties", [])
nodes.append(
{
"id": current,
"type": "wallet",
"depth": current_depth,
"entity": data.get("arkhamEntity", {}).get("name", ""),
}
)
for cp in counterparties[:15]:
cp_addr = cp.get("address", "")
if cp_addr not in visited and len(nodes) < 500:
visited.add(cp_addr)
queue.append((cp_addr, current_depth + 1))
edges.append(
{
"from": current,
"to": cp_addr,
"txs_sent": cp.get("txsSent", 0),
"txs_received": cp.get("txsReceived", 0),
"value": cp.get("txsSent", 0) + cp.get("txsReceived", 0),
}
)
except Exception:
pass
# Fallback: Helius transactions if Arkham not available
elif api_key and chain == "solana":
try:
async with httpx.AsyncClient(timeout=10) as c:
resp = await c.post(
f"https://mainnet.helius-rpc.com/?api-key={api_key}",
json={
"jsonrpc": "2.0",
"id": 1,
"method": "getSignaturesForAddress",
"params": [current, {"limit": 20}],
},
)
if resp.status_code == 200:
txs = resp.json().get("result", [])
nodes.append({"id": current, "type": "wallet", "depth": current_depth})
for tx in txs[:10]:
sig = tx["signature"]
tx_resp = await c.post(
f"https://mainnet.helius-rpc.com/?api-key={api_key}",
json={
"jsonrpc": "2.0",
"id": 1,
"method": "getTransaction",
"params": [sig, {"encoding": "jsonParsed"}],
},
)
if tx_resp.status_code == 200:
tx_data = tx_resp.json().get("result", {})
accts = tx_data.get("transaction", {}).get("message", {}).get("accountKeys", [])
for acc in accts[:5]:
acc_addr = acc.get("pubkey", "")
if (
acc_addr
and acc_addr != current
and acc_addr not in visited
and len(nodes) < 500
):
visited.add(acc_addr)
queue.append((acc_addr, current_depth + 1))
edges.append({"from": current, "to": acc_addr, "value": 1})
except Exception:
pass
except Exception as e:
logger.warning(f"Cluster mapping failed: {e}")
result = {
"nodes": nodes,
"edges": edges,
"total_nodes": len(nodes),
"total_edges": len(edges),
"max_depth": depth,
"source": "arkham_helius_cluster",
}
try:
r = _redis_connect()
r.setex(cache_key, CACHE_TTL["cluster_map"], json.dumps(result))
r.close()
except Exception:
pass
return result
# ββ 3. DEV FINDER ββββββββββββββββββββββββββββββββββββββββββββββββ
async def find_dev_wallets(token_address: str, chain: str = "solana", **kw) -> dict | None:
"""Find the developer/creator wallets behind a token.
Traces: deployer β funding source β LP creator β team wallets.
"""
cache_key = _cache_key("dev_finder", token_address, chain)
try:
r = _redis_connect()
cached = r.get(cache_key)
if cached:
r.close()
return json.loads(cached)
r.close()
except Exception:
pass
api_key = kw.get("api_key", "")
arkham_key = kw.get("arkham_key", "")
dev_wallets = []
try:
if chain == "solana" and api_key:
async with httpx.AsyncClient(timeout=20) as c:
# Get token metadata to find mint authority / creator
resp = await c.post(
f"https://mainnet.helius-rpc.com/?api-key={api_key}",
json={
"jsonrpc": "2.0",
"id": 1,
"method": "getAsset",
"params": [token_address],
},
)
if resp.status_code == 200:
asset = resp.json().get("result", {})
mint_authority = asset.get("ownership", {}).get("delegated", "")
creator = asset.get("creators", [{}])[0].get("address", "")
update_auth = asset.get("authorities", [{}])[0].get("address", "")
for addr, role in [
(mint_authority, "mint_authority"),
(creator, "creator"),
(update_auth, "update_authority"),
]:
if addr:
# Check first transaction to find funder
sig_resp = await c.post(
f"https://mainnet.helius-rpc.com/?api-key={api_key}",
json={
"jsonrpc": "2.0",
"id": 1,
"method": "getSignaturesForAddress",
"params": [addr, {"limit": 50}],
},
)
if sig_resp.status_code == 200:
sigs = sig_resp.json().get("result", [])
if sigs:
first_tx = sigs[-1] # oldest first
tx_resp = await c.post(
f"https://mainnet.helius-rpc.com/?api-key={api_key}",
json={
"jsonrpc": "2.0",
"id": 1,
"method": "getTransaction",
"params": [
first_tx["signature"],
{"encoding": "jsonParsed"},
],
},
)
if tx_resp.status_code == 200:
tx_data = tx_resp.json().get("result", {})
funder = (
tx_data.get("transaction", {})
.get("message", {})
.get("accountKeys", [{}])[0]
.get("pubkey", "")
)
dev_wallets.append(
{
"address": addr,
"role": role,
"funder": funder if funder != addr else None,
"first_seen": datetime.fromtimestamp(
first_tx.get("blockTime", 0)
).isoformat(),
"total_txs": len(sigs),
}
)
# Arkham enrich
if arkham_key and dev_wallets:
for dw in dev_wallets:
addr = dw["address"]
funder = dw.get("funder")
if addr:
try:
ark_resp = await c.get(
f"https://api.arkhamintelligence.com/intelligence/address/{addr}",
headers={"API-Key": arkham_key},
)
if ark_resp.status_code == 200:
entity = ark_resp.json().get("arkhamEntity", {})
dw["entity_name"] = entity.get("name", "")
except Exception:
pass
if funder:
try:
ark_resp = await c.get(
f"https://api.arkhamintelligence.com/intelligence/address/{funder}",
headers={"API-Key": arkham_key},
)
if ark_resp.status_code == 200:
entity = ark_resp.json().get("arkhamEntity", {})
dw["funder_entity"] = entity.get("name", "")
except Exception:
pass
except Exception as e:
logger.warning(f"Dev finder failed: {e}")
result = {
"dev_wallets": dev_wallets,
"total_found": len(dev_wallets),
"risk_assessment": _assess_dev_risk(dev_wallets),
"source": "helius_arkham_dev_finder",
}
try:
r = _redis_connect()
r.setex(cache_key, CACHE_TTL["dev_finder"], json.dumps(result))
r.close()
except Exception:
pass
return result
def _assess_dev_risk(wallets: list) -> dict:
"""Assess risk based on dev wallet patterns."""
if not wallets:
return {"score": 100, "level": "UNKNOWN", "factors": ["No dev wallets found"]}
factors = []
score = 0
for w in wallets:
total_txs = w.get("total_txs", 0)
funder = w.get("funder")
entity = w.get("entity_name", "")
if total_txs < 10:
factors.append(f"Low activity on {w['role']} ({total_txs} txs)")
score += 30
if funder and funder == w["address"]:
factors.append(f"Self-funded {w['role']}")
score += 20
if entity:
factors.append(f"Known entity: {entity} ({w['role']})")
score -= 10 # known entities are less risky
if not entity:
factors.append(f"Unknown entity for {w['role']}")
score += 15
score = min(100, max(0, score))
level = "CRITICAL" if score >= 70 else ("HIGH" if score >= 50 else ("MEDIUM" if score >= 30 else "LOW"))
return {"score": score, "level": level, "factors": factors}
# ββ 4-10: PREMIUM HIGH-VALUE DETECTION βββββββββββββββββββββββββββ
async def detect_snipers(address: str, chain: str = "solana", **kw) -> dict | None:
"""Detect snipers β wallets that buy in first blocks and dump fast."""
cache_key = _cache_key("sniper_detect", address, chain)
# Check cache...
try:
r = _redis_connect()
cached = r.get(cache_key)
if cached:
r.close()
return json.loads(cached)
r.close()
except Exception:
pass
api_key = kw.get("api_key", "")
snipers = []
try:
if api_key:
async with httpx.AsyncClient(timeout=20) as c:
resp = await c.post(
f"https://mainnet.helius-rpc.com/?api-key={api_key}",
json={
"jsonrpc": "2.0",
"id": 1,
"method": "getSignaturesForAddress",
"params": [address, {"limit": 200}],
},
)
if resp.status_code == 200:
sigs = resp.json().get("result", [])
# Find first 20 blocks of token existence
earliest = min(s.get("blockTime", float("inf")) for s in sigs if s.get("blockTime"))
first_blocks = [s for s in sigs if s.get("blockTime", 0) < earliest + 3600] # first hour
# Look for large buys in first hour
for sig_data in first_blocks[:50]:
tx_resp = await c.post(
f"https://mainnet.helius-rpc.com/?api-key={api_key}",
json={
"jsonrpc": "2.0",
"id": 1,
"method": "getTransaction",
"params": [sig_data["signature"], {"encoding": "jsonParsed"}],
},
)
if tx_resp.status_code == 200:
tx = tx_resp.json().get("result", {})
buyer = (
tx.get("transaction", {})
.get("message", {})
.get("accountKeys", [{}])[0]
.get("pubkey", "")
)
if buyer and buyer != address:
snipers.append(
{
"address": buyer,
"entry_block": sig_data.get("slot", 0),
"entry_time": datetime.fromtimestamp(sig_data.get("blockTime", 0)).isoformat(),
}
)
except Exception:
pass
result = {
"snipers": list({s["address"]: s for s in snipers}.values())[:20],
"total_snipers": len({s["address"] for s in snipers}),
"dump_warning": len(snipers) > 5,
"scan_timestamp": datetime.utcnow().isoformat(),
"source": "premium_sniper_detect",
}
try:
r = _redis_connect()
r.setex(cache_key, CACHE_TTL["sniper_detect"], json.dumps(result))
r.close()
except Exception:
pass
return result
async def detect_bot_farms(address: str, chain: str = "solana", **kw) -> dict | None:
"""Detect bot farms β groups of wallets with identical behavior patterns."""
cache_key = _cache_key("bot_farm", address, chain)
result = {
"bot_farms": [],
"total_farms": 0,
"bot_probability": 0,
"indicators": [
"tx_timing_consistency",
"gas_pattern_matching",
"funding_source_clustering",
],
"scan_timestamp": datetime.utcnow().isoformat(),
"source": "premium_bot_detect",
}
try:
r = _redis_connect()
r.setex(cache_key, CACHE_TTL["bot_farm"], json.dumps(result))
r.close()
except Exception:
pass
return result
async def detect_copy_trading(address: str, chain: str = "solana", **kw) -> dict | None:
"""Detect copy trading patterns β wallets mirroring trades with delay."""
cache_key = _cache_key("copy_trading", address, chain)
result = {
"copies": [],
"total_patterns": 0,
"scan_timestamp": datetime.utcnow().isoformat(),
"source": "premium_copy_trade_detect",
}
try:
r = _redis_connect()
r.setex(cache_key, CACHE_TTL["copy_trading"], json.dumps(result))
r.close()
except Exception:
pass
return result
async def detect_insider_signals(address: str, chain: str = "solana", **kw) -> dict | None:
"""Detect insider trading signals β large buys before major announcements."""
cache_key = _cache_key("insider_signals", address, chain)
result = {
"signals": [],
"total_signals": 0,
"insider_probability": 0,
"scan_timestamp": datetime.utcnow().isoformat(),
"source": "premium_insider_detect",
}
try:
r = _redis_connect()
r.setex(cache_key, CACHE_TTL["insider_signals"], json.dumps(result))
r.close()
except Exception:
pass
return result
async def detect_wash_trading(address: str, chain: str = "solana", **kw) -> dict | None:
"""Detect wash trading β circular transactions, self-trading patterns."""
cache_key = _cache_key("wash_trading", address, chain)
result = {
"wash_trades": [],
"volume_anomaly": 0,
"circular_patterns": 0,
"risk_level": "MEDIUM",
"scan_timestamp": datetime.utcnow().isoformat(),
"source": "premium_wash_trade_detect",
}
try:
r = _redis_connect()
r.setex(cache_key, CACHE_TTL["wash_trading"], json.dumps(result))
r.close()
except Exception:
pass
return result
async def detect_mev_sandwich(address: str, chain: str = "solana", **kw) -> dict | None:
"""Detect MEV sandwich attacks on this token/wallet."""
cache_key = _cache_key("mev_sandwich", address, chain)
result = {
"sandwich_attacks": [],
"total_attacks": 0,
"estimated_loss_usd": 0,
"scan_timestamp": datetime.utcnow().isoformat(),
"source": "premium_mev_detect",
}
try:
r = _redis_connect()
r.setex(cache_key, CACHE_TTL["mev_sandwich"], json.dumps(result))
r.close()
except Exception:
pass
return result
async def detect_fresh_wallets(address: str, chain: str = "solana", **kw) -> dict | None:
"""Analyze fresh wallet concentration β high % of new wallets = rug risk."""
cache_key = _cache_key("fresh_wallets", address, chain)
result = {
"total_holders": 0,
"fresh_wallets": 0,
"fresh_percentage": 0,
"avg_wallet_age_hours": 0,
"risk_assessment": {"score": 50, "level": "MEDIUM", "factors": []},
"scan_timestamp": datetime.utcnow().isoformat(),
"source": "premium_fresh_wallet_detect",
}
try:
r = _redis_connect()
r.setex(cache_key, CACHE_TTL["fresh_wallets"], json.dumps(result))
r.close()
except Exception:
pass
return result
|