File size: 45,073 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 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 | """
DataBus Provider Implementations β External API Interfaces
===========================================================
All external API implementations for the DataBus providers.
This module contains NO chain definitions or infrastructure.
"""
import os
import httpx
async def _local_token_price(**kwargs) -> dict | None:
"""Get price from our own data (Redis/ClickHouse)."""
try:
import json
import os
import redis
r = redis.Redis(
host=os.getenv("REDIS_HOST", "rmi-redis"),
port=int(os.getenv("REDIS_PORT", "6379")),
password=os.getenv("REDIS_PASSWORD", ""),
decode_responses=True,
socket_connect_timeout=2,
)
token = kwargs.get("token", "")
if token:
cached = r.get(f"price:{token.lower()}")
if cached:
return json.loads(cached)
r.close()
except Exception:
pass
return None
async def _dexscreener_price(**kwargs) -> dict | None:
"""DexScreener β free, no key."""
token = kwargs.get("mint", "") or kwargs.get("token", "")
if not token:
return None
try:
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(f"https://api.dexscreener.com/latest/dex/tokens/{token}")
if r.status_code == 200:
return r.json()
except Exception:
pass
return None
async def _coingecko_price(**kwargs) -> dict | None:
"""CoinGecko β free for low volume."""
token = kwargs.get("mint", "") or kwargs.get("token", "")
api_key = kwargs.get("api_key", "")
try:
headers = {"x-cg-pro-api-key": api_key} if api_key else {}
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(f"https://api.coingecko.com/api/v3/simple/token_price/{token}", headers=headers)
if r.status_code == 200:
return r.json()
except Exception:
pass
return None
async def _moralis_price(**kwargs) -> dict | None:
"""Moralis β paid, high quality."""
token = kwargs.get("token", "")
api_key = kwargs.get("api_key", "")
try:
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(
f"https://deep-index.moralis.io/api/v2/erc20/{token}/price",
headers={"X-API-Key": api_key},
)
if r.status_code == 200:
return r.json()
except Exception:
pass
return None
# ββ ALCHEMY PROVIDER ββββββββββββββββββββββββββββββββββββββββββ
async def _alchemy_token_balances(address: str = "", network: str = "eth-mainnet", **kw) -> dict | None:
"""Alchemy β get all token balances for an address."""
api_key = kw.get("api_key", "")
if not address or not api_key:
return None
try:
url = f"https://{network}.g.alchemy.com/v2/{api_key}"
payload = {
"jsonrpc": "2.0",
"method": "alchemy_getTokenBalances",
"params": [address, "erc20"],
"id": 1,
}
async with httpx.AsyncClient(timeout=15) as c:
r = await c.post(url, json=payload)
if r.status_code == 200:
data = r.json()
if "result" in data:
return {"balances": data["result"], "address": address, "network": network}
except Exception:
pass
return None
async def _alchemy_token_metadata(contract: str = "", network: str = "eth-mainnet", **kw) -> dict | None:
"""Alchemy β get token metadata."""
api_key = kw.get("api_key", "")
if not contract or not api_key:
return None
try:
url = f"https://{network}.g.alchemy.com/v2/{api_key}"
payload = {
"jsonrpc": "2.0",
"method": "alchemy_getTokenMetadata",
"params": [contract],
"id": 1,
}
async with httpx.AsyncClient(timeout=10) as c:
r = await c.post(url, json=payload)
if r.status_code == 200:
data = r.json()
if "result" in data:
return {"metadata": data["result"], "contract": contract}
except Exception:
pass
return None
# ββ PASSTHROUGH PROVIDERS β call our own backend endpoints ββββββ
async def _passthrough_market_overview(**kwargs) -> dict | None:
"""Market overview from our own /api/v1/content/market-overview."""
try:
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get("http://localhost:8000/api/v1/content/market-overview")
if r.status_code == 200:
return r.json()
except Exception:
pass
return None
async def _passthrough_trending(**kwargs) -> dict | None:
"""Trending tokens from our own /api/v1/tokens/trending."""
try:
limit = kwargs.get("limit", 20)
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(f"http://localhost:8000/api/v1/tokens/trending?limit={limit}")
if r.status_code == 200:
return r.json()
except Exception:
pass
return None
async def _passthrough_news(**kwargs) -> dict | None:
"""News from our own 30-source aggregator."""
try:
limit = kwargs.get("limit", 20)
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(f"http://localhost:8000/api/v1/news/combined?limit={limit}")
if r.status_code == 200:
return r.json()
except Exception:
pass
return None
async def _passthrough_alerts(**kwargs) -> dict | None:
"""Alerts from our real alert pipeline."""
try:
from app.alert_pipeline import get_active_alert_count, get_recent_alerts
count = await get_active_alert_count()
recent = await get_recent_alerts(limit=kwargs.get("limit", 20))
return {"count": count, "alerts": recent}
except Exception:
pass
return {"count": 0, "alerts": []}
# ββ LOCAL DATA PROVIDERS β our own databases βββββββββββββββββββ
async def _local_wallet_labels(address: str = "", **kw) -> dict | None:
"""Our 190K wallet labels from Redis β rmi:label:{chain}:{address} format."""
if not address:
return None
try:
import json
import os
import redis
from dotenv import load_dotenv
load_dotenv("/app/.env", override=True)
r = redis.Redis(
host=os.getenv("REDIS_HOST", "rmi-redis"),
port=int(os.getenv("REDIS_PORT", "6379")),
password=os.getenv("REDIS_PASSWORD", ""),
decode_responses=True,
socket_connect_timeout=2,
)
# Search across all chains β label key is rmi:label:{chain}:{address}
chains = [
"solana",
"ethereum",
"bsc",
"base",
"arbitrum",
"optimism",
"polygon",
"avalanche",
]
for chain in chains:
key = f"rmi:label:{chain}:{address}"
data = r.get(key)
if data:
label = json.loads(data)
r.close()
return {
"labels": [label],
"address": address,
"source": "wallet_memory_bank",
"total_labels": "190K+",
}
# Try prefix search as fallback
keys = r.keys(f"rmi:label:*:{address}")
if keys:
data = r.get(keys[0])
if data:
label = json.loads(data)
r.close()
return {
"labels": [label],
"address": address,
"source": "wallet_memory_bank",
"total_labels": "190K+",
}
r.close()
except Exception:
pass
return None
async def _passthrough_scanner(address: str = "", chain: str = "solana", **kw) -> dict | None:
"""SENTINEL scanner β our own token security analysis."""
try:
async with httpx.AsyncClient(timeout=30) as c:
r = await c.post("http://localhost:8000/api/v1/token/scan", json={"address": address, "chain": chain})
if r.status_code == 200:
return r.json()
except Exception:
pass
return None
async def _passthrough_rag(query: str = "", collection: str = "known_scams", **kw) -> dict | None:
"""RAG search β our 17K+ document knowledge base."""
try:
async with httpx.AsyncClient(timeout=15) as c:
r = await c.post(
"http://localhost:8000/api/v1/rag/search",
json={"query": query, "collection": collection, "limit": kw.get("limit", 10)},
)
if r.status_code == 200:
return r.json()
except Exception:
pass
return None
# ββ MORALIS WEB3 AI AGENTS β Full API Suite ββββββββββββββββββββββ
_MORALIS_BASE = "https://deep-index.moralis.io/api/v2.2"
async def _moralis_wallet_tokens(address: str = "", chain: str = "eth", **kw) -> dict | None:
"""Moralis β get wallet token balances with metadata."""
api_key = kw.get("api_key", "")
if not address or not api_key:
return None
try:
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(
f"{_MORALIS_BASE}/{address}/erc20",
params={"chain": chain},
headers={"X-API-Key": api_key},
)
if r.status_code == 200:
return {"tokens": r.json(), "address": address, "chain": chain}
except Exception:
pass
return None
async def _moralis_wallet_nfts(address: str = "", chain: str = "eth", **kw) -> dict | None:
"""Moralis β get wallet NFTs."""
api_key = kw.get("api_key", "")
if not address or not api_key:
return None
try:
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(
f"{_MORALIS_BASE}/{address}/nft",
params={"chain": chain},
headers={"X-API-Key": api_key},
)
if r.status_code == 200:
return {"nfts": r.json(), "address": address, "chain": chain}
except Exception:
pass
return None
async def _moralis_wallet_transactions(address: str = "", chain: str = "eth", **kw) -> dict | None:
"""Moralis β get wallet transaction history."""
api_key = kw.get("api_key", "")
if not address or not api_key:
return None
try:
limit = kw.get("limit", 50)
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(
f"{_MORALIS_BASE}/{address}",
params={"chain": chain, "limit": limit},
headers={"X-API-Key": api_key},
)
if r.status_code == 200:
return {"transactions": r.json(), "address": address, "chain": chain}
except Exception:
pass
return None
async def _moralis_token_price(address: str = "", chain: str = "eth", **kw) -> dict | None:
"""Moralis β get token price via Token API."""
api_key = kw.get("api_key", "")
if not address or not api_key:
return None
try:
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(
f"{_MORALIS_BASE}/erc20/{address}/price",
params={"chain": chain},
headers={"X-API-Key": api_key},
)
if r.status_code == 200:
return {"price": r.json(), "address": address, "chain": chain}
except Exception:
pass
return None
async def _moralis_token_metadata(address: str = "", chain: str = "eth", **kw) -> dict | None:
"""Moralis β get token metadata."""
api_key = kw.get("api_key", "")
if not address or not api_key:
return None
try:
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(
f"{_MORALIS_BASE}/erc20/{address}",
params={"chain": chain},
headers={"X-API-Key": api_key},
)
if r.status_code == 200:
return {"metadata": r.json(), "address": address}
except Exception:
pass
return None
async def _moralis_wallet_net_worth(address: str = "", **kw) -> dict | None:
"""Moralis β wallet net worth across chains."""
api_key = kw.get("api_key", "")
if not address or not api_key:
return None
try:
async with httpx.AsyncClient(timeout=20) as c:
r = await c.get(f"{_MORALIS_BASE}/wallets/{address}/net-worth", headers={"X-API-Key": api_key})
if r.status_code == 200:
return {"net_worth": r.json(), "address": address}
except Exception:
pass
return None
async def _moralis_search_tokens(query: str = "", **kw) -> dict | None:
"""Moralis β search tokens by name/symbol/address."""
api_key = kw.get("api_key", "")
if not query or not api_key:
return None
try:
limit = kw.get("limit", 10)
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(
f"{_MORALIS_BASE}/search",
params={"q": query, "filter": "token", "limit": limit},
headers={"X-API-Key": api_key},
)
if r.status_code == 200:
return {"results": r.json(), "query": query}
except Exception:
pass
return None
# ββ MCP BRIDGE β Call local MCP servers from DataBus ββββββββββββββ
async def _mcp_bridge(mcp_server: str = "", mcp_tool: str = "", **kw) -> dict | None:
"""Universal MCP bridge β calls any local MCP server tool.
Uses subprocess to call MCP servers installed in /root/.hermes/mcp-servers/.
Falls back to HTTP for configured HTTP MCP servers.
"""
if not mcp_server or not mcp_tool:
return None
try:
import json as _json
import subprocess
# Build tool args dict from kwargs (strip internal params)
tool_args = {k: v for k, v in kw.items() if k not in ("api_key", "mcp_server", "mcp_tool")}
# Known MCP server β command mapping
MCP_COMMANDS = {
"evm-direct": ["node", "/root/.hermes/mcp-servers/evm-direct/bin/cli.js"],
"evmscope": ["node", "/root/.hermes/mcp-servers/evmscope/dist/cli.js"],
"jupiter-mcp": ["node", "/root/.hermes/mcp-servers/jupiter-mcp/index.js"],
"crypto-feargreed-mcp": [
"python3",
"/root/.hermes/mcp-servers/crypto-feargreed-mcp/main.py",
],
"crypto-indicators-mcp": [
"node",
"/root/.hermes/mcp-servers/crypto-indicators-mcp/index.js",
],
"moralis-mcp": ["node", "/root/.hermes/mcp-servers/moralis-mcp/src/index.mjs"],
"web3-research-mcp": ["node", "/root/.hermes/mcp-servers/web3-research-mcp/bin/cli.js"],
"solana-mcp": ["node", "/root/.hermes/mcp-servers/solana-mcp-official/index.js"],
}
if mcp_server in MCP_COMMANDS:
# Build MCP JSON-RPC call
mcp_request = _json.dumps(
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {"name": mcp_tool, "arguments": tool_args},
"id": 1,
}
)
cmd = MCP_COMMANDS[mcp_server]
result = subprocess.run(cmd, input=mcp_request, capture_output=True, text=True, timeout=30)
if result.returncode == 0 and result.stdout:
data = _json.loads(result.stdout)
if "result" in data:
return {"result": data["result"], "server": mcp_server, "tool": mcp_tool}
else:
# Try HTTP MCP server
mcp_configs = {
"coingecko": "https://mcp.api.coingecko.com/mcp",
}
if mcp_server in mcp_configs:
async with httpx.AsyncClient(timeout=30) as c:
r = await c.post(
mcp_configs[mcp_server],
json={
"jsonrpc": "2.0",
"method": "tools/call",
"params": {"name": mcp_tool, "arguments": tool_args},
"id": 1,
},
)
if r.status_code == 200:
data = r.json()
if "result" in data:
return {
"result": data["result"],
"server": mcp_server,
"tool": mcp_tool,
}
except Exception:
pass
return None
# ββ ARKHAM INTELLIGENCE β Free trial month, premium entity data ββ
_ARKHAM_BASE = "https://api.arkhamintelligence.com"
async def _arkham_entity(address: str = "", **kw) -> dict | None:
"""Arkham β entity intelligence (tx counts, top counterparties, tags)."""
api_key = kw.get("api_key", "")
if not address or not api_key:
return None
try:
headers = {"API-Key": api_key}
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(f"{_ARKHAM_BASE}/intelligence/address/{address}", headers=headers)
if r.status_code == 200:
return {"entity": r.json(), "address": address, "source": "arkham"}
except Exception:
pass
return None
async def _arkham_counterparties(address: str = "", **kw) -> dict | None:
"""Arkham β top counterparties ranked by transaction volume."""
api_key = kw.get("api_key", "")
if not address or not api_key:
return None
try:
limit = kw.get("limit", 25)
headers = {"API-Key": api_key}
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(
f"{_ARKHAM_BASE}/counterparties/address/{address}",
params={"limit": limit},
headers=headers,
)
if r.status_code == 200:
return {"counterparties": r.json(), "address": address, "source": "arkham"}
except Exception:
pass
return None
async def _arkham_intel_search(query: str = "", **kw) -> dict | None:
"""Arkham β search entities by address prefix (up to 20 matches)."""
api_key = kw.get("api_key", "")
if not query or not api_key:
return None
try:
headers = {"API-Key": api_key}
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(f"{_ARKHAM_BASE}/intelligence/search", params={"query": query}, headers=headers)
if r.status_code == 200:
return {"results": r.json(), "query": query, "source": "arkham"}
except Exception:
pass
return None
async def _arkham_portfolio(address: str = "", **kw) -> dict | None:
"""Arkham β portfolio via entity intelligence (includes balance info)."""
api_key = kw.get("api_key", "")
if not address or not api_key:
return None
try:
headers = {"API-Key": api_key}
async with httpx.AsyncClient(timeout=20) as c:
r = await c.get(f"{_ARKHAM_BASE}/intelligence/address/{address}", headers=headers)
if r.status_code == 200:
return {"portfolio": r.json(), "address": address, "source": "arkham"}
except Exception:
pass
return None
async def _arkham_transfers(address: str = "", **kw) -> dict | None:
"""Arkham β transfer history via counterparties endpoint."""
api_key = kw.get("api_key", "")
if not address or not api_key:
return None
try:
limit = kw.get("limit", 100)
headers = {"API-Key": api_key}
async with httpx.AsyncClient(timeout=20) as c:
r = await c.get(
f"{_ARKHAM_BASE}/counterparties/address/{address}",
params={"limit": limit},
headers=headers,
)
if r.status_code == 200:
return {"transfers": r.json(), "address": address, "source": "arkham"}
except Exception:
pass
return None
async def _arkham_labels(address: str = "", **kw) -> dict | None:
"""Arkham β labels extracted from entity intelligence (arkhamLabel field)."""
api_key = kw.get("api_key", "")
if not address or not api_key:
return None
try:
headers = {"API-Key": api_key}
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(f"{_ARKHAM_BASE}/intelligence/address/{address}", headers=headers)
if r.status_code == 200:
data = r.json()
label = data.get("arkhamLabel", {})
entity = data.get("arkhamEntity", {})
labels = []
if label and label.get("name"):
labels.append({"name": label["name"], "id": label.get("id"), "type": "arkham"})
if entity and entity.get("name"):
labels.append({"name": entity["name"], "id": entity.get("id"), "type": "entity"})
return {
"labels": labels,
"address": address,
"chain": data.get("chain"),
"source": "arkham",
}
except Exception:
pass
return None
# ββ FREE FALLBACK PROVIDERS β never pay for what's free ββββββββββ
async def _dexscreener_token_metadata(mint: str = "", **kw) -> dict | None:
"""DexScreener β free token metadata from pairs endpoint."""
token = mint or kw.get("token", "") or kw.get("contract", "")
if not token:
return None
try:
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(f"https://api.dexscreener.com/latest/dex/tokens/{token}")
if r.status_code == 200:
data = r.json()
pairs = data.get("pairs", [])
if pairs:
p = pairs[0]
return {
"metadata": {
"name": p.get("baseToken", {}).get("name", ""),
"symbol": p.get("baseToken", {}).get("symbol", ""),
"decimals": None,
"price_usd": p.get("priceUsd"),
"liquidity_usd": p.get("liquidity", {}).get("usd"),
"fdv": p.get("fdv"),
"chain": p.get("chainId", ""),
},
"source": "dexscreener",
}
except Exception:
pass
return None
async def _dexscreener_holders(mint: str = "", **kw) -> dict | None:
"""DexScreener β free holder/liquidity data from pairs."""
token = mint or kw.get("token", "")
if not token:
return None
try:
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(f"https://api.dexscreener.com/latest/dex/tokens/{token}")
if r.status_code == 200:
data = r.json()
pairs = data.get("pairs", [])
if pairs:
return {"pairs": pairs, "total_pairs": len(pairs), "source": "dexscreener"}
except Exception:
pass
return None
async def _dexscreener_trades(token: str = "", chain: str = "solana", **kw) -> dict | None:
"""DexScreener β recent trades for a token (free, no API key required)."""
if not token:
return None
try:
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(f"https://api.dexscreener.com/latest/dex/tokens/{token}")
if r.status_code == 200:
data = r.json()
pairs = data.get("pairs", [])
if pairs:
# DexScreener doesn't have a direct trades endpoint, but we can simulate
# recent activity from pair data or use a mock structure for the frontend
# to render until a dedicated trades API is wired.
return {
"trades": [],
"message": "Live trades feed requires premium DEX API. Showing pair summary.",
"pairs": pairs[:5],
"source": "dexscreener",
}
except Exception:
pass
return None
async def _dexscreener_top_traders(token: str = "", chain: str = "solana", **kw) -> dict | None:
"""DexScreener β top profitable traders for a token."""
if not token:
return None
try:
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(f"https://api.dexscreener.com/latest/dex/tokens/{token}")
if r.status_code == 200:
data = r.json()
pairs = data.get("pairs", [])
if pairs:
return {
"top_traders": [],
"message": "Top trader analytics require premium on-chain indexer. Showing pair summary.",
"pairs": pairs[:3],
"source": "dexscreener",
}
except Exception:
pass
return None
async def _etherscan_tx_trace(tx_hash: str = "", network: str = "ethereum", **kw) -> dict | None:
"""Etherscan β free transaction data (5 req/sec, no key needed for basic)."""
if not tx_hash:
return None
try:
# Map network to Etherscan domain
domains = {
"ethereum": "api.etherscan.io",
"eth-mainnet": "api.etherscan.io",
"bsc": "api.bscscan.com",
"polygon": "api.polygonscan.com",
"arbitrum": "api.arbiscan.io",
"optimism": "api-optimistic.etherscan.io",
"base": "api.basescan.org",
}
domain = domains.get(network, "api.etherscan.io")
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(
f"https://{domain}/api",
params={
"module": "proxy",
"action": "eth_getTransactionByHash",
"txhash": tx_hash,
"apikey": "YourApiKeyToken",
},
)
if r.status_code == 200:
data = r.json()
if data.get("result"):
return {
"transaction": data["result"],
"tx_hash": tx_hash,
"source": "etherscan",
}
except Exception:
pass
return None
# ββ DEFILLAMA PROVIDER (100% FREE, NO API KEY) ββββββββββββββββββββ
async def _defillama_tvl(**kw) -> dict | None:
"""DeFiLlama β global TVL and protocol data (completely free)."""
try:
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get("https://api.llama.fi/protocols")
if r.status_code == 200:
data = r.json()
total_tvl = sum(p.get("tvl", 0) for p in data if isinstance(p, dict))
return {
"total_tvl": total_tvl,
"protocols_count": len(data),
"top_protocols": data[:10],
"source": "defillama",
}
except Exception:
pass
return None
async def _defillama_chains(**kw) -> dict | None:
"""DeFiLlama β TVL by chain (completely free)."""
try:
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get("https://api.llama.fi/chains")
if r.status_code == 200:
data = r.json()
return {
"chains": [{"name": c.get("name"), "tvl": c.get("tvl")} for c in data if isinstance(c, dict)],
"source": "defillama",
}
except Exception:
pass
return None
# ββ BLOCKCHAIR PROVIDER (FREE TIER, NO API KEY FOR BASIC) ββββββββ
async def _blockchair_address(address: str = "", chain: str = "bitcoin", **kw) -> dict | None:
"""Blockchair β address balance and tx count (free tier)."""
if not address:
return None
try:
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(f"https://api.blockchair.com/{chain}/dashboards/address/{address}")
if r.status_code == 200:
data = r.json()
if data.get("data") and address in data["data"]:
return {
"address": address,
"chain": chain,
"data": data["data"][address],
"source": "blockchair",
}
except Exception:
pass
return None
async def _blockchair_stats(chain: str = "bitcoin", **kw) -> dict | None:
"""Blockchair β chain statistics (free tier)."""
try:
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(f"https://api.blockchair.com/{chain}/stats")
if r.status_code == 200:
data = r.json()
return {
"chain": chain,
"stats": data.get("data", {}).get("stats", {}),
"source": "blockchair",
}
except Exception:
pass
return None
# ββ BIRDEYE PROVIDER (FREEMIUM, FREE TIER AVAILABLE) βββββββββββββ
async def _birdeye_overview(address: str = "", **kw) -> dict | None:
"""Birdeye β token overview, liquidity, and holder stats (free tier)."""
api_key = kw.get("api_key", "") or os.getenv("BIRDEYE_API_KEY", "")
if not address:
return None
try:
headers = {"X-API-KEY": api_key, "accept": "application/json"} if api_key else {"accept": "application/json"}
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(
f"https://public-api.birdeye.so/defi/token_overview?address={address}",
headers=headers,
)
if r.status_code == 200:
data = r.json()
return {"address": address, "data": data.get("data", {}), "source": "birdeye"}
except Exception:
pass
return None
async def _birdeye_price(address: str = "", **kw) -> dict | None:
"""Birdeye β real-time token price (free tier)."""
api_key = kw.get("api_key", "") or os.getenv("BIRDEYE_API_KEY", "")
if not address:
return None
try:
headers = {"X-API-KEY": api_key, "accept": "application/json"} if api_key else {"accept": "application/json"}
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(f"https://public-api.birdeye.so/defi/price?address={address}", headers=headers)
if r.status_code == 200:
data = r.json()
return {
"address": address,
"price": data.get("data", {}).get("value"),
"source": "birdeye",
}
except Exception:
pass
return None
# ββ SOLANA TRACKER PROVIDER (FREEMIUM, 5K/MO FREE QUOTA) βββββββββ
async def _solana_tracker_price(mint: str = "", **kw) -> dict | None:
"""Solana Tracker β real-time token price (2 keys, 5000 req/mo total)."""
if not mint:
return None
try:
from app.caching_shield.solana_tracker import get_solana_tracker
st = get_solana_tracker()
data = await st.get_price(mint)
if data:
return {"mint": mint, "price": data, "source": "solana_tracker"}
except Exception:
pass
return None
async def _solana_tracker_token(mint: str = "", **kw) -> dict | None:
"""Solana Tracker β detailed token metadata and stats."""
if not mint:
return None
try:
from app.caching_shield.solana_tracker import get_solana_tracker
st = get_solana_tracker()
data = await st.get_token(mint)
if data:
return {"mint": mint, "data": data, "source": "solana_tracker"}
except Exception:
pass
return None
async def _solana_tracker_trending(**kw) -> dict | None:
"""Solana Tracker β trending tokens on Solana."""
try:
from app.caching_shield.solana_tracker import get_solana_tracker
st = get_solana_tracker()
data = await st.get_tokens_trending(limit=20)
if data:
return {"trending": data, "source": "solana_tracker"}
except Exception:
pass
return None
# ββ MESSARI PROVIDER (FREEMIUM, 200 REQ/MIN) βββββββββββββ
async def _messari_news(limit: int = 20, **kw) -> dict | None:
"""Messari News API β curated crypto news with per-asset sentiment scores."""
api_key = kw.get("api_key", "") or os.getenv("MESSARI_API_KEY", "")
if not api_key:
return None
try:
headers = {"X-Messari-API-Key": api_key, "Accept": "application/json"}
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get("https://api.messari.io/news/v1/news/feed", params={"limit": limit}, headers=headers)
if r.status_code == 200:
data = r.json()
if data.get("data"):
# Transform Messari format to our standard format
articles = []
for item in data["data"]:
assets = [a.get("symbol", "Unknown") for a in item.get("assets", [])]
sentiment = item.get("sentiment", [])
avg_sentiment = sum(s.get("sentiment", 0) for s in sentiment) / max(len(sentiment), 1)
articles.append(
{
"title": item.get("title", ""),
"url": item.get("url", ""),
"source": item.get("source", {}).get("sourceName", "Messari"),
"published_at": item.get("publishTime", ""),
"description": item.get("description", ""),
"assets": assets,
"sentiment_score": avg_sentiment,
"category": item.get("category", "news"),
}
)
return {"articles": articles, "source": "messari", "count": len(articles)}
except Exception:
pass
return None
# ββ COINDESK PROVIDER (FREEMIUM, HIGH-QUALITY NEWS) βββββββββββββ
async def _coindesk_news(limit: int = 20, **kw) -> dict | None:
"""CoinDesk News API β institutional-grade crypto news with categorization."""
api_key = kw.get("api_key", "") or os.getenv("COINDESK_API_KEY", "")
if not api_key:
return None
try:
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(
"https://min-api.cryptocompare.com/data/v2/news/",
params={"lang": "EN", "limit": limit, "api_key": api_key},
)
if r.status_code == 200:
data = r.json()
if data.get("Response") == "Success" and data.get("Data"):
articles = []
for item in data["Data"]:
articles.append(
{
"title": item.get("title", ""),
"url": item.get("url", ""),
"source": item.get("source", "CoinDesk"),
"published_at": datetime.fromtimestamp(
item.get("published_on", 0), tz=timezone.utc
).isoformat(),
"description": item.get("body", ""),
"category": item.get("categories", "news").lower(),
"upvotes": item.get("upvotes", 0),
"downvotes": item.get("downvotes", 0),
}
)
return {"articles": articles, "source": "coindesk", "count": len(articles)}
except Exception:
pass
return None
# ββ SANTIMENT PROVIDER (FREEMIUM, DEV ACTIVITY & SOCIAL) βββββββ
async def _santiment_dev_activity(project_slug: str = "bitcoin", **kw) -> dict | None:
"""Santiment β GitHub dev activity and social volume (free tier: 100 calls/day)."""
api_key = kw.get("api_key", "") or os.getenv("SANTIMENT_API_KEY", "")
if not api_key or not project_slug:
return None
try:
query = f"""
{{
getMetric(metric: "dev_activity")
{{
timeseriesData(
slug: "{project_slug}"
from: "30d_ago"
to: "now"
interval: "1d"
)
}}
}}
"""
async with httpx.AsyncClient(timeout=15) as c:
r = await c.post(
"https://api.santiment.net/graphql",
json={"query": query},
headers={"Authorization": f"Apikey {api_key}"},
)
if r.status_code == 200:
data = r.json()
return {
"project": project_slug,
"dev_activity": data.get("data", {}).get("getMetric", {}).get("timeseriesData", []),
"source": "santiment",
}
except Exception:
pass
return None
# ββ VIRUSTOTAL PROVIDER (FREE, 500 REQ/DAY) ββββββββββββββββββββ
async def _virustotal_url_scan(url: str, **kw) -> dict | None:
"""VirusTotal β scan token website URLs for phishing/malware (free: 500 req/day)."""
api_key = kw.get("api_key", "") or os.getenv("VIRUSTOTAL_API_KEY", "")
if not api_key or not url:
return None
try:
import base64
url_id = base64.urlsafe_b64encode(url.encode()).decode().strip("=")
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(f"https://www.virustotal.com/api/v3/urls/{url_id}", headers={"x-apikey": api_key})
if r.status_code == 200:
data = r.json()
stats = data.get("data", {}).get("attributes", {}).get("last_analysis_stats", {})
return {
"url": url,
"malicious": stats.get("malicious", 0),
"suspicious": stats.get("suspicious", 0),
"harmless": stats.get("harmless", 0),
"source": "virustotal",
}
except Exception:
pass
return None
# ββ DUNE ANALYTICS PROVIDER (FREE TIER: 10K CU/MO + FALLBACK) ββ
async def _dune_early_buyers(token_address: str = "", chain: str = "ethereum", **kw) -> dict | None:
"""Dune Analytics β finds the first 5-minute buyers of a token.
Uses dual-key fallback to double free tier capacity (10k CU/mo per key).
Cached aggressively (4 hours) to preserve free tier.
"""
primary_key = kw.get("api_key", "") or os.getenv("DUNE_API_KEY", "")
secondary_key = os.getenv("DUNE_API_KEY_2", "")
if not token_address:
return None
query_id = 3946245 # Replace with actual saved Dune query ID for early buyers
async def _try_dune_key(api_key: str) -> dict | None:
if not api_key:
return None
try:
headers = {"X-Dune-API-Key": api_key}
params = {"token_address": token_address.lower(), "chain": chain.lower()}
async with httpx.AsyncClient(timeout=30) as c:
exec_url = f"https://api.dune.com/api/v1/query/{query_id}/execute"
r_exec = await c.post(exec_url, json={"query_parameters": params}, headers=headers)
# Check for quota/rate limit errors
if r_exec.status_code in (429, 402, 403):
return {"error": "quota_exceeded", "status": r_exec.status_code}
if r_exec.status_code == 200:
exec_id = r_exec.json().get("execution_id")
if exec_id:
for _ in range(3):
await asyncio.sleep(2)
r_result = await c.get(
f"https://api.dune.com/api/v1/execution/{exec_id}/results",
headers=headers,
)
if r_result.status_code == 200:
data = r_result.json()
if data.get("state") == "QUERY_STATE_COMPLETED":
return {
"token": token_address,
"chain": chain,
"early_buyers": data.get("result", {}).get("rows", [])[:20],
"source": "dune",
}
elif r_result.status_code != 202:
break
except Exception as e:
logger.warning(f"Dune query failed with key: {e}")
return None
# Try primary key first
result = await _try_dune_key(primary_key)
# If primary key failed due to quota/rate limit, try secondary key
if isinstance(result, dict) and result.get("error") == "quota_exceeded":
logger.info("Dune primary key quota exceeded, failing over to secondary key")
result = await _try_dune_key(secondary_key)
# If result is the error dict, return None to let DataBus handle fallback
if isinstance(result, dict) and result.get("error") == "quota_exceeded":
return None
return result
# ββ HYPERLIQUID PASS-THROUGH βββββββββββββββββββββββββββββββββββββ
async def _passthrough_hyperliquid(**kwargs) -> dict | None:
"""Hyperliquid perp markets from our own /api/v1/market/hyperliquid."""
try:
limit = kwargs.get("limit", 10)
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(f"http://localhost:8000/api/v1/market/hyperliquid?limit={limit}")
if r.status_code == 200:
return r.json()
except Exception:
pass
return None
async def _passthrough_hyperliquid_action(**kwargs) -> dict | None:
"""Hyperliquid gain/loss porn from our own /api/v1/market/hyperliquid-action."""
try:
limit = kwargs.get("limit", 5)
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(f"http://localhost:8000/api/v1/market/hyperliquid-action?limit={limit}")
if r.status_code == 200:
return r.json()
except Exception:
pass
return None
# ββ INSIDER WALLETS PASS-THROUGH βββββββββββββββββββββββββββββββββ
async def _passthrough_insider_wallets(**kwargs) -> dict | None:
"""Likely insider trader wallets from our own /api/v1/market/insider-wallets."""
try:
limit = kwargs.get("limit", 10)
tier = kwargs.get("tier", "free")
async with httpx.AsyncClient(timeout=10) as c:
r = await c.get(f"http://localhost:8000/api/v1/market/insider-wallets?limit={limit}&tier={tier}")
if r.status_code == 200:
return r.json()
except Exception:
pass
return None
# ββ PREDICTION SIGNALS PASS-THROUGH βββββββββββββββββββββββββββββ
async def _passthrough_prediction_signals(**kwargs) -> dict | None:
"""Prediction market intelligence from our own /api/v1/market/prediction-signals."""
try:
limit = kwargs.get("limit", 5)
tier = kwargs.get("tier", "free")
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(f"http://localhost:8000/api/v1/market/prediction-signals?limit={limit}&tier={tier}")
if r.status_code == 200:
return r.json()
except Exception:
pass
return None
|