evm_client.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508
  1. #!/usr/bin/env python3
  2. """
  3. evm_client.py — EVM blockchain CLI tool for the Hermes Agent project.
  4. Zero external dependencies. Uses stdlib only: urllib, json, argparse, time, os, sys, typing.
  5. """
  6. import argparse
  7. import json
  8. import os
  9. import sys
  10. import time
  11. import urllib.error
  12. import urllib.request
  13. from typing import Any, Dict, List, Optional, Tuple
  14. # ---------------------------------------------------------------------------
  15. # Chain registry
  16. # ---------------------------------------------------------------------------
  17. CHAINS: dict[str, dict[str, Any]] = {
  18. "ethereum": {
  19. "chain_id": 1,
  20. "rpc": "https://ethereum-rpc.publicnode.com",
  21. "native": "ETH",
  22. "coingecko": "ethereum",
  23. "explorer": "https://etherscan.io",
  24. "decimals": 18,
  25. },
  26. "bsc": {
  27. "chain_id": 56,
  28. "rpc": "https://bsc-dataseed1.binance.org",
  29. "native": "BNB",
  30. "coingecko": "binancecoin",
  31. "explorer": "https://bscscan.com",
  32. "decimals": 18,
  33. },
  34. "base": {
  35. "chain_id": 8453,
  36. "rpc": "https://mainnet.base.org",
  37. "native": "ETH",
  38. "coingecko": "ethereum",
  39. "explorer": "https://basescan.org",
  40. "decimals": 18,
  41. },
  42. "arbitrum": {
  43. "chain_id": 42161,
  44. "rpc": "https://arb1.arbitrum.io/rpc",
  45. "native": "ETH",
  46. "coingecko": "ethereum",
  47. "explorer": "https://arbiscan.io",
  48. "decimals": 18,
  49. },
  50. "polygon": {
  51. "chain_id": 137,
  52. "rpc": "https://polygon-rpc.com",
  53. "native": "MATIC",
  54. "coingecko": "matic-network",
  55. "explorer": "https://polygonscan.com",
  56. "decimals": 18,
  57. },
  58. "optimism": {
  59. "chain_id": 10,
  60. "rpc": "https://mainnet.optimism.io",
  61. "native": "ETH",
  62. "coingecko": "ethereum",
  63. "explorer": "https://optimistic.etherscan.io",
  64. "decimals": 18,
  65. },
  66. "avalanche": {
  67. "chain_id": 43114,
  68. "rpc": "https://api.avax.network/ext/bc/C/rpc",
  69. "native": "AVAX",
  70. "coingecko": "avalanche-2",
  71. "explorer": "https://snowtrace.io",
  72. "decimals": 18,
  73. },
  74. "zksync": {
  75. "chain_id": 324,
  76. "rpc": "https://mainnet.era.zksync.io",
  77. "native": "ETH",
  78. "coingecko": "ethereum",
  79. "explorer": "https://explorer.zksync.io",
  80. "decimals": 18,
  81. },
  82. }
  83. DEFAULT_CHAIN = "ethereum"
  84. # ---------------------------------------------------------------------------
  85. # Known ERC-20 token registry {chain -> {symbol -> address}}
  86. # ---------------------------------------------------------------------------
  87. KNOWN_TOKENS: dict[str, dict[str, str]] = {
  88. "ethereum": {
  89. "USDT": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
  90. "USDC": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
  91. "DAI": "0x6B175474E89094C44Da98b954EedeAC495271d0F",
  92. "WETH": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
  93. "WBTC": "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",
  94. "LINK": "0x514910771AF9Ca656af840dff83E8264EcF986CA",
  95. "UNI": "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",
  96. "AAVE": "0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9",
  97. "MKR": "0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2",
  98. "COMP": "0xc00e94Cb662C3520282E6f5717214004A7f26888",
  99. "SNX": "0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F",
  100. "CRV": "0xD533a949740bb3306d119CC777fa900bA034cd52",
  101. "LDO": "0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32",
  102. "RPL": "0xD33526068D116cE69F19A9ee46F0bd304F21A51f",
  103. "MATIC": "0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0",
  104. "SHIB": "0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE",
  105. "APE": "0x4d224452801ACEd8B2F0aebE155379bb5D594381",
  106. "GRT": "0xc944E90C64B2c07662A292be6244BDf05Cda44a7",
  107. "FXS": "0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0",
  108. "FRAX": "0x853d955aCEf822Db058eb8505911ED77F175b99e",
  109. "BAL": "0xba100000625a3754423978a60c9317c58a424e3D",
  110. "SUSHI": "0x6B3595068778DD592e39A122f4f5a5cF09C90fE2",
  111. "YFI": "0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e",
  112. "1INCH": "0x111111111117dC0aa78b770fA6A738034120C302",
  113. "ENS": "0xC18360217D8F7Ab5e7c516566761Ea12Ce7F9D72",
  114. "IMX": "0xF57e7e7C23978C3cAEC3C3548E3D615c346e79fF",
  115. "SAND": "0x3845badAde8e6dFF049820680d1F14bD3903a5d0",
  116. "MANA": "0x0F5D2fB29fb7d3CFeE444a200298f468908cC942",
  117. "AXS": "0xBB0E17EF65F82Ab018d8EDd776e8DD940327B28b",
  118. "CHZ": "0x3506424F91fD33084466F402d5D97f05F8e3b4AF",
  119. "PEPE": "0x6982508145454Ce325dDbE47a25d4ec3d2311933",
  120. },
  121. "bsc": {
  122. "USDT": "0x55d398326f99059fF775485246999027B3197955",
  123. "USDC": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
  124. "BUSD": "0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56",
  125. "WBNB": "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",
  126. "CAKE": "0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82",
  127. "XVS": "0xcF6BB5389c92Bdda8a3747Ddb454cB7a64626C63",
  128. "ALPACA":"0x8F0528cE5eF7B51152A59745bEfDD91D97091d2F",
  129. "BAKE": "0xE02dF9e3e622DeBdD69fb838bB799E3F168902c5",
  130. "BURGER":"0xAe9269f27437f0fcBC232d39Ec814844a51d6b8f",
  131. "DOGE": "0xbA2aE424d960c26247Dd6c32edC70B295c744C43",
  132. },
  133. "base": {
  134. # Stables + wrapped
  135. "USDC": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
  136. "DAI": "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb",
  137. "WETH": "0x4200000000000000000000000000000000000006",
  138. # Liquid-staked ETH variants
  139. "cbETH": "0x2Ae3F1Ec7F1F5012CFEab0185bfc7aa3cF0DEc22",
  140. "wstETH": "0xc1CBa3fCea344f92D9239c08C0568f6F2F0ee452",
  141. "rETH": "0xB6fe221Fe9EeF5aBa221c348bA20A1Bf5e73624c",
  142. "cbBTC": "0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf",
  143. # Base-native DeFi + meme tokens (carried over from the standalone base/ skill)
  144. "AERO": "0x940181a94A35A4569E4529A3CDfB74e38FD98631",
  145. "DEGEN": "0x4ed4E862860beD51a9570b96d89aF5E1B0Efefed",
  146. "TOSHI": "0xAC1Bd2486aAf3B5C0fc3Fd868558b082a531B2B4",
  147. "BRETT": "0x532f27101965dd16442E59d40670FaF5eBB142E4",
  148. "WELL": "0xA88594D404727625A9437C3f886C7643872296AE",
  149. },
  150. "arbitrum": {
  151. "USDC": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
  152. "USDT": "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",
  153. "WETH": "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
  154. "ARB": "0x912CE59144191C1204E64559FE8253a0e49E6548",
  155. },
  156. "optimism": {
  157. "USDC": "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",
  158. "USDT": "0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",
  159. "WETH": "0x4200000000000000000000000000000000000006",
  160. "OP": "0x4200000000000000000000000000000000000042",
  161. },
  162. "polygon": {
  163. "USDC": "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
  164. "USDT": "0xc2132D05D31c914a87C6611C10748AEb04B58e8F",
  165. "WMATIC":"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",
  166. "WETH": "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619",
  167. "DAI": "0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063",
  168. },
  169. "avalanche": {
  170. "USDC": "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",
  171. "USDT": "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",
  172. "WAVAX": "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",
  173. },
  174. }
  175. # Gas estimates (units) for common operations
  176. GAS_ESTIMATES = {
  177. "transfer": 21_000,
  178. "erc20": 65_000,
  179. "approve": 46_000,
  180. "swap": 180_000,
  181. "nft_mint": 150_000,
  182. "nft_transfer": 85_000,
  183. }
  184. # CoinGecko symbol -> id map for common tokens
  185. COINGECKO_IDS: dict[str, str] = {
  186. "ETH": "ethereum",
  187. "BTC": "bitcoin",
  188. "BNB": "binancecoin",
  189. "MATIC": "matic-network",
  190. "AVAX": "avalanche-2",
  191. "USDT": "tether",
  192. "USDC": "usd-coin",
  193. "DAI": "dai",
  194. "WBTC": "wrapped-bitcoin",
  195. "WETH": "weth",
  196. "LINK": "chainlink",
  197. "UNI": "uniswap",
  198. "AAVE": "aave",
  199. "MKR": "maker",
  200. "COMP": "compound-governance-token",
  201. "SNX": "havven",
  202. "CRV": "curve-dao-token",
  203. "LDO": "lido-dao",
  204. "RPL": "rocket-pool",
  205. "SHIB": "shiba-inu",
  206. "APE": "apecoin",
  207. "GRT": "the-graph",
  208. "BAL": "balancer",
  209. "SUSHI": "sushi",
  210. "YFI": "yearn-finance",
  211. "1INCH": "1inch",
  212. "ENS": "ethereum-name-service",
  213. "IMX": "immutable-x",
  214. "SAND": "the-sandbox",
  215. "MANA": "decentraland",
  216. "AXS": "axie-infinity",
  217. "ARB": "arbitrum",
  218. "OP": "optimism",
  219. "CAKE": "pancakeswap-token",
  220. "PEPE": "pepe",
  221. "CHZ": "chiliz",
  222. }
  223. # ---------------------------------------------------------------------------
  224. # Helper utilities
  225. # ---------------------------------------------------------------------------
  226. def hex_to_int(h: str) -> int:
  227. if not h or h == "0x":
  228. return 0
  229. return int(h, 16)
  230. # ---------------------------------------------------------------------------
  231. # Input validation
  232. # ---------------------------------------------------------------------------
  233. def is_valid_address(s: str) -> bool:
  234. """Return True if `s` looks like a 20-byte hex Ethereum address.
  235. Does NOT validate EIP-55 checksum — RPC endpoints accept any-case hex.
  236. Just guards against typos / wrong-length input before we burn an RPC call.
  237. """
  238. if not isinstance(s, str):
  239. return False
  240. if not s.startswith("0x") and not s.startswith("0X"):
  241. return False
  242. if len(s) != 42:
  243. return False
  244. try:
  245. int(s, 16)
  246. except ValueError:
  247. return False
  248. return True
  249. def is_valid_txhash(s: str) -> bool:
  250. """Return True if `s` looks like a 32-byte hex transaction hash."""
  251. if not isinstance(s, str):
  252. return False
  253. if not s.startswith("0x") and not s.startswith("0X"):
  254. return False
  255. if len(s) != 66:
  256. return False
  257. try:
  258. int(s, 16)
  259. except ValueError:
  260. return False
  261. return True
  262. def require_address(s: str, *, field: str = "address") -> str:
  263. """Return `s` lowercased if valid, else exit with an error message.
  264. Centralizing validation here means every subcommand fails fast on bad input
  265. instead of bubbling up an opaque RPC error 30 seconds later.
  266. """
  267. if not is_valid_address(s):
  268. sys.stderr.write(
  269. f"error: invalid {field} {s!r}: expected 0x-prefixed 40-hex-char address\n"
  270. )
  271. sys.exit(2)
  272. return s.lower()
  273. def require_txhash(s: str, *, field: str = "tx hash") -> str:
  274. """Return `s` lowercased if valid, else exit with an error message."""
  275. if not is_valid_txhash(s):
  276. sys.stderr.write(
  277. f"error: invalid {field} {s!r}: expected 0x-prefixed 64-hex-char tx hash\n"
  278. )
  279. sys.exit(2)
  280. return s.lower()
  281. def wei_to_native(wei: int, decimals: int = 18) -> float:
  282. return wei / (10 ** decimals)
  283. def gwei_from_wei(wei: int) -> float:
  284. return wei / 1e9
  285. def _short_addr(addr: str) -> str:
  286. if addr and len(addr) >= 10:
  287. return addr[:6] + "..." + addr[-4:]
  288. return addr or ""
  289. def print_json(data: Any) -> None:
  290. print(json.dumps(data, indent=2, default=str))
  291. # ---------------------------------------------------------------------------
  292. # HTTP / JSON-RPC layer
  293. # ---------------------------------------------------------------------------
  294. def _http_post(url: str, payload: Any, retries: int = 5, timeout: int = 20) -> Any:
  295. body = json.dumps(payload).encode()
  296. headers = {
  297. "Content-Type": "application/json",
  298. "Accept": "application/json",
  299. "User-Agent": "Mozilla/5.0 (compatible; evm_client/1.0)",
  300. }
  301. req = urllib.request.Request(url, data=body, headers=headers, method="POST")
  302. delay = 1.0
  303. last_err: Exception = RuntimeError("No attempts made")
  304. for attempt in range(retries):
  305. try:
  306. with urllib.request.urlopen(req, timeout=timeout) as resp:
  307. return json.loads(resp.read().decode())
  308. except urllib.error.HTTPError as e:
  309. if e.code == 429:
  310. time.sleep(delay)
  311. delay = min(delay * 2, 30)
  312. last_err = e
  313. continue
  314. body_text = ""
  315. try:
  316. body_text = e.read().decode()
  317. except Exception:
  318. pass
  319. raise RuntimeError(f"HTTP {e.code}: {body_text}") from e
  320. except Exception as e:
  321. last_err = e
  322. if attempt < retries - 1:
  323. time.sleep(delay)
  324. delay = min(delay * 2, 30)
  325. raise RuntimeError(f"Request failed after {retries} retries: {last_err}") from last_err
  326. def _http_get(url: str, retries: int = 5, timeout: int = 20) -> Any:
  327. headers = {"Accept": "application/json", "User-Agent": "evm_client/1.0"}
  328. req = urllib.request.Request(url, headers=headers, method="GET")
  329. delay = 1.0
  330. last_err: Exception = RuntimeError("No attempts made")
  331. for attempt in range(retries):
  332. try:
  333. with urllib.request.urlopen(req, timeout=timeout) as resp:
  334. return json.loads(resp.read().decode())
  335. except urllib.error.HTTPError as e:
  336. if e.code == 429:
  337. time.sleep(delay)
  338. delay = min(delay * 2, 30)
  339. last_err = e
  340. continue
  341. body_text = ""
  342. try:
  343. body_text = e.read().decode()
  344. except Exception:
  345. pass
  346. raise RuntimeError(f"HTTP {e.code}: {body_text}") from e
  347. except Exception as e:
  348. last_err = e
  349. if attempt < retries - 1:
  350. time.sleep(delay)
  351. delay = min(delay * 2, 30)
  352. raise RuntimeError(f"Request failed after {retries} retries: {last_err}") from last_err
  353. # ---------------------------------------------------------------------------
  354. # RPC helpers
  355. # ---------------------------------------------------------------------------
  356. def get_rpc_url(chain: str) -> str:
  357. env = os.environ.get("EVM_RPC_URL", "")
  358. if env:
  359. return env
  360. cfg = CHAINS.get(chain)
  361. if not cfg:
  362. raise ValueError(f"Unknown chain '{chain}'. Available: {', '.join(CHAINS)}")
  363. return cfg["rpc"]
  364. def rpc_call(chain: str, method: str, params: list[Any], req_id: int = 1) -> Any:
  365. url = get_rpc_url(chain)
  366. payload = {"jsonrpc": "2.0", "id": req_id, "method": method, "params": params}
  367. resp = _http_post(url, payload)
  368. if "error" in resp:
  369. raise RuntimeError(f"RPC error: {resp['error']}")
  370. return resp.get("result")
  371. def rpc_batch(chain: str, calls: list[tuple[str, list[Any]]], batch_limit: int = 10) -> list[Any]:
  372. """Send a batch of JSON-RPC calls; returns list of results in same order.
  373. Auto-chunks at `batch_limit` (default 10) so we stay under per-RPC limits.
  374. Base's public RPC caps batches at 10 — exceeding that returns a single error
  375. dict instead of a results list, which would mask all our calls.
  376. """
  377. url = get_rpc_url(chain)
  378. # Build the full payload, preserving order via JSON-RPC `id`
  379. items = [
  380. {"jsonrpc": "2.0", "id": i, "method": m, "params": p}
  381. for i, (m, p) in enumerate(calls)
  382. ]
  383. out: list[Any] = [None] * len(items)
  384. for start in range(0, len(items), batch_limit):
  385. chunk = items[start:start + batch_limit]
  386. resp = _http_post(url, chunk)
  387. if not isinstance(resp, list):
  388. # Single error response (e.g. batch-too-large) — leave this chunk as None
  389. continue
  390. for r in resp:
  391. rid = r.get("id")
  392. if isinstance(rid, int) and 0 <= rid < len(out):
  393. if "error" in r:
  394. out[rid] = None
  395. else:
  396. out[rid] = r.get("result")
  397. return out
  398. # ---------------------------------------------------------------------------
  399. # ABI encoding helpers (minimal, for ERC-20 calls)
  400. # ---------------------------------------------------------------------------
  401. def _encode_address(addr: str) -> str:
  402. """Pad address to 32 bytes."""
  403. return addr.lower().replace("0x", "").zfill(64)
  404. def _keccak256(data: bytes) -> bytes:
  405. """Pure Python Keccak-256 (Ethereum's hash, NOT SHA3-256)."""
  406. # Keccak-256 round constants
  407. RC = [
  408. 0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000,
  409. 0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009,
  410. 0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A,
  411. 0x000000008000808B, 0x800000000000008B, 0x8000_0000_0000_8089, 0x8000000000008003,
  412. 0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A,
  413. 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008,
  414. ]
  415. ROT = [
  416. [0, 36, 3, 41, 18], [1, 44, 10, 45, 2], [62, 6, 43, 15, 61],
  417. [28, 55, 25, 21, 56], [27, 20, 39, 8, 14],
  418. ]
  419. def rot64(x, n): return ((x << n) | (x >> (64 - n))) & 0xFFFFFFFFFFFFFFFF
  420. rate = 136 # 1088 bits for keccak-256
  421. # Padding
  422. msg = bytearray(data)
  423. msg.append(0x01)
  424. while len(msg) % rate != 0:
  425. msg.append(0x00)
  426. msg[-1] |= 0x80
  427. # Absorb
  428. state = [0] * 25
  429. for block_start in range(0, len(msg), rate):
  430. block = msg[block_start:block_start + rate]
  431. for i in range(rate // 8):
  432. state[i] ^= int.from_bytes(block[i*8:(i+1)*8], "little")
  433. # Keccak-f[1600]
  434. for rnd in range(24):
  435. # Theta
  436. C = [state[x] ^ state[x+5] ^ state[x+10] ^ state[x+15] ^ state[x+20] for x in range(5)]
  437. D = [C[(x-1) % 5] ^ rot64(C[(x+1) % 5], 1) for x in range(5)]
  438. state = [state[i] ^ D[i % 5] for i in range(25)]
  439. # Rho + Pi
  440. B = [0] * 25
  441. for x in range(5):
  442. for y in range(5):
  443. B[y*5 + ((2*x+3*y) % 5)] = rot64(state[x + 5*y], ROT[x][y])
  444. # Chi
  445. state = [B[i] ^ ((~B[(i//5)*5 + (i%5+1)%5]) & B[(i//5)*5 + (i%5+2)%5]) for i in range(25)]
  446. # Iota
  447. state[0] ^= RC[rnd]
  448. # Squeeze
  449. out = b"".join(state[i].to_bytes(8, "little") for i in range(4))
  450. return out
  451. def _selector(sig: str) -> str:
  452. """Compute 4-byte function selector via keccak-256."""
  453. return "0x" + _keccak256(sig.encode()).hex()[:8]
  454. # Precomputed selectors for ERC-20 functions
  455. ERC20_SELECTORS: dict[str, str] = {
  456. "name()": "0x06fdde03",
  457. "symbol()": "0x95d89b41",
  458. "decimals()": "0x313ce567",
  459. "totalSupply()": "0x18160ddd",
  460. "balanceOf(address)": "0x70a08231",
  461. }
  462. def eth_call_erc20(chain: str, contract: str, fn: str, arg_addr: Optional[str] = None) -> str:
  463. selector = ERC20_SELECTORS[fn]
  464. data = selector
  465. if arg_addr:
  466. data += _encode_address(arg_addr)
  467. params = [{"to": contract, "data": data}, "latest"]
  468. return rpc_call(chain, "eth_call", params) or "0x"
  469. def decode_string(hex_data: str) -> str:
  470. """Decode ABI-encoded string from eth_call result."""
  471. try:
  472. raw = hex_data.removeprefix("0x")
  473. if len(raw) < 128:
  474. # Try decoding as raw bytes (some tokens return non-ABI strings)
  475. b = bytes.fromhex(raw)
  476. return b.rstrip(b"\x00").decode("utf-8", errors="replace").strip()
  477. # offset (skip 32 bytes), length, data
  478. length = int(raw[64:128], 16)
  479. chars = raw[128:128 + length * 2]
  480. return bytes.fromhex(chars).decode("utf-8", errors="replace").strip()
  481. except Exception:
  482. return ""
  483. def decode_uint256(hex_data: str) -> int:
  484. try:
  485. raw = hex_data.removeprefix("0x")
  486. if not raw:
  487. return 0
  488. return int(raw, 16)
  489. except Exception:
  490. return 0
  491. def decode_uint8(hex_data: str) -> int:
  492. return decode_uint256(hex_data)
  493. # ---------------------------------------------------------------------------
  494. # CoinGecko price fetching
  495. # ---------------------------------------------------------------------------
  496. COINGECKO_BASE = "https://api.coingecko.com/api/v3"
  497. def cg_price_by_id(cg_id: str) -> Optional[float]:
  498. try:
  499. url = f"{COINGECKO_BASE}/simple/price?ids={cg_id}&vs_currencies=usd"
  500. data = _http_get(url)
  501. return data.get(cg_id, {}).get("usd")
  502. except Exception:
  503. return None
  504. def cg_price_by_ids(cg_ids: list[str]) -> dict[str, float]:
  505. """Fetch multiple prices in one request."""
  506. if not cg_ids:
  507. return {}
  508. try:
  509. joined = ",".join(cg_ids)
  510. url = f"{COINGECKO_BASE}/simple/price?ids={joined}&vs_currencies=usd"
  511. data = _http_get(url)
  512. return {k: v.get("usd", 0.0) for k, v in data.items() if "usd" in v}
  513. except Exception:
  514. return {}
  515. def cg_price_by_contract(chain: str, contract: str) -> Optional[float]:
  516. cg_platform_map = {
  517. "ethereum": "ethereum",
  518. "bsc": "binance-smart-chain",
  519. "base": "base",
  520. "arbitrum": "arbitrum-one",
  521. "polygon": "polygon-pos",
  522. "optimism": "optimistic-ethereum",
  523. "avalanche":"avalanche",
  524. "zksync": "zksync",
  525. }
  526. platform = cg_platform_map.get(chain)
  527. if not platform:
  528. return None
  529. try:
  530. url = (
  531. f"{COINGECKO_BASE}/simple/token_price/{platform}"
  532. f"?contract_addresses={contract}&vs_currencies=usd"
  533. )
  534. data = _http_get(url)
  535. addr_lower = contract.lower()
  536. for k, v in data.items():
  537. if k.lower() == addr_lower:
  538. return v.get("usd")
  539. return None
  540. except Exception:
  541. return None
  542. def get_native_price(chain: str) -> Optional[float]:
  543. cg_id = CHAINS[chain]["coingecko"]
  544. return cg_price_by_id(cg_id)
  545. # ---------------------------------------------------------------------------
  546. # Command implementations
  547. # ---------------------------------------------------------------------------
  548. def cmd_stats(args: argparse.Namespace) -> None:
  549. chain = args.chain
  550. cfg = CHAINS[chain]
  551. # Batch: blockNumber + gasPrice
  552. results = rpc_batch(chain, [
  553. ("eth_blockNumber", []),
  554. ("eth_gasPrice", []),
  555. ])
  556. block_num = hex_to_int(results[0] or "0x0")
  557. gas_price_wei = hex_to_int(results[1] or "0x0")
  558. # TPS estimate: compare latest block timestamp with parent
  559. tps: Optional[float] = None
  560. try:
  561. latest_block = rpc_call(chain, "eth_getBlockByNumber", ["latest", False])
  562. if latest_block:
  563. parent_hex = latest_block.get("parentHash")
  564. parent_block = rpc_call(chain, "eth_getBlockByHash", [parent_hex, False])
  565. if parent_block:
  566. t1 = hex_to_int(latest_block.get("timestamp", "0x0"))
  567. t0 = hex_to_int(parent_block.get("timestamp", "0x0"))
  568. tx_count = len(latest_block.get("transactions", []))
  569. if t1 > t0:
  570. tps = round(tx_count / (t1 - t0), 2)
  571. except Exception:
  572. pass
  573. native_price = get_native_price(chain)
  574. print_json({
  575. "chain": chain,
  576. "block_number": block_num,
  577. "gas_price_gwei": round(gwei_from_wei(gas_price_wei), 4),
  578. "gas_price_wei": gas_price_wei,
  579. "native_token": cfg["native"],
  580. "native_price_usd": native_price,
  581. "tps_estimate": tps,
  582. "explorer": cfg["explorer"],
  583. })
  584. def cmd_wallet(args: argparse.Namespace) -> None:
  585. address = require_address(args.address)
  586. chain = args.chain
  587. limit = args.limit
  588. no_prices = args.no_prices
  589. cfg = CHAINS[chain]
  590. # Native balance
  591. balance_hex = rpc_call(chain, "eth_getBalance", [address, "latest"])
  592. native_wei = hex_to_int(balance_hex or "0x0")
  593. native_val = wei_to_native(native_wei, cfg["decimals"])
  594. native_usd_price: Optional[float] = None
  595. native_usd: Optional[float] = None
  596. if not no_prices:
  597. native_usd_price = get_native_price(chain)
  598. if native_usd_price is not None:
  599. native_usd = round(native_val * native_usd_price, 4)
  600. # ERC-20 tokens
  601. token_list = list((KNOWN_TOKENS.get(chain) or {}).items())[:limit]
  602. tokens_out = []
  603. portfolio_usd = native_usd or 0.0
  604. if token_list:
  605. # Batch balanceOf calls
  606. balance_calls = [
  607. ("eth_call", [{"to": addr, "data": ERC20_SELECTORS["balanceOf(address)"] + _encode_address(address)}, "latest"])
  608. for _, addr in token_list
  609. ]
  610. balances = rpc_batch(chain, balance_calls)
  611. for idx, (symbol, addr) in enumerate(token_list):
  612. raw_bal = decode_uint256(balances[idx] or "0x0")
  613. if raw_bal == 0:
  614. continue
  615. # Fetch decimals
  616. dec_hex = eth_call_erc20(chain, addr, "decimals()")
  617. decimals = decode_uint8(dec_hex) if dec_hex and dec_hex != "0x" else 18
  618. bal_human = wei_to_native(raw_bal, decimals)
  619. token_price: Optional[float] = None
  620. token_usd: Optional[float] = None
  621. if not no_prices:
  622. try:
  623. cg_id = COINGECKO_IDS.get(symbol)
  624. if cg_id:
  625. token_price = cg_price_by_id(cg_id)
  626. if token_price is None:
  627. token_price = cg_price_by_contract(chain, addr)
  628. if token_price is not None:
  629. token_usd = round(bal_human * token_price, 4)
  630. portfolio_usd += token_usd
  631. except Exception:
  632. pass
  633. tokens_out.append({
  634. "symbol": symbol,
  635. "contract": addr,
  636. "balance": round(bal_human, 8),
  637. "price_usd": token_price,
  638. "value_usd": token_usd,
  639. })
  640. print_json({
  641. "chain": chain,
  642. "address": address,
  643. "native_token": cfg["native"],
  644. "native_balance": round(native_val, 8),
  645. "native_price_usd": native_usd_price,
  646. "native_value_usd": native_usd,
  647. "erc20_tokens": tokens_out,
  648. "portfolio_total_usd": round(portfolio_usd, 4) if not no_prices else None,
  649. })
  650. def cmd_tx(args: argparse.Namespace) -> None:
  651. tx_hash = require_txhash(args.hash)
  652. chain = args.chain
  653. cfg = CHAINS[chain]
  654. results = rpc_batch(chain, [
  655. ("eth_getTransactionByHash", [tx_hash]),
  656. ("eth_getTransactionReceipt", [tx_hash]),
  657. ])
  658. tx = results[0]
  659. receipt = results[1]
  660. if not tx:
  661. print_json({"error": f"Transaction {tx_hash} not found on {chain}"})
  662. return
  663. block_num = hex_to_int(tx.get("blockNumber") or "0x0")
  664. timestamp: Optional[int] = None
  665. try:
  666. blk = rpc_call(chain, "eth_getBlockByNumber", [hex(block_num), False])
  667. if blk:
  668. timestamp = hex_to_int(blk.get("timestamp", "0x0"))
  669. except Exception:
  670. pass
  671. value_wei = hex_to_int(tx.get("value", "0x0"))
  672. value_eth = wei_to_native(value_wei, cfg["decimals"])
  673. gas_price = hex_to_int(tx.get("gasPrice") or "0x0")
  674. gas_limit = hex_to_int(tx.get("gas", "0x0"))
  675. gas_used = hex_to_int((receipt or {}).get("gasUsed", "0x0")) if receipt else None
  676. status = None
  677. if receipt:
  678. status = "success" if hex_to_int(receipt.get("status", "0x0")) == 1 else "failed"
  679. input_data = tx.get("input", "0x")
  680. input_preview = input_data[:66] + ("..." if len(input_data) > 66 else "")
  681. native_price = get_native_price(chain)
  682. value_usd = round(value_eth * native_price, 4) if native_price else None
  683. fee_eth: Optional[float] = None
  684. fee_usd: Optional[float] = None
  685. if gas_used is not None:
  686. fee_eth = wei_to_native(gas_used * gas_price, cfg["decimals"])
  687. if native_price:
  688. fee_usd = round(fee_eth * native_price, 6)
  689. print_json({
  690. "chain": chain,
  691. "hash": tx_hash,
  692. "block": block_num,
  693. "timestamp": timestamp,
  694. "from": tx.get("from"),
  695. "to": tx.get("to"),
  696. "value": round(value_eth, 8),
  697. "value_usd": value_usd,
  698. "native_token": cfg["native"],
  699. "gas_limit": gas_limit,
  700. "gas_used": gas_used,
  701. "gas_price_gwei": round(gwei_from_wei(gas_price), 4),
  702. "fee_native": round(fee_eth, 8) if fee_eth is not None else None,
  703. "fee_usd": fee_usd,
  704. "status": status,
  705. "input_preview": input_preview,
  706. "nonce": hex_to_int(tx.get("nonce", "0x0")),
  707. "explorer_url": f"{cfg['explorer']}/tx/{tx_hash}",
  708. })
  709. def cmd_token(args: argparse.Namespace) -> None:
  710. contract = require_address(args.contract, field="contract address")
  711. chain = args.chain
  712. # Batch all ERC-20 metadata calls
  713. calls = [
  714. ("eth_call", [{"to": contract, "data": ERC20_SELECTORS["name()"]}, "latest"]),
  715. ("eth_call", [{"to": contract, "data": ERC20_SELECTORS["symbol()"]}, "latest"]),
  716. ("eth_call", [{"to": contract, "data": ERC20_SELECTORS["decimals()"]}, "latest"]),
  717. ("eth_call", [{"to": contract, "data": ERC20_SELECTORS["totalSupply()"]}, "latest"]),
  718. ]
  719. results = rpc_batch(chain, calls)
  720. name = decode_string(results[0] or "0x")
  721. symbol = decode_string(results[1] or "0x")
  722. decimals = decode_uint8(results[2] or "0x0")
  723. supply_raw = decode_uint256(results[3] or "0x0")
  724. supply = wei_to_native(supply_raw, decimals)
  725. price: Optional[float] = None
  726. market_cap: Optional[float] = None
  727. cg_id = COINGECKO_IDS.get(symbol.upper())
  728. if cg_id:
  729. price = cg_price_by_id(cg_id)
  730. if price is None:
  731. price = cg_price_by_contract(chain, contract)
  732. if price is not None and supply > 0:
  733. market_cap = round(price * supply, 2)
  734. cfg = CHAINS[chain]
  735. print_json({
  736. "chain": chain,
  737. "contract": contract,
  738. "name": name,
  739. "symbol": symbol,
  740. "decimals": decimals,
  741. "total_supply": round(supply, 4),
  742. "price_usd": price,
  743. "market_cap_usd": market_cap,
  744. "explorer_url": f"{cfg['explorer']}/token/{contract}",
  745. })
  746. def cmd_activity(args: argparse.Namespace) -> None:
  747. address = require_address(args.address)
  748. chain = args.chain
  749. limit = args.limit
  750. cfg = CHAINS[chain]
  751. # Get current block
  752. block_hex = rpc_call(chain, "eth_blockNumber", [])
  753. latest = hex_to_int(block_hex or "0x0")
  754. txs_out: list[dict[str, Any]] = []
  755. scan_range = min(200, latest)
  756. blocks_checked = 0
  757. for bn in range(latest, max(0, latest - scan_range), -1):
  758. if len(txs_out) >= limit:
  759. break
  760. try:
  761. blk = rpc_call(chain, "eth_getBlockByNumber", [hex(bn), True])
  762. except Exception:
  763. continue
  764. if not blk:
  765. continue
  766. blocks_checked += 1
  767. timestamp = hex_to_int(blk.get("timestamp", "0x0"))
  768. for tx in blk.get("transactions", []):
  769. if len(txs_out) >= limit:
  770. break
  771. frm = (tx.get("from") or "").lower()
  772. to = (tx.get("to") or "").lower()
  773. addr_lower = address.lower()
  774. if frm == addr_lower or to == addr_lower:
  775. value_wei = hex_to_int(tx.get("value", "0x0"))
  776. value_eth = wei_to_native(value_wei, cfg["decimals"])
  777. gas_price = hex_to_int(tx.get("gasPrice") or "0x0")
  778. txs_out.append({
  779. "hash": tx.get("hash"),
  780. "block": bn,
  781. "timestamp": timestamp,
  782. "from": tx.get("from"),
  783. "to": tx.get("to"),
  784. "value": round(value_eth, 8),
  785. "native_token": cfg["native"],
  786. "gas_price_gwei": round(gwei_from_wei(gas_price), 4),
  787. "direction": "out" if frm == addr_lower else "in",
  788. })
  789. print_json({
  790. "chain": chain,
  791. "address": address,
  792. "blocks_scanned": blocks_checked,
  793. "tx_count": len(txs_out),
  794. "transactions": txs_out,
  795. })
  796. def cmd_gas(args: argparse.Namespace) -> None:
  797. chain = args.chain
  798. cfg = CHAINS[chain]
  799. gas_price_hex = rpc_call(chain, "eth_gasPrice", [])
  800. gas_wei = hex_to_int(gas_price_hex or "0x0")
  801. gas_gwei = gwei_from_wei(gas_wei)
  802. native_price = get_native_price(chain)
  803. estimates: dict[str, Any] = {}
  804. for op, gas_units in GAS_ESTIMATES.items():
  805. cost_wei = gas_wei * gas_units
  806. cost_native = wei_to_native(cost_wei, cfg["decimals"])
  807. cost_usd = round(cost_native * native_price, 6) if native_price else None
  808. estimates[op] = {
  809. "gas_units": gas_units,
  810. "cost_native": round(cost_native, 8),
  811. "cost_usd": cost_usd,
  812. }
  813. print_json({
  814. "chain": chain,
  815. "native_token": cfg["native"],
  816. "gas_price_gwei": round(gas_gwei, 4),
  817. "gas_price_wei": gas_wei,
  818. "native_price_usd": native_price,
  819. "estimates": estimates,
  820. })
  821. def cmd_price(args: argparse.Namespace) -> None:
  822. token = args.token
  823. chain = args.chain
  824. price: Optional[float] = None
  825. source = "unknown"
  826. # Check if it's a contract address
  827. if token.startswith("0x") and len(token) >= 10:
  828. price = cg_price_by_contract(chain, token)
  829. source = "coingecko_contract"
  830. if price is None:
  831. print_json({"error": f"Could not find price for contract {token} on {chain}"})
  832. return
  833. else:
  834. symbol = token.upper()
  835. cg_id = COINGECKO_IDS.get(symbol)
  836. if cg_id:
  837. price = cg_price_by_id(cg_id)
  838. source = f"coingecko:{cg_id}"
  839. if price is None:
  840. # Try known tokens on given chain
  841. contract = (KNOWN_TOKENS.get(chain) or {}).get(symbol)
  842. if contract:
  843. price = cg_price_by_contract(chain, contract)
  844. source = f"coingecko_contract:{contract}"
  845. if price is None:
  846. print_json({"error": f"Could not find price for '{token}'. Try a contract address."})
  847. return
  848. print_json({
  849. "token": token,
  850. "chain": chain,
  851. "price_usd": price,
  852. "source": source,
  853. })
  854. def _fetch_chain_stats(chain: str) -> dict[str, Any]:
  855. """Fetch gas price + native price for a single chain (used in compare)."""
  856. try:
  857. gas_hex = rpc_call(chain, "eth_gasPrice", [])
  858. gas_wei = hex_to_int(gas_hex or "0x0")
  859. gas_gwei = round(gwei_from_wei(gas_wei), 4)
  860. except Exception:
  861. gas_gwei = None
  862. cg_id = CHAINS[chain]["coingecko"]
  863. native_price = cg_price_by_id(cg_id)
  864. transfer_usd: Optional[float] = None
  865. if gas_gwei is not None and native_price is not None:
  866. gas_wei_val = int(gas_gwei * 1e9)
  867. cost_wei = gas_wei_val * GAS_ESTIMATES["transfer"]
  868. cost_native = wei_to_native(cost_wei, CHAINS[chain]["decimals"])
  869. transfer_usd = round(cost_native * native_price, 6)
  870. return {
  871. "chain": chain,
  872. "native_token": CHAINS[chain]["native"],
  873. "gas_price_gwei": gas_gwei,
  874. "native_price_usd": native_price,
  875. "transfer_cost_usd": transfer_usd,
  876. }
  877. def cmd_compare(_args: argparse.Namespace) -> None:
  878. """Compare gas prices and native token prices across all chains simultaneously."""
  879. import threading
  880. results: dict[str, Any] = {}
  881. errors: dict[str, str] = {}
  882. lock = threading.Lock()
  883. def fetch(chain: str) -> None:
  884. try:
  885. data = _fetch_chain_stats(chain)
  886. with lock:
  887. results[chain] = data
  888. except Exception as e:
  889. with lock:
  890. errors[chain] = str(e)
  891. threads = [threading.Thread(target=fetch, args=(c,), daemon=True) for c in CHAINS]
  892. for t in threads:
  893. t.start()
  894. for t in threads:
  895. t.join(timeout=30)
  896. sorted_by_gas = sorted(
  897. results.values(),
  898. key=lambda x: x.get("gas_price_gwei") or float("inf"),
  899. )
  900. print_json({
  901. "comparison": sorted_by_gas,
  902. "errors": errors,
  903. "cheapest_gas": sorted_by_gas[0]["chain"] if sorted_by_gas else None,
  904. "most_expensive_gas": sorted_by_gas[-1]["chain"] if sorted_by_gas else None,
  905. })
  906. def cmd_whale(args: argparse.Namespace) -> None:
  907. chain = args.chain
  908. blocks = args.blocks
  909. min_usd = args.min_usd
  910. cfg = CHAINS[chain]
  911. native_price = get_native_price(chain)
  912. if native_price is None:
  913. print_json({"error": "Could not fetch native token price for USD conversion."})
  914. return
  915. block_hex = rpc_call(chain, "eth_blockNumber", [])
  916. latest = hex_to_int(block_hex or "0x0")
  917. whales: list[dict[str, Any]] = []
  918. blocks_scanned = 0
  919. for bn in range(latest, max(0, latest - blocks), -1):
  920. try:
  921. blk = rpc_call(chain, "eth_getBlockByNumber", [hex(bn), True])
  922. except Exception:
  923. continue
  924. if not blk:
  925. continue
  926. blocks_scanned += 1
  927. timestamp = hex_to_int(blk.get("timestamp", "0x0"))
  928. for tx in blk.get("transactions", []):
  929. value_wei = hex_to_int(tx.get("value", "0x0"))
  930. if value_wei == 0:
  931. continue
  932. value_native = wei_to_native(value_wei, cfg["decimals"])
  933. value_usd = value_native * native_price
  934. if value_usd >= min_usd:
  935. whales.append({
  936. "hash": tx.get("hash"),
  937. "block": bn,
  938. "timestamp": timestamp,
  939. "from": tx.get("from"),
  940. "from_short": _short_addr(tx.get("from") or ""),
  941. "to": tx.get("to"),
  942. "to_short": _short_addr(tx.get("to") or ""),
  943. "value_native": round(value_native, 6),
  944. "native_token": cfg["native"],
  945. "value_usd": round(value_usd, 2),
  946. })
  947. whales.sort(key=lambda x: x["value_usd"], reverse=True)
  948. print_json({
  949. "chain": chain,
  950. "blocks_scanned": blocks_scanned,
  951. "latest_block": latest,
  952. "min_usd": min_usd,
  953. "native_price_usd": native_price,
  954. "whale_count": len(whales),
  955. "transfers": whales,
  956. })
  957. # ---------------------------------------------------------------------------
  958. # New commands: multichain, allowance, decode, ens, contract
  959. # ---------------------------------------------------------------------------
  960. def cmd_multichain(args: argparse.Namespace) -> None:
  961. """Scan same wallet across all 8 chains simultaneously."""
  962. import threading
  963. address = require_address(args.address)
  964. results: dict[str, Any] = {}
  965. lock = threading.Lock()
  966. def scan_chain(chain: str) -> None:
  967. cfg = CHAINS[chain]
  968. try:
  969. bal_hex = rpc_call(chain, "eth_getBalance", [address, "latest"])
  970. native_bal = int(bal_hex, 16) / 1e18 if bal_hex else 0.0
  971. native_price = get_native_price(chain)
  972. native_usd = round(native_bal * native_price, 2) if native_price else None
  973. entry: dict[str, Any] = {
  974. "native_symbol": cfg["native"],
  975. "native_balance": round(native_bal, 8),
  976. "native_price_usd": native_price,
  977. "native_value_usd": native_usd,
  978. "tokens": [],
  979. "total_usd": native_usd or 0.0,
  980. }
  981. # Check known tokens for this chain.
  982. # KNOWN_TOKENS[chain] maps {symbol: contract_address}, not {addr: (sym, name)}.
  983. known = KNOWN_TOKENS.get(chain, {})
  984. for symbol, contract in known.items():
  985. raw = eth_call_erc20(chain, contract, "balanceOf(address)", address)
  986. if not raw or raw == "0x":
  987. continue
  988. try:
  989. bal_int = int(raw, 16)
  990. except Exception:
  991. continue
  992. if bal_int == 0:
  993. continue
  994. dec_raw = eth_call_erc20(chain, contract, "decimals()")
  995. decimals = decode_uint8(dec_raw) if dec_raw else 18
  996. human = bal_int / (10 ** decimals)
  997. tok_price = cg_price_by_contract(chain, contract)
  998. tok_usd = round(human * tok_price, 2) if tok_price else None
  999. entry["tokens"].append({
  1000. "symbol": symbol,
  1001. "balance": round(human, 6),
  1002. "value_usd": tok_usd,
  1003. })
  1004. if tok_usd:
  1005. entry["total_usd"] = round(entry["total_usd"] + tok_usd, 2)
  1006. with lock:
  1007. results[chain] = entry
  1008. except Exception as exc:
  1009. with lock:
  1010. results[chain] = {"error": str(exc)}
  1011. threads = [threading.Thread(target=scan_chain, args=(c,)) for c in CHAINS]
  1012. for t in threads:
  1013. t.start()
  1014. for t in threads:
  1015. t.join()
  1016. grand_total = sum(
  1017. v.get("total_usd", 0) for v in results.values() if isinstance(v, dict)
  1018. )
  1019. print_json({
  1020. "address": address,
  1021. "chains": results,
  1022. "grand_total_usd": round(grand_total, 2),
  1023. })
  1024. def cmd_allowance(args: argparse.Namespace) -> None:
  1025. """Check dangerous ERC-20 approvals for a wallet (known spenders)."""
  1026. address = require_address(args.address)
  1027. chain = args.chain
  1028. # Well-known spender contracts (DEXes, bridges, etc.)
  1029. KNOWN_SPENDERS = {
  1030. "0x000000000022D473030F116dDEE9F6B43aC78BA3": "Permit2 (Uniswap)",
  1031. "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D": "Uniswap V2 Router",
  1032. "0xE592427A0AEce92De3Edee1F18E0157C05861564": "Uniswap V3 Router",
  1033. "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45": "Uniswap Universal Router",
  1034. "0x1111111254EEB25477B68fb85Ed929f73A960582": "1inch Router V5",
  1035. "0x6131B5fae19EA4f9D964eAc0408E4408b66337b5": "KyberSwap Router",
  1036. "0xDef1C0ded9bec7F1a1670819833240f027b25EfF": "0x Exchange Proxy",
  1037. "0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad": "Uniswap Universal Router 2",
  1038. }
  1039. known = KNOWN_TOKENS.get(chain, {})
  1040. approvals = []
  1041. # KNOWN_TOKENS[chain] is {symbol: contract_address}, not {addr: (sym, name)}.
  1042. for symbol, contract in known.items():
  1043. for spender_addr, spender_name in KNOWN_SPENDERS.items():
  1044. # allowance(owner, spender) = 0xdd62ed3e
  1045. owner_pad = address.lower().replace("0x", "").zfill(64)
  1046. spender_pad = spender_addr.lower().replace("0x", "").zfill(64)
  1047. data = "0xdd62ed3e" + owner_pad + spender_pad
  1048. raw = rpc_call(chain, "eth_call", [{"to": contract, "data": data}, "latest"])
  1049. if not raw or raw == "0x":
  1050. continue
  1051. try:
  1052. allowance_int = int(raw, 16)
  1053. except Exception:
  1054. continue
  1055. if allowance_int == 0:
  1056. continue
  1057. dec_raw = eth_call_erc20(chain, contract, "decimals()")
  1058. decimals = decode_uint8(dec_raw) if dec_raw else 18
  1059. max_uint = 2**256 - 1
  1060. is_unlimited = allowance_int >= max_uint // 2
  1061. approvals.append({
  1062. "token": symbol,
  1063. "contract": contract,
  1064. "spender": spender_name,
  1065. "spender_address": spender_addr,
  1066. "allowance": "UNLIMITED" if is_unlimited else str(round(allowance_int / 10**decimals, 4)),
  1067. "risk": "HIGH" if is_unlimited else "LOW",
  1068. })
  1069. print_json({
  1070. "chain": chain,
  1071. "address": address,
  1072. "approvals_found": len(approvals),
  1073. "approvals": approvals,
  1074. "note": "Only checks known DEX/bridge spenders. Use a full allowance checker for complete coverage.",
  1075. })
  1076. def cmd_decode(args: argparse.Namespace) -> None:
  1077. """Decode transaction input data using 4byte.directory."""
  1078. chain = args.chain
  1079. tx_hash = require_txhash(args.hash)
  1080. tx = rpc_call(chain, "eth_getTransactionByHash", [tx_hash])
  1081. if not tx:
  1082. print_json({"error": "Transaction not found"})
  1083. return
  1084. input_data: str = tx.get("input", "0x")
  1085. if not input_data or input_data == "0x":
  1086. print_json({
  1087. "chain": chain,
  1088. "hash": tx_hash,
  1089. "decoded": None,
  1090. "note": "No input data (plain ETH transfer)",
  1091. })
  1092. return
  1093. selector = input_data[:10] # 0x + 4 bytes = 10 chars
  1094. # Query 4byte.directory
  1095. url = f"https://www.4byte.directory/api/v1/signatures/?hex_signature={selector}"
  1096. data = _http_get(url)
  1097. signatures = []
  1098. if data and data.get("results"):
  1099. signatures = [r["text_signature"] for r in data["results"]]
  1100. # Decode known transfer(address,uint256) manually as fallback
  1101. decoded_args: Optional[dict] = None
  1102. if signatures and len(input_data) >= 74:
  1103. sig = signatures[0]
  1104. if sig == "transfer(address,uint256)" and len(input_data) == 138:
  1105. to_addr = "0x" + input_data[34:74]
  1106. amount_hex = input_data[74:]
  1107. try:
  1108. amount = int(amount_hex, 16)
  1109. decoded_args = {"to": to_addr, "amount_raw": amount}
  1110. except Exception:
  1111. pass
  1112. print_json({
  1113. "chain": chain,
  1114. "hash": tx_hash,
  1115. "selector": selector,
  1116. "input_length_bytes": (len(input_data) - 2) // 2,
  1117. "from": tx.get("from"),
  1118. "to": tx.get("to"),
  1119. "signatures": signatures,
  1120. "primary_signature": signatures[0] if signatures else None,
  1121. "decoded_args": decoded_args,
  1122. "raw_input_preview": input_data[:74] + ("..." if len(input_data) > 74 else ""),
  1123. "source": "4byte.directory",
  1124. })
  1125. def cmd_ens(args: argparse.Namespace) -> None:
  1126. """Resolve ENS name <-> address via ensideas.com public API (no key needed)."""
  1127. query = args.name_or_address
  1128. # ensideas.com handles both forward (name->address) and reverse (address->name)
  1129. try:
  1130. data = _http_get(f"https://api.ensideas.com/ens/resolve/{query}")
  1131. except Exception as exc:
  1132. print_json({"error": str(exc), "note": "ENS API unavailable"})
  1133. return
  1134. if not data:
  1135. print_json({"query": query, "address": None, "ens_name": None, "note": "Not found"})
  1136. return
  1137. print_json({
  1138. "query": query,
  1139. "address": data.get("address"),
  1140. "ens_name": data.get("name"),
  1141. "avatar": data.get("avatar"),
  1142. "display": data.get("displayName"),
  1143. "twitter": data.get("twitter"),
  1144. "github": data.get("github"),
  1145. "source": "ensideas.com",
  1146. })
  1147. def cmd_contract(args: argparse.Namespace) -> None:
  1148. """Inspect a smart contract: bytecode size, proxy detection, creation info."""
  1149. chain = args.chain
  1150. address = require_address(args.address)
  1151. # Get bytecode
  1152. code_hex = rpc_call(chain, "eth_getCode", [address, "latest"])
  1153. if not code_hex or code_hex == "0x":
  1154. print_json({"chain": chain, "address": address, "is_contract": False, "note": "EOA (externally owned account)"})
  1155. return
  1156. bytecode_bytes = (len(code_hex) - 2) // 2
  1157. # Proxy detection patterns
  1158. # EIP-1967: implementation slot 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
  1159. impl_slot = "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
  1160. impl_raw = rpc_call(chain, "eth_getStorageAt", [address, impl_slot, "latest"])
  1161. implementation = None
  1162. is_proxy = False
  1163. if impl_raw and impl_raw != "0x" and int(impl_raw, 16) != 0:
  1164. is_proxy = True
  1165. implementation = "0x" + impl_raw[-40:]
  1166. # EIP-1167 minimal proxy detection (starts with 0x363d3d37)
  1167. if code_hex[2:10] == "363d3d37" or code_hex[2:18] == "3d602d80600a3d39":
  1168. is_proxy = True
  1169. # supportsInterface check: ERC-165
  1170. supports_erc165 = False
  1171. try:
  1172. erc165_data = "0x01ffc9a701ffc9a700000000000000000000000000000000000000000000000000000000"
  1173. erc165_raw = rpc_call(chain, "eth_call", [{"to": address, "data": erc165_data}, "latest"])
  1174. supports_erc165 = bool(erc165_raw and erc165_raw != "0x" and int(erc165_raw, 16) == 1)
  1175. except Exception:
  1176. pass
  1177. # Try to detect ERC-20 (has totalSupply)
  1178. is_erc20 = False
  1179. try:
  1180. ts_raw = eth_call_erc20(chain, address, "totalSupply()")
  1181. is_erc20 = ts_raw is not None and ts_raw != "0x" and int(ts_raw, 16) > 0
  1182. except Exception:
  1183. pass
  1184. # Try to detect ERC-721 (supportsInterface 0x80ac58cd)
  1185. is_erc721 = False
  1186. try:
  1187. erc721_data = "0x01ffc9a780ac58cd00000000000000000000000000000000000000000000000000000000"
  1188. erc721_raw = rpc_call(chain, "eth_call", [{"to": address, "data": erc721_data}, "latest"])
  1189. is_erc721 = bool(erc721_raw and erc721_raw != "0x" and int(erc721_raw, 16) == 1)
  1190. except Exception:
  1191. pass
  1192. detected_standards = []
  1193. if is_erc20:
  1194. detected_standards.append("ERC-20")
  1195. if is_erc721:
  1196. detected_standards.append("ERC-721")
  1197. if supports_erc165:
  1198. detected_standards.append("ERC-165")
  1199. print_json({
  1200. "chain": chain,
  1201. "address": address,
  1202. "is_contract": True,
  1203. "bytecode_size_bytes": bytecode_bytes,
  1204. "is_proxy": is_proxy,
  1205. "implementation": implementation,
  1206. "detected_standards": detected_standards,
  1207. "explorer_url": f"{CHAINS[chain]['explorer']}/address/{address}",
  1208. "note": "Proxy detected via EIP-1967 storage slot. Standards via EIP-165 + heuristics." if is_proxy else None,
  1209. })
  1210. # ---------------------------------------------------------------------------
  1211. # Argument parsing & dispatch
  1212. # ---------------------------------------------------------------------------
  1213. def build_parser() -> argparse.ArgumentParser:
  1214. chain_choices = list(CHAINS.keys())
  1215. parser = argparse.ArgumentParser(
  1216. prog="evm_client",
  1217. description="EVM blockchain CLI — stdlib only, zero dependencies.",
  1218. )
  1219. sub = parser.add_subparsers(dest="command", metavar="COMMAND")
  1220. sub.required = True
  1221. # -- stats --
  1222. p_stats = sub.add_parser("stats", help="Chain stats: block, gas price, native price, TPS")
  1223. p_stats.add_argument("--chain", default=DEFAULT_CHAIN, choices=chain_choices)
  1224. # -- wallet --
  1225. p_wallet = sub.add_parser("wallet", help="Wallet balance + ERC-20 portfolio")
  1226. p_wallet.add_argument("address", help="Wallet address (0x...)")
  1227. p_wallet.add_argument("--limit", type=int, default=20, metavar="N",
  1228. help="Max number of known tokens to check (default: 20)")
  1229. p_wallet.add_argument("--no-prices", action="store_true",
  1230. help="Skip USD price lookups (faster)")
  1231. p_wallet.add_argument("--chain", default=DEFAULT_CHAIN, choices=chain_choices)
  1232. # -- tx --
  1233. p_tx = sub.add_parser("tx", help="Transaction details")
  1234. p_tx.add_argument("hash", help="Transaction hash (0x...)")
  1235. p_tx.add_argument("--chain", default=DEFAULT_CHAIN, choices=chain_choices)
  1236. # -- token --
  1237. p_token = sub.add_parser("token", help="ERC-20 token metadata + price")
  1238. p_token.add_argument("contract", help="Token contract address (0x...)")
  1239. p_token.add_argument("--chain", default=DEFAULT_CHAIN, choices=chain_choices)
  1240. # -- activity --
  1241. p_act = sub.add_parser("activity", help="Recent transactions for an address")
  1242. p_act.add_argument("address", help="Wallet address (0x...)")
  1243. p_act.add_argument("--limit", type=int, default=10, metavar="N",
  1244. help="Max transactions to return (default: 10)")
  1245. p_act.add_argument("--chain", default=DEFAULT_CHAIN, choices=chain_choices)
  1246. # -- gas --
  1247. p_gas = sub.add_parser("gas", help="Gas prices and cost estimates")
  1248. p_gas.add_argument("--chain", default=DEFAULT_CHAIN, choices=chain_choices)
  1249. # -- price --
  1250. p_price = sub.add_parser("price", help="Token price by symbol or contract address")
  1251. p_price.add_argument("token", help="Symbol (e.g. ETH, USDC) or contract address")
  1252. p_price.add_argument("--chain", default=DEFAULT_CHAIN, choices=chain_choices)
  1253. # -- compare --
  1254. sub.add_parser("compare", help="Gas + native prices across ALL chains simultaneously")
  1255. # -- whale --
  1256. p_whale = sub.add_parser("whale", help="Scan for large value transfers in recent blocks")
  1257. p_whale.add_argument("--blocks", type=int, default=20, metavar="N",
  1258. help="Number of recent blocks to scan (default: 20)")
  1259. p_whale.add_argument("--min-usd", type=float, default=10_000.0, metavar="N",
  1260. help="Minimum USD value to report (default: 10000)")
  1261. p_whale.add_argument("--chain", default=DEFAULT_CHAIN, choices=chain_choices)
  1262. # -- multichain --
  1263. p_multi = sub.add_parser("multichain", help="Scan same wallet across ALL chains simultaneously")
  1264. p_multi.add_argument("address", help="Wallet address (0x...)")
  1265. # -- allowance --
  1266. p_allow = sub.add_parser("allowance", help="Check dangerous ERC-20 approvals (known DEX/bridge spenders)")
  1267. p_allow.add_argument("address", help="Wallet address (0x...)")
  1268. p_allow.add_argument("--chain", default=DEFAULT_CHAIN, choices=chain_choices)
  1269. # -- decode --
  1270. p_decode = sub.add_parser("decode", help="Decode transaction input data via 4byte.directory")
  1271. p_decode.add_argument("hash", help="Transaction hash (0x...)")
  1272. p_decode.add_argument("--chain", default=DEFAULT_CHAIN, choices=chain_choices)
  1273. # -- ens --
  1274. p_ens = sub.add_parser("ens", help="Resolve ENS name <-> address (Ethereum only)")
  1275. p_ens.add_argument("name_or_address", help="ENS name (vitalik.eth) or address (0x...)")
  1276. # -- contract --
  1277. p_contract = sub.add_parser("contract", help="Inspect a smart contract: proxy, standards, bytecode size")
  1278. p_contract.add_argument("address", help="Contract address (0x...)")
  1279. p_contract.add_argument("--chain", default=DEFAULT_CHAIN, choices=chain_choices)
  1280. return parser
  1281. DISPATCH = {
  1282. "stats": cmd_stats,
  1283. "wallet": cmd_wallet,
  1284. "tx": cmd_tx,
  1285. "token": cmd_token,
  1286. "activity": cmd_activity,
  1287. "gas": cmd_gas,
  1288. "price": cmd_price,
  1289. "compare": cmd_compare,
  1290. "whale": cmd_whale,
  1291. "multichain": cmd_multichain,
  1292. "allowance": cmd_allowance,
  1293. "decode": cmd_decode,
  1294. "ens": cmd_ens,
  1295. "contract": cmd_contract,
  1296. }
  1297. def main() -> None:
  1298. parser = build_parser()
  1299. args = parser.parse_args()
  1300. # Validate chain exists (argparse choices already handles this, but for ENV override)
  1301. if hasattr(args, "chain") and args.chain not in CHAINS:
  1302. print_json({"error": f"Unknown chain '{args.chain}'. Available: {list(CHAINS.keys())}"})
  1303. sys.exit(1)
  1304. cmd_fn = DISPATCH.get(args.command)
  1305. if cmd_fn is None:
  1306. print_json({"error": f"Unknown command '{args.command}'"})
  1307. sys.exit(1)
  1308. try:
  1309. cmd_fn(args)
  1310. except KeyboardInterrupt:
  1311. print_json({"error": "Interrupted by user"})
  1312. sys.exit(130)
  1313. except Exception as e:
  1314. print_json({"error": str(e)})
  1315. sys.exit(1)
  1316. if __name__ == "__main__":
  1317. main()