Spaces:
Sleeping
Sleeping
Download metadata.py from LAEGEND/solana-runner-bot: direct link, hf CLI and curl.
- Browser
- Download file 12.8 kB
-
https://huggingface.co/spaces/LAEGEND/solana-runner-bot/resolve/main/metadata.py
- Command line
-
hf download hf://spaces/LAEGEND/solana-runner-bot/metadata.py
-
curl -L -o metadata.py https://huggingface.co/spaces/LAEGEND/solana-runner-bot/resolve/main/metadata.py
12.8 kB
| import urllib.request | |
| import json | |
| import time | |
| import re | |
| import html | |
| def resolve_ipfs_url(uri: str) -> str: | |
| """Transform IPFS URIs into Pump.fun's high-speed dedicated gateway""" | |
| if not uri: | |
| return "" | |
| # Extract CID | |
| cid_match = re.search(r'(Qm[1-9A-HJ-NP-Za-km-z]{44}|bafy[a-z0-9]{55}|bafk[a-z0-9]{55})', uri) | |
| if cid_match: | |
| cid = cid_match.group(1) | |
| return f"https://pump.mypinata.cloud/ipfs/{cid}" | |
| return uri | |
| def fetch_uri_json(uri: str): | |
| """Fetch JSON from token metadata URI (using Pump dedicated gateway or raw URL)""" | |
| if not uri: | |
| return {} | |
| # Try pump dedicated pinata gateway first for IPFS CIDs | |
| target_urls = [] | |
| resolved = resolve_ipfs_url(uri) | |
| if resolved and resolved != uri: | |
| target_urls.append(resolved) | |
| target_urls.append(uri) | |
| # Fallback gateways | |
| cid_match = re.search(r'(Qm[1-9A-HJ-NP-Za-km-z]{44}|bafy[a-z0-9]{55}|bafk[a-z0-9]{55})', uri) | |
| if cid_match: | |
| cid = cid_match.group(1) | |
| target_urls.extend([ | |
| f"https://gateway.pinata.cloud/ipfs/{cid}", | |
| f"https://ipfs.io/ipfs/{cid}" | |
| ]) | |
| for url in target_urls: | |
| try: | |
| req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}) | |
| with urllib.request.urlopen(req, timeout=5) as resp: | |
| data = json.loads(resp.read().decode("utf-8")) | |
| if isinstance(data, dict): | |
| return data | |
| except Exception: | |
| continue | |
| return {} | |
| def fetch_rpc_account_info(mint: str, rpc_url: str = "https://api.mainnet-beta.solana.com"): | |
| """Fetch mint account info from Solana RPC to extract tokenMetadata URI""" | |
| payload = json.dumps({ | |
| "jsonrpc": "2.0", | |
| "id": 1, | |
| "method": "getAccountInfo", | |
| "params": [mint, {"encoding": "jsonParsed"}] | |
| }).encode("utf-8") | |
| req = urllib.request.Request( | |
| rpc_url, | |
| data=payload, | |
| headers={"Content-Type": "application/json", "User-Agent": "Mozilla/5.0"} | |
| ) | |
| try: | |
| with urllib.request.urlopen(req, timeout=8) as resp: | |
| data = json.loads(resp.read().decode("utf-8")) | |
| parsed = data.get("result", {}).get("value", {}).get("data", {}).get("parsed", {}) | |
| extensions = parsed.get("info", {}).get("extensions", []) | |
| for ext in extensions: | |
| if ext.get("extension") == "tokenMetadata": | |
| state = ext.get("state", {}) | |
| return { | |
| "name": state.get("name"), | |
| "symbol": state.get("symbol"), | |
| "uri": state.get("uri") | |
| } | |
| except Exception: | |
| pass | |
| return None | |
| def fetch_dexscreener_info(mint: str): | |
| """Fetch market metrics, price, volume, and socials from DexScreener""" | |
| url = f"https://api.dexscreener.com/latest/dex/tokens/{mint}" | |
| try: | |
| req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}) | |
| with urllib.request.urlopen(req, timeout=7) as resp: | |
| data = json.loads(resp.read().decode("utf-8")) | |
| pairs = data.get("pairs", []) | |
| if pairs: | |
| pairs.sort(key=lambda x: (x.get("liquidity", {}).get("usd", 0) if x.get("liquidity") else 0), reverse=True) | |
| return pairs[0] | |
| except Exception: | |
| pass | |
| return None | |
| def fetch_pumpfun_coin(mint: str) -> dict: | |
| """Fetch coin metadata directly from Pump.fun API in <150ms""" | |
| url = f"https://frontend-api-v3.pump.fun/coins/{mint}" | |
| try: | |
| req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}) | |
| with urllib.request.urlopen(req, timeout=3) as resp: | |
| data = json.loads(resp.read().decode("utf-8")) | |
| if isinstance(data, dict): | |
| return data | |
| except Exception: | |
| pass | |
| return {} | |
| def extract_coin_description(pump_data: dict, uri_json: dict, dex_data: dict) -> str: | |
| """ | |
| Extract the developer's original coin description written when creating the token. | |
| Checks: | |
| 1. Direct Pump.fun API description | |
| 2. On-chain token metadata URI (IPFS / Pinata) | |
| 3. DexScreener info description | |
| Returns cleaned description string or "" if empty or placeholder. | |
| """ | |
| desc = "" | |
| if pump_data and pump_data.get("description"): | |
| desc = str(pump_data["description"]).strip() | |
| elif uri_json and uri_json.get("description"): | |
| desc = str(uri_json["description"]).strip() | |
| elif dex_data and dex_data.get("info", {}).get("description"): | |
| desc = str(dex_data["info"]["description"]).strip() | |
| if not desc: | |
| return "" | |
| # Check if developer actually wrote a description or just put empty / placeholder text | |
| is_placeholder = desc.lower() in [ | |
| "no description", "none", ".", "-", "n/a", "no lore", "test", "null", "undefined", "coin description" | |
| ] | |
| if is_placeholder or len(desc) < 3: | |
| return "" | |
| return desc | |
| def is_charity_buyback_token(token_data: dict) -> tuple: | |
| """ | |
| Detects if a token is a charity coin featuring buyback mechanics. | |
| Searches across token name, symbol, dev_description, and lore. | |
| Returns (is_charity_buyback: bool, reason: str). | |
| """ | |
| if not token_data: | |
| return False, "" | |
| name = (token_data.get("name") or "").lower() | |
| symbol = (token_data.get("symbol") or "").lower() | |
| desc = (token_data.get("description") or token_data.get("dev_description") or "").lower() | |
| lore = (token_data.get("lore") or "").lower() | |
| combined_text = f"{name} {symbol} {desc} {lore}" | |
| # Direct combined pattern phrases | |
| direct_patterns = [ | |
| r"charity\s+(?:coin\s+)?(?:with\s+)?buy\s*backs?", | |
| r"buy\s*backs?\s+(?:for\s+)?charity", | |
| r"charity\s+buy\s*backs?", | |
| r"charity\s+(?:and|&)\s+buy\s*backs?", | |
| r"donation[s]?\s+buy\s*backs?", | |
| r"buy\s*backs?[s]?\s+(?:to\s+)?donate" | |
| ] | |
| for p in direct_patterns: | |
| if re.search(p, combined_text, re.IGNORECASE): | |
| return True, "Direct charity & buyback phrase match" | |
| # Distinct charity & buyback keywords | |
| charity_keywords = [ | |
| "charity", "charities", "donate", "donation", "donations", "donating", | |
| "giving", "giveback", "give-back", "philanthropy", "philanthropic", | |
| "humanitarian", "nonprofit", "non-profit", "foundation", "relief fund", | |
| "clean water", "feed the", "animal rescue", "shelter" | |
| ] | |
| buyback_keywords = [ | |
| "buyback", "buybacks", "buy-back", "buy-backs", "buy back", "buy backs", | |
| "autobuyback", "auto-buyback", "buyback and burn", "buyback & burn", | |
| "buyback-and-burn" | |
| ] | |
| has_charity = any(re.search(rf"\b{re.escape(k)}\b", combined_text, re.IGNORECASE) for k in charity_keywords) | |
| has_buyback = any(re.search(rf"\b{re.escape(k)}\b", combined_text, re.IGNORECASE) for k in buyback_keywords) | |
| if has_charity and has_buyback: | |
| return True, "Charity cause and buyback mechanism verified" | |
| return False, "" | |
| def get_token_details(mint: str, rpc_url: str = "https://api.mainnet-beta.solana.com", chain_hint: str = ""): | |
| """ | |
| Unified function returning complete token details including developer coin description, | |
| market metrics, bonding curve, fast trading links, and charity buyback detection | |
| for Solana, BSC, and Robinhood. | |
| """ | |
| is_evm = mint.startswith("0x") | |
| dex_data = fetch_dexscreener_info(mint) or {} | |
| rpc_meta = {} if is_evm else (fetch_rpc_account_info(mint, rpc_url) or {}) | |
| pump_data = fetch_pumpfun_coin(mint) if (not is_evm and mint.endswith("pump")) else {} | |
| # Determine chain from DexScreener, chain_hint, or EVM address | |
| dex_chain = (dex_data.get("chainId") or "").lower() | |
| if dex_chain: | |
| chain = dex_chain | |
| elif chain_hint: | |
| chain = chain_hint.lower() | |
| elif is_evm: | |
| chain = "bsc" | |
| else: | |
| chain = "solana" | |
| is_robinhood = (chain == "robinhood" or "rh" in chain) | |
| is_bsc = (chain == "bsc" or (is_evm and not is_robinhood)) | |
| chain_name = "robinhood" if is_robinhood else ("bsc" if is_bsc else "solana") | |
| currency = "ETH" if is_robinhood else ("BNB" if is_bsc else "SOL") | |
| uri = rpc_meta.get("uri") | |
| uri_json = fetch_uri_json(uri) if uri else {} | |
| name = (pump_data.get("name") or rpc_meta.get("name") or uri_json.get("name") or dex_data.get("baseToken", {}).get("name") or "Unknown Token").strip() | |
| symbol = (pump_data.get("symbol") or rpc_meta.get("symbol") or uri_json.get("symbol") or dex_data.get("baseToken", {}).get("symbol") or (currency if is_evm else "MEME")).strip().upper() | |
| # Socials | |
| twitter = pump_data.get("twitter") or uri_json.get("twitter") or "" | |
| telegram = pump_data.get("telegram") or uri_json.get("telegram") or "" | |
| website = pump_data.get("website") or uri_json.get("website") or "" | |
| dex_socials = dex_data.get("info", {}).get("socials", []) | |
| for s in dex_socials: | |
| if s.get("type") == "twitter" and not twitter: | |
| twitter = s.get("url") | |
| elif s.get("type") == "telegram" and not telegram: | |
| telegram = s.get("url") | |
| dex_websites = dex_data.get("info", {}).get("websites", []) | |
| if dex_websites and not website: | |
| website = dex_websites[0].get("url") | |
| # Developer coin description created on token launch | |
| dev_description = extract_coin_description(pump_data, uri_json, dex_data) | |
| # Image | |
| image_url = uri_json.get("image") or dex_data.get("info", {}).get("imageUrl") or "" | |
| if image_url and "ipfs" in image_url: | |
| image_url = resolve_ipfs_url(image_url) | |
| # Market metrics | |
| mc = dex_data.get("marketCap") or dex_data.get("fdv") or 0 | |
| price_usd = float(dex_data.get("priceUsd", 0) or 0) | |
| vol_5m = dex_data.get("volume", {}).get("m5", 0) or 0 | |
| vol_1h = dex_data.get("volume", {}).get("h1", 0) or 0 | |
| vol_24h = dex_data.get("volume", {}).get("h24", 0) or 0 | |
| txns = dex_data.get("txns", {}) | |
| buys_5m = txns.get("m5", {}).get("buys", 0) or 0 | |
| sells_5m = txns.get("m5", {}).get("sells", 0) or 0 | |
| buys_24h = txns.get("h24", {}).get("buys", 0) or 0 | |
| sells_24h = txns.get("h24", {}).get("sells", 0) or 0 | |
| buy_ratio_5m = (buys_5m / (sells_5m + 1e-5)) if (buys_5m + sells_5m) > 0 else 1.0 | |
| cap_target = 70000.0 if is_robinhood else (65000.0 if is_bsc else 69000.0) | |
| bonding_curve_pct = min(100.0, round((mc / cap_target) * 100, 1)) if mc > 0 else 0.0 | |
| multiplier = round(mc / 6000.0, 1) if mc > 0 else 1.0 | |
| if is_robinhood: | |
| default_dex = f"https://dexscreener.com/robinhood/{mint}" | |
| elif is_bsc: | |
| default_dex = f"https://dexscreener.com/bsc/{mint}" | |
| else: | |
| default_dex = f"https://dexscreener.com/solana/{mint}" | |
| dex_url = dex_data.get("url") or default_dex | |
| # Volume & Turnover Metrics | |
| total_volume = float(vol_24h or vol_1h or vol_5m or 0) | |
| vol_to_mc_ratio = round(total_volume / mc, 2) if mc > 0 else 0.0 | |
| volume_gt_mc = bool(total_volume >= mc and mc > 0) | |
| token_dict = { | |
| "mint": mint, | |
| "chain": chain_name, | |
| "currency": currency, | |
| "name": name.strip(), | |
| "symbol": symbol.strip().upper(), | |
| "description": dev_description, | |
| "dev_description": dev_description, | |
| "lore": dev_description, | |
| "has_description": bool(dev_description), | |
| "has_dev_description": bool(dev_description), | |
| "image_url": image_url, | |
| "market_cap": mc, | |
| "price_usd": price_usd, | |
| "volume": total_volume, | |
| "vol_5m": vol_5m, | |
| "vol_1h": vol_1h, | |
| "vol_24h": total_volume, | |
| "vol_to_mc_ratio": vol_to_mc_ratio, | |
| "volume_gt_mc": volume_gt_mc, | |
| "buys_5m": buys_5m, | |
| "sells_5m": sells_5m, | |
| "buys_24h": buys_24h, | |
| "sells_24h": sells_24h, | |
| "buy_ratio_5m": round(buy_ratio_5m, 2), | |
| "bonding_curve_pct": bonding_curve_pct, | |
| "multiplier": multiplier, | |
| "twitter": twitter, | |
| "telegram": telegram, | |
| "website": website, | |
| "dex_url": dex_url | |
| } | |
| # Check for charity coins with buybacks | |
| is_cb, cb_reason = is_charity_buyback_token(token_dict) | |
| token_dict["is_charity_buyback"] = is_cb | |
| token_dict["charity_buyback_reason"] = cb_reason | |
| return token_dict | |