solana_client.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. #!/usr/bin/env python3
  2. """
  3. Solana Blockchain CLI Tool for Hermes Agent
  4. --------------------------------------------
  5. Queries the Solana JSON-RPC API and CoinGecko for enriched on-chain data.
  6. Uses only Python standard library — no external packages required.
  7. Usage:
  8. python3 solana_client.py stats
  9. python3 solana_client.py wallet <address> [--limit N] [--all] [--no-prices]
  10. python3 solana_client.py tx <signature>
  11. python3 solana_client.py token <mint_address>
  12. python3 solana_client.py activity <address> [--limit N]
  13. python3 solana_client.py nft <address>
  14. python3 solana_client.py whales [--min-sol N]
  15. python3 solana_client.py price <mint_address_or_symbol>
  16. Environment:
  17. SOLANA_RPC_URL Override the default RPC endpoint (default: mainnet-beta public)
  18. """
  19. import argparse
  20. import json
  21. import os
  22. import sys
  23. import time
  24. import urllib.request
  25. import urllib.error
  26. from typing import Any, Dict, List, Optional
  27. RPC_URL = os.environ.get(
  28. "SOLANA_RPC_URL",
  29. "https://api.mainnet-beta.solana.com",
  30. )
  31. LAMPORTS_PER_SOL = 1_000_000_000
  32. # Well-known Solana token names — avoids API calls for common tokens.
  33. # Maps mint address → (symbol, name).
  34. KNOWN_TOKENS: dict[str, tuple] = {
  35. "So11111111111111111111111111111111111111112": ("SOL", "Solana"),
  36. "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v": ("USDC", "USD Coin"),
  37. "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB": ("USDT", "Tether"),
  38. "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263": ("BONK", "Bonk"),
  39. "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN": ("JUP", "Jupiter"),
  40. "7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs": ("WETH", "Wrapped Ether"),
  41. "jtojtomepa8beP8AuQc6eXt5FriJwfFMwQx2v2f9mCL": ("JTO", "Jito"),
  42. "mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So": ("mSOL", "Marinade Staked SOL"),
  43. "7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj": ("stSOL", "Lido Staked SOL"),
  44. "HZ1JovNiVvGrGNiiYvEozEVgZ58xaU3RKwX8eACQBCt3": ("PYTH", "Pyth Network"),
  45. "RLBxxFkseAZ4RgJH3Sqn8jXxhmGoz9jWxDNJMh8pL7a": ("RLBB", "Rollbit"),
  46. "hntyVP6YFm1Hg25TN9WGLqM12b8TQmcknKrdu1oxWux": ("HNT", "Helium"),
  47. "rndrizKT3MK1iimdxRdWabcF7Zg7AR5T4nud4EkHBof": ("RNDR", "Render"),
  48. "WENWENvqqNya429ubCdR81ZmD69brwQaaBYY6p91oHQQ": ("WEN", "Wen"),
  49. "85VBFQZC9TZkfaptBWjvUw7YbZjy52A6mjtPGjstQAmQ": ("W", "Wormhole"),
  50. "TNSRxcUxoT9xBG3de7PiJyTDYu7kskLqcpddxnEJAS6": ("TNSR", "Tensor"),
  51. "DriFtupJYLTosbwoN8koMbEYSx54aFAVLddWsbksjwg7": ("DRIFT", "Drift"),
  52. "bSo13r4TkiE4KumL71LsHTPpL2euBYLFx6h9HP3piy1": ("bSOL", "BlazeStake Staked SOL"),
  53. "27G8MtK7VtTcCHkpASjSDdkWWYfoqT6ggEuKidVJidD4": ("JLP", "Jupiter LP"),
  54. "EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm": ("WIF", "dogwifhat"),
  55. "MEW1gQWJ3nEXg2qgERiKu7FAFj79PHvQVREQUzScPP5": ("MEW", "cat in a dogs world"),
  56. "ukHH6c7mMyiWCf1b9pnWe25TSpkDDt3H5pQZgZ74J82": ("BOME", "Book of Meme"),
  57. "A8C3xuqscfmyLrte3VwJvtPHXvcSN3FjDbUaSMAkQrCS": ("PENGU", "Pudgy Penguins"),
  58. }
  59. # Reverse lookup: symbol → mint (for the `price` command).
  60. _SYMBOL_TO_MINT = {v[0].upper(): k for k, v in KNOWN_TOKENS.items()}
  61. # ---------------------------------------------------------------------------
  62. # HTTP / RPC helpers
  63. # ---------------------------------------------------------------------------
  64. def _http_get_json(url: str, timeout: int = 10, retries: int = 2) -> Any:
  65. """GET JSON from a URL with retry on 429 rate-limit. Returns parsed JSON or None."""
  66. for attempt in range(retries + 1):
  67. req = urllib.request.Request(
  68. url, headers={"Accept": "application/json", "User-Agent": "HermesAgent/1.0"},
  69. )
  70. try:
  71. with urllib.request.urlopen(req, timeout=timeout) as resp:
  72. return json.load(resp)
  73. except urllib.error.HTTPError as exc:
  74. if exc.code == 429 and attempt < retries:
  75. time.sleep(2.0 * (attempt + 1))
  76. continue
  77. return None
  78. except Exception:
  79. return None
  80. return None
  81. def _rpc_call(method: str, params: list | None = None, retries: int = 2) -> Any:
  82. """Send a JSON-RPC request with retry on 429 rate-limit."""
  83. payload = json.dumps({
  84. "jsonrpc": "2.0", "id": 1,
  85. "method": method, "params": params or [],
  86. }).encode()
  87. for attempt in range(retries + 1):
  88. req = urllib.request.Request(
  89. RPC_URL, data=payload,
  90. headers={"Content-Type": "application/json"}, method="POST",
  91. )
  92. try:
  93. with urllib.request.urlopen(req, timeout=20) as resp:
  94. body = json.load(resp)
  95. if "error" in body:
  96. err = body["error"]
  97. # Rate-limit: retry after delay
  98. if isinstance(err, dict) and err.get("code") == 429:
  99. if attempt < retries:
  100. time.sleep(1.5 * (attempt + 1))
  101. continue
  102. sys.exit(f"RPC error: {err}")
  103. return body.get("result")
  104. except urllib.error.HTTPError as exc:
  105. if exc.code == 429 and attempt < retries:
  106. time.sleep(1.5 * (attempt + 1))
  107. continue
  108. sys.exit(f"RPC HTTP error: {exc}")
  109. except urllib.error.URLError as exc:
  110. sys.exit(f"RPC connection error: {exc}")
  111. return None
  112. # Keep backward compat — the rest of the code uses `rpc()`.
  113. rpc = _rpc_call
  114. def rpc_batch(calls: list) -> list:
  115. """Send a batch of JSON-RPC requests (with retry on 429)."""
  116. payload = json.dumps([
  117. {"jsonrpc": "2.0", "id": i, "method": c["method"], "params": c.get("params", [])}
  118. for i, c in enumerate(calls)
  119. ]).encode()
  120. for attempt in range(3):
  121. req = urllib.request.Request(
  122. RPC_URL, data=payload,
  123. headers={"Content-Type": "application/json"}, method="POST",
  124. )
  125. try:
  126. with urllib.request.urlopen(req, timeout=20) as resp:
  127. return json.load(resp)
  128. except urllib.error.HTTPError as exc:
  129. if exc.code == 429 and attempt < 2:
  130. time.sleep(1.5 * (attempt + 1))
  131. continue
  132. sys.exit(f"RPC batch HTTP error: {exc}")
  133. except urllib.error.URLError as exc:
  134. sys.exit(f"RPC batch error: {exc}")
  135. return []
  136. def lamports_to_sol(lamports: int) -> float:
  137. return lamports / LAMPORTS_PER_SOL
  138. def print_json(obj: Any) -> None:
  139. print(json.dumps(obj, indent=2))
  140. def _short_mint(mint: str) -> str:
  141. """Abbreviate a mint address for display: first 4 + last 4."""
  142. if len(mint) <= 12:
  143. return mint
  144. return f"{mint[:4]}...{mint[-4:]}"
  145. # ---------------------------------------------------------------------------
  146. # Price & token name helpers (CoinGecko — free, no API key)
  147. # ---------------------------------------------------------------------------
  148. def fetch_prices(mints: list[str], max_lookups: int = 20) -> dict[str, float]:
  149. """Fetch USD prices for mint addresses via CoinGecko (one per request).
  150. CoinGecko free tier doesn't support batch Solana token lookups,
  151. so we do individual calls — capped at *max_lookups* to stay within
  152. rate limits. Returns {mint: usd_price}.
  153. """
  154. prices: dict[str, float] = {}
  155. for i, mint in enumerate(mints[:max_lookups]):
  156. url = (
  157. f"https://api.coingecko.com/api/v3/simple/token_price/solana"
  158. f"?contract_addresses={mint}&vs_currencies=usd"
  159. )
  160. data = _http_get_json(url, timeout=10)
  161. if data and isinstance(data, dict):
  162. for addr, info in data.items():
  163. if isinstance(info, dict) and "usd" in info:
  164. prices[mint] = info["usd"]
  165. break
  166. # Pause between calls to respect CoinGecko free-tier rate-limits
  167. if i < len(mints[:max_lookups]) - 1:
  168. time.sleep(1.0)
  169. return prices
  170. def fetch_sol_price() -> Optional[float]:
  171. """Fetch current SOL price in USD via CoinGecko."""
  172. data = _http_get_json(
  173. "https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd"
  174. )
  175. if data and "solana" in data:
  176. return data["solana"].get("usd")
  177. return None
  178. def resolve_token_name(mint: str) -> Optional[dict[str, str]]:
  179. """Look up token name and symbol from CoinGecko by mint address.
  180. Returns {"name": ..., "symbol": ...} or None.
  181. """
  182. if mint in KNOWN_TOKENS:
  183. sym, name = KNOWN_TOKENS[mint]
  184. return {"symbol": sym, "name": name}
  185. url = f"https://api.coingecko.com/api/v3/coins/solana/contract/{mint}"
  186. data = _http_get_json(url, timeout=10)
  187. if data and "symbol" in data:
  188. return {"symbol": data["symbol"].upper(), "name": data.get("name", "")}
  189. return None
  190. def _token_label(mint: str) -> str:
  191. """Return a human-readable label for a mint: symbol if known, else abbreviated address."""
  192. if mint in KNOWN_TOKENS:
  193. return KNOWN_TOKENS[mint][0]
  194. return _short_mint(mint)
  195. # ---------------------------------------------------------------------------
  196. # 1. Network Stats
  197. # ---------------------------------------------------------------------------
  198. def cmd_stats(_args):
  199. """Live Solana network: slot, epoch, TPS, supply, version, SOL price."""
  200. results = rpc_batch([
  201. {"method": "getSlot"},
  202. {"method": "getEpochInfo"},
  203. {"method": "getRecentPerformanceSamples", "params": [1]},
  204. {"method": "getSupply"},
  205. {"method": "getVersion"},
  206. ])
  207. by_id = {r["id"]: r.get("result") for r in results}
  208. slot = by_id.get(0)
  209. epoch_info = by_id.get(1)
  210. perf_samples = by_id.get(2)
  211. supply = by_id.get(3)
  212. version = by_id.get(4)
  213. tps = None
  214. if perf_samples:
  215. s = perf_samples[0]
  216. tps = round(s["numTransactions"] / s["samplePeriodSecs"], 1)
  217. total_supply = lamports_to_sol(supply["value"]["total"]) if supply else None
  218. circ_supply = lamports_to_sol(supply["value"]["circulating"]) if supply else None
  219. sol_price = fetch_sol_price()
  220. out = {
  221. "slot": slot,
  222. "epoch": epoch_info.get("epoch") if epoch_info else None,
  223. "slot_in_epoch": epoch_info.get("slotIndex") if epoch_info else None,
  224. "tps": tps,
  225. "total_supply_SOL": round(total_supply, 2) if total_supply else None,
  226. "circulating_supply_SOL": round(circ_supply, 2) if circ_supply else None,
  227. "validator_version": version.get("solana-core") if version else None,
  228. }
  229. if sol_price is not None:
  230. out["sol_price_usd"] = sol_price
  231. if circ_supply:
  232. out["market_cap_usd"] = round(sol_price * circ_supply, 0)
  233. print_json(out)
  234. # ---------------------------------------------------------------------------
  235. # 2. Wallet Info (enhanced with prices, sorting, filtering)
  236. # ---------------------------------------------------------------------------
  237. def cmd_wallet(args):
  238. """SOL balance + SPL token holdings with USD values."""
  239. address = args.address
  240. show_all = getattr(args, "all", False)
  241. limit = getattr(args, "limit", 20) or 20
  242. skip_prices = getattr(args, "no_prices", False)
  243. # Fetch SOL balance
  244. balance_result = rpc("getBalance", [address])
  245. sol_balance = lamports_to_sol(balance_result["value"])
  246. # Fetch all SPL token accounts
  247. token_result = rpc("getTokenAccountsByOwner", [
  248. address,
  249. {"programId": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},
  250. {"encoding": "jsonParsed"},
  251. ])
  252. raw_tokens = []
  253. for acct in (token_result.get("value") or []):
  254. info = acct["account"]["data"]["parsed"]["info"]
  255. ta = info["tokenAmount"]
  256. amount = float(ta.get("uiAmountString") or 0)
  257. if amount > 0:
  258. raw_tokens.append({
  259. "mint": info["mint"],
  260. "amount": amount,
  261. "decimals": ta["decimals"],
  262. })
  263. # Separate NFTs (amount=1, decimals=0) from fungible tokens
  264. nfts = [t for t in raw_tokens if t["decimals"] == 0 and t["amount"] == 1]
  265. fungible = [t for t in raw_tokens if not (t["decimals"] == 0 and t["amount"] == 1)]
  266. # Fetch prices for fungible tokens (cap lookups to avoid API abuse)
  267. sol_price = None
  268. prices: dict[str, float] = {}
  269. if not skip_prices and fungible:
  270. sol_price = fetch_sol_price()
  271. # Prioritize known tokens, then a small sample of unknowns.
  272. # CoinGecko free tier = 1 request per mint, so we cap lookups.
  273. known_mints = [t["mint"] for t in fungible if t["mint"] in KNOWN_TOKENS]
  274. other_mints = [t["mint"] for t in fungible if t["mint"] not in KNOWN_TOKENS][:15]
  275. mints_to_price = known_mints + other_mints
  276. if mints_to_price:
  277. prices = fetch_prices(mints_to_price, max_lookups=30)
  278. # Enrich tokens with labels and USD values
  279. enriched = []
  280. dust_count = 0
  281. dust_value = 0.0
  282. for t in fungible:
  283. mint = t["mint"]
  284. label = _token_label(mint)
  285. usd_price = prices.get(mint)
  286. usd_value = round(usd_price * t["amount"], 2) if usd_price else None
  287. # Filter dust (< $0.01) unless --all
  288. if not show_all and usd_value is not None and usd_value < 0.01:
  289. dust_count += 1
  290. dust_value += usd_value
  291. continue
  292. entry = {"token": label, "mint": mint, "amount": t["amount"]}
  293. if usd_price is not None:
  294. entry["price_usd"] = usd_price
  295. entry["value_usd"] = usd_value
  296. enriched.append(entry)
  297. # Sort: tokens with known USD value first (highest→lowest), then unknowns
  298. enriched.sort(key=lambda x: (x.get("value_usd") is not None, x.get("value_usd") or 0), reverse=True)
  299. # Apply limit unless --all
  300. total_tokens = len(enriched)
  301. if not show_all and len(enriched) > limit:
  302. enriched = enriched[:limit]
  303. # Compute portfolio total
  304. total_usd = sum(t.get("value_usd", 0) for t in enriched)
  305. sol_value_usd = round(sol_price * sol_balance, 2) if sol_price else None
  306. if sol_value_usd:
  307. total_usd += sol_value_usd
  308. total_usd += dust_value
  309. output = {
  310. "address": address,
  311. "sol_balance": round(sol_balance, 9),
  312. }
  313. if sol_price:
  314. output["sol_price_usd"] = sol_price
  315. output["sol_value_usd"] = sol_value_usd
  316. output["tokens_shown"] = len(enriched)
  317. if total_tokens > len(enriched):
  318. output["tokens_hidden"] = total_tokens - len(enriched)
  319. output["spl_tokens"] = enriched
  320. if dust_count > 0:
  321. output["dust_filtered"] = {"count": dust_count, "total_value_usd": round(dust_value, 4)}
  322. output["nft_count"] = len(nfts)
  323. if nfts:
  324. output["nfts"] = [_token_label(n["mint"]) + f" ({_short_mint(n['mint'])})" for n in nfts[:10]]
  325. if len(nfts) > 10:
  326. output["nfts"].append(f"... and {len(nfts) - 10} more")
  327. if total_usd > 0:
  328. output["portfolio_total_usd"] = round(total_usd, 2)
  329. print_json(output)
  330. # ---------------------------------------------------------------------------
  331. # 3. Transaction Details
  332. # ---------------------------------------------------------------------------
  333. def cmd_tx(args):
  334. """Full transaction details by signature."""
  335. result = rpc("getTransaction", [
  336. args.signature,
  337. {"encoding": "jsonParsed", "maxSupportedTransactionVersion": 0},
  338. ])
  339. if result is None:
  340. sys.exit("Transaction not found (may be too old for public RPC history).")
  341. meta = result.get("meta", {}) or {}
  342. msg = result.get("transaction", {}).get("message", {})
  343. account_keys = msg.get("accountKeys", [])
  344. pre = meta.get("preBalances", [])
  345. post = meta.get("postBalances", [])
  346. balance_changes = []
  347. for i, key in enumerate(account_keys):
  348. acct_key = key["pubkey"] if isinstance(key, dict) else key
  349. if i < len(pre) and i < len(post):
  350. change = lamports_to_sol(post[i] - pre[i])
  351. if change != 0:
  352. balance_changes.append({"account": acct_key, "change_SOL": round(change, 9)})
  353. programs = []
  354. for ix in msg.get("instructions", []):
  355. prog = ix.get("programId")
  356. if prog is None and "programIdIndex" in ix:
  357. k = account_keys[ix["programIdIndex"]]
  358. prog = k["pubkey"] if isinstance(k, dict) else k
  359. if prog:
  360. programs.append(prog)
  361. # Add USD value for SOL changes
  362. sol_price = fetch_sol_price()
  363. if sol_price and balance_changes:
  364. for bc in balance_changes:
  365. bc["change_USD"] = round(bc["change_SOL"] * sol_price, 2)
  366. print_json({
  367. "signature": args.signature,
  368. "slot": result.get("slot"),
  369. "block_time": result.get("blockTime"),
  370. "fee_SOL": lamports_to_sol(meta.get("fee", 0)),
  371. "status": "success" if meta.get("err") is None else "failed",
  372. "balance_changes": balance_changes,
  373. "programs_invoked": list(dict.fromkeys(programs)),
  374. })
  375. # ---------------------------------------------------------------------------
  376. # 4. Token Info (enhanced with name + price)
  377. # ---------------------------------------------------------------------------
  378. def cmd_token(args):
  379. """SPL token metadata, supply, decimals, price, top holders."""
  380. mint = args.mint
  381. mint_info = rpc("getAccountInfo", [mint, {"encoding": "jsonParsed"}])
  382. if mint_info is None or mint_info.get("value") is None:
  383. sys.exit("Mint account not found.")
  384. parsed = mint_info["value"]["data"]["parsed"]["info"]
  385. decimals = parsed.get("decimals", 0)
  386. supply_raw = int(parsed.get("supply", 0))
  387. supply_human = supply_raw / (10 ** decimals) if decimals else supply_raw
  388. largest = rpc("getTokenLargestAccounts", [mint])
  389. holders = []
  390. for acct in (largest.get("value") or [])[:5]:
  391. amount = float(acct.get("uiAmountString") or 0)
  392. pct = round((amount / supply_human * 100), 4) if supply_human > 0 else 0
  393. holders.append({
  394. "account": acct["address"],
  395. "amount": amount,
  396. "percent": pct,
  397. })
  398. # Resolve name + price
  399. token_meta = resolve_token_name(mint)
  400. price_data = fetch_prices([mint])
  401. out = {"mint": mint}
  402. if token_meta:
  403. out["name"] = token_meta["name"]
  404. out["symbol"] = token_meta["symbol"]
  405. out["decimals"] = decimals
  406. out["supply"] = round(supply_human, min(decimals, 6))
  407. out["mint_authority"] = parsed.get("mintAuthority")
  408. out["freeze_authority"] = parsed.get("freezeAuthority")
  409. if mint in price_data:
  410. out["price_usd"] = price_data[mint]
  411. out["market_cap_usd"] = round(price_data[mint] * supply_human, 0)
  412. out["top_5_holders"] = holders
  413. print_json(out)
  414. # ---------------------------------------------------------------------------
  415. # 5. Recent Activity
  416. # ---------------------------------------------------------------------------
  417. def cmd_activity(args):
  418. """Recent transaction signatures for an address."""
  419. limit = min(args.limit, 25)
  420. result = rpc("getSignaturesForAddress", [args.address, {"limit": limit}])
  421. txs = [
  422. {
  423. "signature": item["signature"],
  424. "slot": item.get("slot"),
  425. "block_time": item.get("blockTime"),
  426. "err": item.get("err"),
  427. }
  428. for item in (result or [])
  429. ]
  430. print_json({"address": args.address, "transactions": txs})
  431. # ---------------------------------------------------------------------------
  432. # 6. NFT Portfolio
  433. # ---------------------------------------------------------------------------
  434. def cmd_nft(args):
  435. """NFTs owned by a wallet (amount=1 && decimals=0 heuristic)."""
  436. result = rpc("getTokenAccountsByOwner", [
  437. args.address,
  438. {"programId": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},
  439. {"encoding": "jsonParsed"},
  440. ])
  441. nfts = [
  442. acct["account"]["data"]["parsed"]["info"]["mint"]
  443. for acct in (result.get("value") or [])
  444. if acct["account"]["data"]["parsed"]["info"]["tokenAmount"]["decimals"] == 0
  445. and int(acct["account"]["data"]["parsed"]["info"]["tokenAmount"]["amount"]) == 1
  446. ]
  447. print_json({
  448. "address": args.address,
  449. "nft_count": len(nfts),
  450. "nfts": nfts,
  451. "note": "Heuristic only. Compressed NFTs (cNFTs) are not detected.",
  452. })
  453. # ---------------------------------------------------------------------------
  454. # 7. Whale Detector (enhanced with USD values)
  455. # ---------------------------------------------------------------------------
  456. def cmd_whales(args):
  457. """Scan the latest block for large SOL transfers."""
  458. min_lamports = int(args.min_sol * LAMPORTS_PER_SOL)
  459. slot = rpc("getSlot")
  460. block = rpc("getBlock", [
  461. slot,
  462. {
  463. "encoding": "jsonParsed",
  464. "transactionDetails": "full",
  465. "maxSupportedTransactionVersion": 0,
  466. "rewards": False,
  467. },
  468. ])
  469. if block is None:
  470. sys.exit("Could not retrieve latest block.")
  471. sol_price = fetch_sol_price()
  472. whales = []
  473. for tx in (block.get("transactions") or []):
  474. meta = tx.get("meta", {}) or {}
  475. if meta.get("err") is not None:
  476. continue
  477. msg = tx["transaction"].get("message", {})
  478. account_keys = msg.get("accountKeys", [])
  479. pre = meta.get("preBalances", [])
  480. post = meta.get("postBalances", [])
  481. for i in range(len(pre)):
  482. change = post[i] - pre[i]
  483. if change >= min_lamports:
  484. k = account_keys[i]
  485. receiver = k["pubkey"] if isinstance(k, dict) else k
  486. sender = None
  487. for j in range(len(pre)):
  488. if pre[j] - post[j] >= min_lamports:
  489. sk = account_keys[j]
  490. sender = sk["pubkey"] if isinstance(sk, dict) else sk
  491. break
  492. entry = {
  493. "sender": sender,
  494. "receiver": receiver,
  495. "amount_SOL": round(lamports_to_sol(change), 4),
  496. }
  497. if sol_price:
  498. entry["amount_USD"] = round(lamports_to_sol(change) * sol_price, 2)
  499. whales.append(entry)
  500. out = {
  501. "slot": slot,
  502. "min_threshold_SOL": args.min_sol,
  503. "large_transfers": whales,
  504. "note": "Scans latest block only — point-in-time snapshot.",
  505. }
  506. if sol_price:
  507. out["sol_price_usd"] = sol_price
  508. print_json(out)
  509. # ---------------------------------------------------------------------------
  510. # 8. Price Lookup
  511. # ---------------------------------------------------------------------------
  512. def cmd_price(args):
  513. """Quick price lookup for a token by mint address or known symbol."""
  514. query = args.token
  515. # Check if it's a known symbol
  516. mint = _SYMBOL_TO_MINT.get(query.upper(), query)
  517. # Try to resolve name
  518. token_meta = resolve_token_name(mint)
  519. # Fetch price
  520. prices = fetch_prices([mint])
  521. out = {"query": query, "mint": mint}
  522. if token_meta:
  523. out["name"] = token_meta["name"]
  524. out["symbol"] = token_meta["symbol"]
  525. if mint in prices:
  526. out["price_usd"] = prices[mint]
  527. else:
  528. out["price_usd"] = None
  529. out["note"] = "Price not available — token may not be listed on CoinGecko."
  530. print_json(out)
  531. # ---------------------------------------------------------------------------
  532. # CLI
  533. # ---------------------------------------------------------------------------
  534. def main():
  535. parser = argparse.ArgumentParser(
  536. prog="solana_client.py",
  537. description="Solana blockchain query tool for Hermes Agent",
  538. )
  539. sub = parser.add_subparsers(dest="command", required=True)
  540. sub.add_parser("stats", help="Network stats: slot, epoch, TPS, supply, SOL price")
  541. p_wallet = sub.add_parser("wallet", help="SOL balance + SPL tokens with USD values")
  542. p_wallet.add_argument("address")
  543. p_wallet.add_argument("--limit", type=int, default=20,
  544. help="Max tokens to display (default: 20)")
  545. p_wallet.add_argument("--all", action="store_true",
  546. help="Show all tokens (no limit, no dust filter)")
  547. p_wallet.add_argument("--no-prices", action="store_true",
  548. help="Skip price lookups (faster, RPC-only)")
  549. p_tx = sub.add_parser("tx", help="Transaction details by signature")
  550. p_tx.add_argument("signature")
  551. p_token = sub.add_parser("token", help="SPL token metadata, price, and top holders")
  552. p_token.add_argument("mint")
  553. p_activity = sub.add_parser("activity", help="Recent transactions for an address")
  554. p_activity.add_argument("address")
  555. p_activity.add_argument("--limit", type=int, default=10,
  556. help="Number of transactions (max 25, default 10)")
  557. p_nft = sub.add_parser("nft", help="NFT portfolio for a wallet")
  558. p_nft.add_argument("address")
  559. p_whales = sub.add_parser("whales", help="Large SOL transfers in the latest block")
  560. p_whales.add_argument("--min-sol", type=float, default=1000.0,
  561. help="Minimum SOL transfer size (default: 1000)")
  562. p_price = sub.add_parser("price", help="Quick price lookup by mint or symbol")
  563. p_price.add_argument("token", help="Mint address or known symbol (SOL, BONK, JUP, ...)")
  564. args = parser.parse_args()
  565. dispatch = {
  566. "stats": cmd_stats,
  567. "wallet": cmd_wallet,
  568. "tx": cmd_tx,
  569. "token": cmd_token,
  570. "activity": cmd_activity,
  571. "nft": cmd_nft,
  572. "whales": cmd_whales,
  573. "price": cmd_price,
  574. }
  575. dispatch[args.command](args)
  576. if __name__ == "__main__":
  577. main()