"""BitAddy payments, the watch-only part: which coins can pay, what they cost in dollars, and reading incoming payments from free public blockchain services. Nothing here can spend: BitAddy only ever knows public addresses. incoming(asset, address, since) -> [{"uid", "tx", "amount" (int, smallest unit), "confirmed", "tag"}] """ import random, threading, time from decimal import Decimal, ROUND_UP import ba_coins as coins S = None # the core console module (http_json); set by bitaddy.init def init(core): global S S = core # id, name, the chain whose receiving address is used, decimals, CoinGecko id, CoinPaprika id, token contract / mint ASSETS = { "BTC": {"name": "Bitcoin", "chain": "BTC", "dec": 8, "gecko": "bitcoin", "paprika": "btc-bitcoin", "wait": "about 10 minutes (one confirmation)"}, "ETH": {"name": "Ethereum", "chain": "ETH", "dec": 18, "gecko": "ethereum", "paprika": "eth-ethereum", "wait": "a minute or two"}, "ADA": {"name": "Cardano", "chain": "ADA", "dec": 6, "gecko": "cardano", "paprika": "ada-cardano", "wait": "a minute or two"}, "SOL": {"name": "Solana", "chain": "SOL", "dec": 9, "gecko": "solana", "paprika": "sol-solana", "wait": "under a minute"}, "LTC": {"name": "Litecoin", "chain": "LTC", "dec": 8, "gecko": "litecoin", "paprika": "ltc-litecoin", "wait": "a few minutes (one confirmation)"}, "DOGE": {"name": "Dogecoin", "chain": "DOGE", "dec": 8, "gecko": "dogecoin", "paprika": "doge-dogecoin", "wait": "a few minutes (one confirmation)"}, "XRP": {"name": "XRP", "chain": "XRP", "dec": 6, "gecko": "ripple", "paprika": "xrp-xrp", "wait": "under a minute"}, "TRX": {"name": "TRON", "chain": "TRX", "dec": 6, "gecko": "tron", "paprika": "trx-tron", "wait": "a minute or two"}, "USDT-ETH": {"name": "USDT on Ethereum", "chain": "ETH", "dec": 6, "gecko": "tether", "paprika": "usdt-tether", "stable": True, "symbol": "USDT", "token": "0xdAC17F958D2ee523a2206206994597C13D831ec7", "wait": "a minute or two"}, "USDC-ETH": {"name": "USDC on Ethereum", "chain": "ETH", "dec": 6, "gecko": "usd-coin", "paprika": "usdc-usd-coin", "stable": True, "symbol": "USDC", "token": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "wait": "a minute or two"}, "USDT-SOL": {"name": "USDT on Solana", "chain": "SOL", "dec": 6, "gecko": "tether", "paprika": "usdt-tether", "stable": True, "symbol": "USDT", "token": "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", "wait": "under a minute"}, "USDC-SOL": {"name": "USDC on Solana", "chain": "SOL", "dec": 6, "gecko": "usd-coin", "paprika": "usdc-usd-coin", "stable": True, "symbol": "USDC", "token": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "wait": "under a minute"}, "USDT-TRX": {"name": "USDT on TRON", "chain": "TRX", "dec": 6, "gecko": "tether", "paprika": "usdt-tether", "stable": True, "symbol": "USDT", "token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "wait": "a minute or two"}, } ORDER = list(ASSETS) CHAINS = ["BTC", "ETH", "ADA", "SOL", "LTC", "DOGE", "XRP", "TRX"] # one receiving address each MIN_GAP = {"DOGE": 110, "TRX": 45, "USDT-TRX": 45} # seconds between looks, for services with small free allowances EXPLORER = {"BTC": "https://mempool.space/tx/", "ETH": "https://etherscan.io/tx/", "ADA": "https://cardanoscan.io/transaction/", "SOL": "https://solscan.io/tx/", "LTC": "https://litecoinspace.org/tx/", "DOGE": "https://dogechain.info/tx/", "XRP": "https://xrpscan.com/tx/", "TRX": "https://tronscan.org/#/transaction/"} def symbol(asset): return ASSETS[asset].get("symbol") or asset def explorer(asset, tx): return EXPLORER[ASSETS[asset]["chain"]] + tx # ------------------------------------------------------------------ prices PRICE = {"ts": 0, "p": {}, "src": ""} PLOCK = threading.Lock() def _gecko(): ids = sorted({a["gecko"] for a in ASSETS.values()}) st, j = S.http_json("GET", "https://api.coingecko.com/api/v3/simple/price?ids=%s&vs_currencies=usd" % ",".join(ids), timeout=15) if st != 200 or not isinstance(j, dict): return {} return {k: Decimal(str(j[a["gecko"]]["usd"])) for k, a in ASSETS.items() if a["gecko"] in j and j[a["gecko"]].get("usd")} def _paprika(): out, cache = {}, {} for k, a in ASSETS.items(): pid = a["paprika"] if pid not in cache: st, j = S.http_json("GET", "https://api.coinpaprika.com/v1/tickers/" + pid, timeout=15) cache[pid] = Decimal(str(j["quotes"]["USD"]["price"])) if st == 200 and isinstance(j, dict) and j.get("quotes") else None if cache[pid]: out[k] = cache[pid] return out def prices(): """Dollar price of each asset. Dollar coins count as exactly $1, and are left out (paused) if they drift more than 3%.""" with PLOCK: if time.time() - PRICE["ts"] < 300 and PRICE["p"]: return PRICE["p"] p, src = {}, "" for name, fn in (("CoinGecko", _gecko), ("CoinPaprika", _paprika)): try: p = fn() except Exception: p = {} if len(p) >= len(CHAINS): src = name break if p: for k, a in ASSETS.items(): if a.get("stable") and k in p: if abs(p[k] - 1) <= Decimal("0.03"): p[k] = Decimal(1) else: p.pop(k) PRICE.update(ts=time.time(), p=p, src=src) return PRICE["p"] def fmt_amount(base, asset): d = ASSETS[asset]["dec"] q = Decimal(int(base)) / (Decimal(10) ** d) return format(q.quantize(Decimal(1) / (Decimal(10) ** d)), "f").rstrip("0").rstrip(".") def places(asset, price): """How many decimal places to show, so that one step is worth about a hundredth of a cent (never finer than the coin allows).""" d, n = ASSETS[asset]["dec"], 0 while n < d and price / (Decimal(10) ** n) > Decimal("0.0001"): n += 1 return n def make_amount(usd, asset, taken): """The exact amount to ask for: the dollar price in that coin, plus a tiny random extra (normally under a cent) that makes this order's amount different from every other open order, since everyone pays to the same address. `taken`: base amounts in use.""" p = prices().get(asset) if not p: raise ValueError("Prices for %s aren't available right now. Please try another coin or try again in a minute." % ASSETS[asset]["name"]) n = places(asset, p) d = ASSETS[asset]["dec"] whole = (Decimal(usd) / p).quantize(Decimal(1) / (Decimal(10) ** n), rounding=ROUND_UP) step = 10 ** (d - n) base0 = int(whole * (Decimal(10) ** d)) for hi in (99, 99, 99, 999, 999, 9999, 9999): base = base0 + random.randint(1, hi) * step if str(base) not in taken: return str(base) raise ValueError("Busy right now, please try again.") # ------------------------------------------------------------------ reading the chains def _get(url, timeout=25, headers=None): return S.http_json("GET", url, timeout=timeout, headers=headers) def _esplora(bases, address): last = None for b in bases: try: st, txs = _get("%s/address/%s/txs" % (b, address)) except Exception as e: last = e continue if st == 200 and isinstance(txs, list): out = [] for t in txs: amt = sum(int(v.get("value") or 0) for v in t.get("vout", []) if v.get("scriptpubkey_address") == address) if amt: out.append({"uid": t["txid"], "tx": t["txid"], "amount": amt, "confirmed": bool((t.get("status") or {}).get("confirmed")), "tag": None}) return out last = RuntimeError("%s answered %s" % (b, st)) raise last or RuntimeError("no answer") def _blockcypher(net, address): st, j = _get("https://api.blockcypher.com/v1/%s/main/addrs/%s/full?limit=50" % (net, address)) if st != 200 or not isinstance(j, dict): raise RuntimeError("blockcypher answered %s" % st) out = [] for t in j.get("txs") or []: amt = sum(int(o.get("value") or 0) for o in t.get("outputs", []) if address in (o.get("addresses") or [])) if amt: out.append({"uid": t["hash"], "tx": t["hash"], "amount": amt, "confirmed": int(t.get("confirmations") or 0) >= 1, "tag": None}) return out def _ada(address, since): st, txs = S.http_json("POST", "https://api.koios.rest/api/v1/address_txs", body={"_addresses": [address], "_after_block_height": int(since or 0)}) if st != 200 or not isinstance(txs, list): raise RuntimeError("koios answered %s" % st) hashes = [t["tx_hash"] for t in txs][-50:] if not hashes: return [] st, infos = S.http_json("POST", "https://api.koios.rest/api/v1/tx_info", body={"_tx_hashes": hashes, "_inputs": False, "_metadata": False, "_assets": False, "_withdrawals": False, "_certs": False, "_scripts": False, "_bytecode": False}) out = [] for t in infos if isinstance(infos, list) else []: amt = sum(int(o.get("value") or 0) for o in t.get("outputs", []) if (o.get("payment_addr") or {}).get("bech32") == address) if amt: out.append({"uid": t["tx_hash"], "tx": t["tx_hash"], "amount": amt, "confirmed": True, "tag": None}) return out ETH_RPCS = ["https://ethereum-rpc.publicnode.com", "https://rpc.mevblocker.io", "https://1rpc.io/eth", "https://eth.drpc.org"] ETH_LOG_RPCS = ["https://ethereum-rpc.publicnode.com", "https://rpc.mevblocker.io"] # the free ones that answer log searches over ~2000 blocks TRANSFER = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" def _eth_rpc(method, params, urls=None): errs = [] for u in urls or ETH_RPCS: try: st, j = S.http_json("POST", u, body={"jsonrpc": "2.0", "id": 1, "method": method, "params": params}, timeout=20) except Exception as e: errs.append("%s: %s" % (u, e)) continue if st == 200 and isinstance(j, dict) and "result" in j: return j["result"] errs.append("%s: %s" % (u, str(j)[:100])) raise RuntimeError("; ".join(errs) or "no answer") def eth_block(): return int(_eth_rpc("eth_blockNumber", []), 16) def _eth_native(address): st, j = _get("https://eth.blockscout.com/api/v2/addresses/%s/transactions?filter=to" % address, timeout=30) if st != 200 or not isinstance(j, dict): raise RuntimeError("blockscout answered %s" % st) out = [] for t in j.get("items") or []: if ((t.get("to") or {}).get("hash") or "").lower() == address.lower() and t.get("result") == "success" and int(t.get("value") or 0) > 0: out.append({"uid": t["hash"], "tx": t["hash"], "amount": int(t["value"]), "confirmed": bool(t.get("block_number") or t.get("block")), "tag": None}) return out def _eth_token(contract, address, since): tip = eth_block() start = max(int(since or 0), tip - 9000) if since else tip - 1500 topic = "0x" + "0" * 24 + address.lower()[2:] out = [] while start <= tip: end = min(start + 1999, tip) logs = _eth_rpc("eth_getLogs", [{"fromBlock": hex(start), "toBlock": hex(end), "address": contract, "topics": [TRANSFER, None, topic]}], ETH_LOG_RPCS) for l in logs or []: if l.get("removed"): continue amt = int(l.get("data") or "0x0", 16) if amt: out.append({"uid": "%s:%s" % (l["transactionHash"], int(l.get("logIndex") or "0x0", 16)), "tx": l["transactionHash"], "amount": amt, "confirmed": int(l["blockNumber"], 16) <= tip - 1, "tag": None}) start = end + 1 return out SOL_RPCS = ["https://api.mainnet-beta.solana.com", "https://solana-rpc.publicnode.com"] SOL_DONE = {} # signatures already looked at that held no payment, so they aren't fetched again every minute SOL_LOCK = threading.Lock() SOL_LAST = [0.0] def _sol_rpc(method, params): """Public Solana services allow only a few calls a second, so calls are spaced out, and a busy answer is retried once.""" errs = [] with SOL_LOCK: for u in SOL_RPCS: for attempt in (0, 1): wait = 0.45 - (time.time() - SOL_LAST[0]) if wait > 0: time.sleep(wait) try: st, j = S.http_json("POST", u, body={"jsonrpc": "2.0", "id": 1, "method": method, "params": params}, timeout=20) except Exception as e: st, j = 0, {"raw": str(e)} SOL_LAST[0] = time.time() if st == 200 and isinstance(j, dict) and "result" in j: return j["result"] errs.append("%s: %s %s" % (u, st, str(j)[:90])) if st == 429 and attempt == 0: time.sleep(4) continue break raise RuntimeError("; ".join(errs)) def _sol(asset, address, skip): mint = ASSETS[asset].get("token") watch = [address] if mint: r = _sol_rpc("getTokenAccountsByOwner", [address, {"mint": mint}, {"encoding": "jsonParsed"}]) watch = [x["pubkey"] for x in (r or {}).get("value", [])] out, looked = [], 0 for acct in watch: for s in _sol_rpc("getSignaturesForAddress", [acct, {"limit": 25, "commitment": "confirmed"}]) or []: sig = s.get("signature") key = asset + ":" + (sig or "") if not sig or s.get("err") or key in SOL_DONE or (skip and sig in skip): continue if looked >= 12: # the rest are read on the next look break looked += 1 r = _sol_rpc("getTransaction", [sig, {"encoding": "jsonParsed", "maxSupportedTransactionVersion": 0, "commitment": "confirmed"}]) or {} meta, msg = r.get("meta") or {}, (r.get("transaction") or {}).get("message") or {} delta = 0 if meta and not meta.get("err"): if mint: def bal(rows): return sum(int((x.get("uiTokenAmount") or {}).get("amount") or 0) for x in rows or [] if x.get("owner") == address and x.get("mint") == mint) delta = bal(meta.get("postTokenBalances")) - bal(meta.get("preTokenBalances")) else: keys = [k.get("pubkey") if isinstance(k, dict) else k for k in msg.get("accountKeys", [])] if address in keys: i = keys.index(address) delta = int(meta["postBalances"][i]) - int(meta["preBalances"][i]) if delta > 0: out.append({"uid": sig, "tx": sig, "amount": delta, "confirmed": True, "tag": None}) else: SOL_DONE[key] = time.time() return out TRON_LOCK = threading.Lock() TRON_LAST = [0.0] def _tron_get(path): with TRON_LOCK: for attempt in (0, 1): wait = 1.3 - (time.time() - TRON_LAST[0]) if wait > 0: time.sleep(wait) st, j = _get("https://api.trongrid.io" + path) TRON_LAST[0] = time.time() if st == 429 and attempt == 0: time.sleep(6) continue if st != 200 or not isinstance(j, dict) or "data" not in j: raise RuntimeError("trongrid answered %s" % st) return j["data"] def _tron(asset, address): contract = ASSETS[asset].get("token") out = [] if contract: for t in _tron_get("/v1/accounts/%s/transactions/trc20?only_to=true&only_confirmed=true&limit=50&contract_address=%s" % (address, contract)): if t.get("to") == address and (t.get("token_info") or {}).get("address") == contract and t.get("type") == "Transfer": out.append({"uid": t["transaction_id"], "tx": t["transaction_id"], "amount": int(t.get("value") or 0), "confirmed": True, "tag": None}) return out ver, body = coins.b58check(address) want = "41" + body.hex() # the same address the way TronGrid writes it for t in _tron_get("/v1/accounts/%s/transactions?only_to=true&only_confirmed=true&limit=50" % address): try: c = t["raw_data"]["contract"][0] v = c["parameter"]["value"] if c.get("type") == "TransferContract" and (t.get("ret") or [{}])[0].get("contractRet") == "SUCCESS" and v.get("to_address", "").lower() == want: out.append({"uid": t["txID"], "tx": t["txID"], "amount": int(v.get("amount") or 0), "confirmed": True, "tag": None}) except (KeyError, IndexError, TypeError): continue return out def _xrp(address): last = None for u in ("https://s1.ripple.com:51234/", "https://xrplcluster.com/"): try: st, j = S.http_json("POST", u, body={"method": "account_tx", "params": [{"account": address, "limit": 50, "ledger_index_min": -1, "ledger_index_max": -1, "forward": False}]}, timeout=20) except Exception as e: last = e continue r = (j or {}).get("result") if isinstance(j, dict) else None if st != 200 or not r or "transactions" not in r: last = RuntimeError("xrp ledger answered %s" % st) continue out = [] for e in r["transactions"]: tx = e.get("tx") or e.get("tx_json") or {} meta = e.get("meta") or {} h = tx.get("hash") or e.get("hash") got = meta.get("delivered_amount") # the amount that really arrived (never trust "Amount": partial payments exist) if tx.get("TransactionType") != "Payment" or tx.get("Destination") != address or meta.get("TransactionResult") != "tesSUCCESS" \ or not isinstance(got, str) or not got.isdigit() or not h: continue out.append({"uid": h, "tx": h, "amount": int(got), "confirmed": bool(e.get("validated")), "tag": tx.get("DestinationTag")}) return out raise last or RuntimeError("no answer") def start_height(asset): """A marker taken when an order is made, so later looks only need to read from there (only some chains use it).""" try: a = ASSETS[asset] if a["chain"] == "ADA": st, j = S.http_json("GET", "https://api.koios.rest/api/v1/tip", timeout=15) return int(j[0]["block_no"]) if st == 200 else None if a["chain"] == "ETH" and a.get("token"): return eth_block() - 5 except Exception: return None return None def incoming(asset, address, since=None, skip=None): a = ASSETS[asset] ch = a["chain"] if ch == "BTC": return _esplora(["https://mempool.space/api", "https://blockstream.info/api"], address) if ch == "LTC": try: return _esplora(["https://litecoinspace.org/api"], address) except Exception: return _blockcypher("ltc", address) if ch == "DOGE": return _blockcypher("doge", address) if ch == "ADA": return _ada(address, since) if ch == "ETH": return _eth_token(a["token"], address, since) if a.get("token") else _eth_native(address) if ch == "SOL": return _sol(asset, address, skip) if ch == "TRX": return _tron(asset, address) if ch == "XRP": return _xrp(address) raise ValueError("unknown asset") def check_address(chain, text): """A receiving address for one of the 8 chains (the owner's own wallet). Returns the cleaned address or raises ValueError.""" ok, why = coins.check(chain, text) if not ok: raise ValueError("%s wallet: %s" % (ASSETS[chain]["name"], why)) if chain == "ADA" and not ok.startswith("addr1"): raise ValueError("Cardano wallet: please use a normal addr1... address.") if chain == "XRP" and not ok.startswith("r"): raise ValueError("XRP wallet: please use a classic r... address (payments are told apart by a destination tag).") return ok def known(asset, address): """The ids of everything already in the address (for the first-time baseline). Cheap: never opens single transactions.""" a = ASSETS[asset] if a["chain"] == "SOL": watch = [address] if a.get("token"): r = _sol_rpc("getTokenAccountsByOwner", [address, {"mint": a["token"]}, {"encoding": "jsonParsed"}]) watch = [x["pubkey"] for x in (r or {}).get("value", [])] return [s["signature"] for acct in watch for s in (_sol_rpc("getSignaturesForAddress", [acct, {"limit": 25, "commitment": "confirmed"}]) or [])] return [t["uid"] for t in incoming(asset, address, start_height(asset))]