|
| 1 | +"""On-chain wallet activity from Base Sepolia Blockscout (token transfers + deployer txs).""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | +import os |
| 7 | +from collections.abc import Mapping |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +import httpx |
| 11 | + |
| 12 | +from backend.schemas import WalletTransactionItem |
| 13 | +from backend.services.base_sepolia import blockscout_tx_url |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | +BLOCKSCOUT_API = "https://base-sepolia.blockscout.com/api/v2" |
| 18 | +BLOCKSCOUT_PROVENANCE = "base:sepolia:blockscout" |
| 19 | + |
| 20 | + |
| 21 | +def _env(env: Mapping[str, str] | None = None) -> dict[str, str]: |
| 22 | + return dict(os.environ) if env is None else dict(env) |
| 23 | + |
| 24 | + |
| 25 | +def _env_address(env: Mapping[str, str], key: str) -> str: |
| 26 | + raw = env.get(key, "").strip() |
| 27 | + if not raw: |
| 28 | + return "" |
| 29 | + return raw.split("#", 1)[0].strip() |
| 30 | + |
| 31 | + |
| 32 | +def _amount_usdc(total: dict[str, Any] | None) -> float: |
| 33 | + if not isinstance(total, dict): |
| 34 | + return 0.0 |
| 35 | + raw = total.get("value") |
| 36 | + decimals = int(total.get("decimals") or 6) |
| 37 | + try: |
| 38 | + return round(int(raw) / 10**decimals, 6) |
| 39 | + except (TypeError, ValueError): |
| 40 | + return 0.0 |
| 41 | + |
| 42 | + |
| 43 | +def _address_hash(entry: dict[str, Any] | None) -> str: |
| 44 | + if not isinstance(entry, dict): |
| 45 | + return "" |
| 46 | + return str(entry.get("hash") or "") |
| 47 | + |
| 48 | + |
| 49 | +def _parse_token_transfer(entry: dict[str, Any], *, wallet_address: str) -> WalletTransactionItem | None: |
| 50 | + tx_hash = str(entry.get("transaction_hash") or "") |
| 51 | + if not tx_hash.startswith("0x"): |
| 52 | + return None |
| 53 | + wallet_l = wallet_address.lower() |
| 54 | + from_addr = _address_hash(entry.get("from")).lower() |
| 55 | + to_addr = _address_hash(entry.get("to")).lower() |
| 56 | + amount = _amount_usdc(entry.get("total")) |
| 57 | + if to_addr == wallet_l: |
| 58 | + operation = "USDC in" |
| 59 | + elif from_addr == wallet_l: |
| 60 | + operation = "USDC out" |
| 61 | + else: |
| 62 | + operation = "USDC transfer" |
| 63 | + ts = str(entry.get("timestamp") or "") |
| 64 | + log_index = entry.get("log_index", 0) |
| 65 | + return WalletTransactionItem( |
| 66 | + id=f"{tx_hash}:{log_index}", |
| 67 | + state="confirmed", |
| 68 | + tx_hash=tx_hash, |
| 69 | + amount_usdc=amount, |
| 70 | + operation=operation, |
| 71 | + transaction_type="token_transfer", |
| 72 | + create_date=ts.replace("T", " ").replace(".000000Z", " UTC") if ts else "", |
| 73 | + explorer_url=blockscout_tx_url(tx_hash), |
| 74 | + ) |
| 75 | + |
| 76 | + |
| 77 | +def _parse_address_transaction(entry: dict[str, Any]) -> WalletTransactionItem | None: |
| 78 | + tx_hash = str(entry.get("hash") or "") |
| 79 | + if not tx_hash.startswith("0x"): |
| 80 | + return None |
| 81 | + method = str(entry.get("method") or "") |
| 82 | + if not method and entry.get("transaction_types"): |
| 83 | + types = entry.get("transaction_types") or [] |
| 84 | + method = str(types[0]) if types else "transaction" |
| 85 | + amount = 0.0 |
| 86 | + token_transfers = entry.get("token_transfers") or [] |
| 87 | + if isinstance(token_transfers, list) and token_transfers: |
| 88 | + amount = _amount_usdc(token_transfers[0].get("total")) |
| 89 | + ts = str(entry.get("timestamp") or "") |
| 90 | + state = "confirmed" if entry.get("status") == "ok" else str(entry.get("status") or "unknown") |
| 91 | + return WalletTransactionItem( |
| 92 | + id=tx_hash, |
| 93 | + state=state, |
| 94 | + tx_hash=tx_hash, |
| 95 | + amount_usdc=amount, |
| 96 | + operation=method or "transaction", |
| 97 | + transaction_type=str(entry.get("type") or "contract_call"), |
| 98 | + create_date=ts.replace("T", " ").replace(".000000Z", " UTC") if ts else "", |
| 99 | + explorer_url=blockscout_tx_url(tx_hash), |
| 100 | + ) |
| 101 | + |
| 102 | + |
| 103 | +def _get_json(path: str, *, timeout: float = 20.0) -> dict[str, Any]: |
| 104 | + url = f"{BLOCKSCOUT_API}{path}" |
| 105 | + with httpx.Client(timeout=timeout) as client: |
| 106 | + response = client.get(url) |
| 107 | + response.raise_for_status() |
| 108 | + payload = response.json() |
| 109 | + return payload if isinstance(payload, dict) else {} |
| 110 | + |
| 111 | + |
| 112 | +def fetch_blockscout_token_transfers(address: str, *, limit: int = 15) -> list[WalletTransactionItem]: |
| 113 | + if not address.startswith("0x"): |
| 114 | + return [] |
| 115 | + try: |
| 116 | + payload = _get_json(f"/addresses/{address}/token-transfers") |
| 117 | + except Exception: |
| 118 | + logger.debug("Blockscout token transfers failed for %s", address, exc_info=True) |
| 119 | + return [] |
| 120 | + items = payload.get("items") or [] |
| 121 | + parsed: list[WalletTransactionItem] = [] |
| 122 | + for entry in items[:limit]: |
| 123 | + if not isinstance(entry, dict): |
| 124 | + continue |
| 125 | + item = _parse_token_transfer(entry, wallet_address=address) |
| 126 | + if item: |
| 127 | + parsed.append(item) |
| 128 | + return parsed |
| 129 | + |
| 130 | + |
| 131 | +def fetch_blockscout_address_transactions(address: str, *, limit: int = 15) -> list[WalletTransactionItem]: |
| 132 | + if not address.startswith("0x"): |
| 133 | + return [] |
| 134 | + try: |
| 135 | + payload = _get_json(f"/addresses/{address}/transactions") |
| 136 | + except Exception: |
| 137 | + logger.debug("Blockscout transactions failed for %s", address, exc_info=True) |
| 138 | + return [] |
| 139 | + items = payload.get("items") or [] |
| 140 | + parsed: list[WalletTransactionItem] = [] |
| 141 | + for entry in items[:limit]: |
| 142 | + if not isinstance(entry, dict): |
| 143 | + continue |
| 144 | + item = _parse_address_transaction(entry) |
| 145 | + if item: |
| 146 | + parsed.append(item) |
| 147 | + return parsed |
| 148 | + |
| 149 | + |
| 150 | +def merge_wallet_transactions( |
| 151 | + *groups: list[WalletTransactionItem], |
| 152 | + limit: int, |
| 153 | +) -> list[WalletTransactionItem]: |
| 154 | + seen: set[str] = set() |
| 155 | + merged: list[WalletTransactionItem] = [] |
| 156 | + for group in groups: |
| 157 | + ordered = sorted(group, key=lambda tx: tx.create_date, reverse=True) |
| 158 | + for item in ordered: |
| 159 | + key = item.id or item.tx_hash |
| 160 | + if not key or key in seen: |
| 161 | + continue |
| 162 | + seen.add(key) |
| 163 | + merged.append(item) |
| 164 | + if len(merged) >= limit: |
| 165 | + return merged |
| 166 | + return merged |
| 167 | + |
| 168 | + |
| 169 | +def fetch_onchain_wallet_activity( |
| 170 | + *, |
| 171 | + limit: int = 15, |
| 172 | + env: Mapping[str, str] | None = None, |
| 173 | +) -> list[WalletTransactionItem]: |
| 174 | + """Circle wallet token transfers plus deployer contract calls (e.g. purchasePolicy).""" |
| 175 | + current = _env(env) |
| 176 | + wallet = _env_address(current, "CIRCLE_WALLET_ID") |
| 177 | + deployer = _env_address(current, "BASE_SEPOLIA_DEPLOYER_ADDRESS") |
| 178 | + wallet_txs = fetch_blockscout_token_transfers(wallet, limit=limit) if wallet.startswith("0x") else [] |
| 179 | + deployer_txs = fetch_blockscout_address_transactions(deployer, limit=limit) if deployer.startswith("0x") else [] |
| 180 | + return merge_wallet_transactions(wallet_txs, deployer_txs, limit=limit) |
0 commit comments