"""Flask app — the shippable front end. Routes: / landing + "paste a wallet" scorer form + email capture /score GET ?wallet=0x… -> live consistency score card (lead magnet) /digest latest daily digest rendered as HTML (SEO surface) /subscribe POST email -> data/subscribers.csv Run: cd polymarket-copytrade && source .venv/bin/activate python webapp/app.py # http://127.0.0.1:5000 """ from __future__ import annotations import csv import re import os import sys from datetime import datetime, timezone from html import escape from pathlib import Path _ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(_ROOT)) os.chdir(_ROOT) # so config.yaml + data/ resolve regardless of launch cwd from flask import Flask, request, redirect, url_for from pmct.client import PolymarketClient from pmct.score import score_wallet from pmct.util import load_config, cache_path app = Flask(__name__) _cfg = load_config() _client = PolymarketClient(sleep_sec=0.1) BRAND = "SharpFlow" TAGLINE = "The Polymarket smart-money tracker whale trackers miss." CSS = """ :root{--bg:#0a0f14;--card:#111820;--ink:#e6edf3;--mut:#7d8da0;--body:#c7d0dc;--acc:#22d3ee; --acc2:#14b8a6;--warn:#d29922;--bad:#f85149;--line:#1c2531;--inset:#0c131b} *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink); font:16px/1.55 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif; background-image:radial-gradient(900px 500px at 80% -10%,rgba(34,211,238,.10),transparent 70%), radial-gradient(700px 400px at -10% 10%,rgba(20,184,166,.08),transparent 70%)} a{color:var(--acc);text-decoration:none}a:hover{text-decoration:underline} .wrap{max-width:820px;margin:0 auto;padding:32px 20px} .brand{font-weight:800;font-size:22px;letter-spacing:-.02em} .brand span{background:linear-gradient(135deg,var(--acc),var(--acc2)); -webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent} .hero{margin:28px 0 10px}.hero h1{font-size:34px;line-height:1.15;margin:0 0 10px;letter-spacing:-.02em} .hero p{color:var(--mut);font-size:18px;margin:0} .card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:22px;margin:18px 0} input[type=text],input[type=email]{width:100%;padding:13px 14px;border-radius:10px; border:1px solid var(--line);background:var(--inset);color:var(--ink);font-size:15px} input:focus{outline:none;border-color:var(--acc);box-shadow:0 0 0 3px rgba(34,211,238,.15)} .row{display:flex;gap:10px;flex-wrap:wrap}.row>*{flex:1;min-width:180px} button{background:linear-gradient(135deg,var(--acc),var(--acc2));color:#04121a;border:0; border-radius:10px;padding:13px 18px;font-weight:700;font-size:15px;cursor:pointer; white-space:nowrap;flex:0 0 auto}button:hover{filter:brightness(1.08)} button.ghost{background:transparent;color:var(--ink);border:1px solid var(--line)} .mut{color:var(--mut)}.small{font-size:13px}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace} .tag{display:inline-block;padding:3px 10px;border-radius:999px;font-size:12px;font-weight:700} .tag.watch{background:#0c3138;color:var(--acc)}.tag.whale{background:#3a2f10;color:var(--warn)} .tag.maker{background:#3a1414;color:var(--bad)}.tag.inconsistent{background:#2a2033;color:#c98bff} .tag.thin,.tag.bad{background:#1a222c;color:var(--mut)} .grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-top:14px} .metric{background:var(--inset);border:1px solid var(--line);border-radius:10px;padding:12px} .metric .k{color:var(--mut);font-size:12px}.metric .v{font-size:20px;font-weight:700;margin-top:2px} .bar{height:8px;background:var(--inset);border-radius:6px;overflow:hidden;margin-top:6px} .bar>i{display:block;height:100%;background:linear-gradient(90deg,var(--acc),var(--acc2))} table{border-collapse:collapse;width:100%;font-size:14px}th,td{border-bottom:1px solid var(--line); padding:8px 6px;text-align:left}th{color:var(--mut);font-weight:600} tbody tr:hover{background:rgba(34,211,238,.04)} .foot{color:var(--mut);font-size:12px;margin-top:26px;border-top:1px solid var(--line);padding-top:16px} .pill{border:1px solid var(--line);border-radius:999px;padding:4px 12px;font-size:13px;color:var(--mut)} .nav{display:flex;align-items:center;justify-content:space-between;gap:16px; padding-bottom:12px;border-bottom:1px solid var(--line)} .nav .brand{text-decoration:none;color:var(--ink)} .navlinks{display:flex;gap:20px}.navlinks a{color:var(--mut);font-weight:600;font-size:14px} .navlinks a:hover{color:var(--acc);text-decoration:none} .examples{margin-top:14px;display:flex;flex-wrap:wrap;gap:8px;align-items:center} .exlabel{color:var(--mut);font-size:13px;margin-right:2px} .chip{border:1px solid var(--line);background:var(--inset);border-radius:999px; padding:6px 12px;font-size:13px;color:var(--ink)} .chip:hover{border-color:var(--acc);color:var(--acc)} ul.explain{margin:10px 0 0;padding-left:20px}ul.explain li{margin:10px 0;color:var(--body); line-height:1.65;max-width:64ch}ul.explain b{color:var(--ink)} .tscroll{overflow-x:auto;-webkit-overflow-scrolling:touch} .tscroll table{min-width:520px} .digest p{color:var(--body);line-height:1.7;max-width:66ch;margin:12px 0} .digest h2{font-size:19px;margin:28px 0 6px;letter-spacing:-.01em} .digest h2:first-child{margin-top:4px} .digest .lead{font-size:15px;color:var(--mut);margin:0 0 6px} .tiers{display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin:18px 0} .tier{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:22px; display:flex;flex-direction:column} .tier.feat{border-color:var(--acc);box-shadow:inset 0 0 0 1px var(--acc)} .tier h3{margin:0;font-size:18px} .tier .price{font-size:30px;font-weight:800;letter-spacing:-.02em;margin:8px 0 0} .tier .price small{font-size:14px;font-weight:600;color:var(--mut)} .tier .soon{display:inline-block;margin:8px 0 0;font-size:12px;font-weight:700; color:var(--acc);background:#0c3138;padding:3px 10px;border-radius:999px} .tier .live{display:inline-block;margin:8px 0 0;font-size:12px;font-weight:700; color:var(--acc2);background:#0c2c28;padding:3px 10px;border-radius:999px} .tier ul.feats{list-style:none;margin:14px 0 18px;padding:0;flex:1} .tier ul.feats li{margin:9px 0;padding-left:22px;position:relative;color:var(--body);line-height:1.5} .tier ul.feats li:before{content:'\\2713';position:absolute;left:0;color:var(--acc);font-weight:700} .tier .cta{margin-top:auto} @media (max-width:760px){.tiers{grid-template-columns:1fr}} @media (max-width:640px){ .wrap{padding:20px 14px} .hero h1{font-size:26px}.hero p{font-size:16px} .card{padding:16px} .grid{grid-template-columns:1fr 1fr} .navlinks{gap:14px}.navlinks a{font-size:13px} .brand{font-size:19px} button{width:100%}.row>*{min-width:100%} table{font-size:13px}th,td{padding:7px 5px} } @media (max-width:380px){.grid{grid-template-columns:1fr}} """ # Real wallets that showcase the product's judgement — one to follow, one too big # to mirror, one uncopyable. Doubles as the "try it" hook so a first-time visitor # never dead-ends on a random address with no Polymarket history. EXAMPLES = [ ("Consistent mid-size", "0x28059b3fb7af7ed76d83dc9121bbb72ec7cf76ed"), ("Mega-whale", "0xd235973291b2b75ff4070e9c0b01728c520b0f29"), ("Market-maker", "0x5d189e816b4149be00977c1a3c8840374aec4972"), ] def example_chips(label: str = "Try a real trader:") -> str: chips = "".join( f'{escape(t)}' for t, w in EXAMPLES ) return f'
{escape(label)}{chips}
' TAGLABEL = {"watch": "WORTH WATCHING", "whale": "MEGA-WHALE", "maker": "MARKET-MAKER", "inconsistent": "INCONSISTENT", "thin": "TOO THIN", "bad": "INVALID"} DIGEST_EXPLAINER = """

Daily smart-money digest

The mid-size Polymarket traders who win consistently — and the boldest bets they just made.

What am I looking at?

Flow intelligence, not financial advice.

""" SITE_URL = "https://sharpflowapp-web.hf.space" JSONLD = ( '{"@context":"https://schema.org","@type":"WebApplication",' '"name":"SharpFlow","applicationCategory":"FinanceApplication",' '"operatingSystem":"Web","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},' '"description":"Score any Polymarket wallet and follow consistent mid-size smart-money ' 'traders that whale trackers miss.","url":"' + SITE_URL + '"}' ) def page(title: str, body: str, desc: str = "", path: str = "/") -> str: desc = desc or TAGLINE canon = SITE_URL + path return f""" {escape(title)}
{body}
Built from Polymarket public data. Flow intelligence, not financial advice. Consistency scoring ≠ guaranteed profit. Past performance is not predictive.
""" @app.route("/robots.txt") def robots(): return (f"User-agent: *\nAllow: /\nSitemap: {SITE_URL}/sitemap.xml\n", 200, {"Content-Type": "text/plain"}) @app.route("/sitemap.xml") def sitemap(): urls = ["/", "/digest", "/pricing"] items = "".join(f"{SITE_URL}{u}" for u in urls) xml = ('' '' f"{items}") return xml, 200, {"Content-Type": "application/xml"} def scorer_form(prefill: str = "") -> str: return f"""
""" @app.route("/") def home(): body = f"""

{escape(TAGLINE)}

Paste any Polymarket wallet and we score it — consistent smart money, a whale, a market-maker, or just lucky. Every tracker flags $10k whales; we surface the consistent mid-size Polymarket traders they skip.

Score any wallet — free

{scorer_form()} {example_chips()}

Paste any Polymarket address. We read its history and tell you: consistent & copyable, a whale, a market-maker, or just lucky.

Get the daily digest

The top consistent traders and their highest-conviction moves, once a day. Free tier delayed 24h.

""" return page( f"{BRAND} — Polymarket smart-money tracker & free wallet score", body, desc="Score any Polymarket wallet free, and follow consistent mid-size " "smart-money traders that whale trackers miss. Flow intelligence, not " "financial advice.", path="/") @app.route("/score") def score(): wallet = (request.args.get("wallet") or "").strip() if not wallet: return redirect(url_for("home")) r = score_wallet(_client, wallet) if not r.ok: body = f"""

Nothing to score here

{escape(r.note)} This wallet has no Polymarket trading history we can read — try a real trader below.

{scorer_form(wallet)} {example_chips("Or try one of these:")}
""" return page(f"{BRAND} — score", body) tag = r.verdict_tag or "thin" pct = int(round(r.trader_score * 100)) short = f"{r.wallet[:8]}…{r.wallet[-6:]}" prof = f"https://polymarket.com/profile/{r.wallet}" body = f"""
{escape(r.wallet)} ↗

Trader score: {r.trader_score:.2f} {TAGLABEL.get(tag,tag.upper())}

{escape(r.verdict)}

Consistency (green months)
{r.monthly_profit_ratio:.0%}
Repeatability
{r.repeatability:.2f}
Copyable (1 − rebate)
{max(0,1-r.rebate_share):.0%}
Reconstructed PnL
${r.total_pnl:,.0f}
Avg bet size
${r.avg_trade_usdc:,.0f}
Trades · resolved
{r.n_trades:,} · {r.n_resolved_markets}
Score another{scorer_form()}

{escape(r.note)}

""" return page( f"{short} Polymarket wallet score {r.trader_score:.2f} — {BRAND}", body, desc=f"Polymarket wallet {short} scored {r.trader_score:.2f}: " f"{TAGLABEL.get(tag, tag).lower()}. Consistency, repeatability and " f"copyability — not size.", path="/score") _TABLE_RE = re.compile(r"^\|(.+)\|\s*$") _LINK_RE = re.compile(r"\[([^\]]+)\]\((https?://[^\s)]+)\)") _BOLD_RE = re.compile(r"\*\*([^*]+)\*\*") def _inline(text: str) -> str: """Escape text, then render inline **bold** and [label](https url) links. Links are restricted to http/https so escaped content stays injection-safe.""" out, i = [], 0 for mm in _LINK_RE.finditer(text): out.append(_bold(text[i:mm.start()])) label, url = mm.group(1), mm.group(2) out.append(f'{escape(label)}') i = mm.end() out.append(_bold(text[i:])) return "".join(out) def _bold(text: str) -> str: parts, i = [], 0 for mm in _BOLD_RE.finditer(text): parts.append(escape(text[i:mm.start()])) parts.append(f"{escape(mm.group(1))}") i = mm.end() parts.append(escape(text[i:])) return "".join(parts) def _md_to_html(md: str, terse: bool = False) -> str: """Tiny markdown renderer: headings, tables, hr, paragraphs. Enough for our own digest output — not a general parser. In terse mode we drop the leading H1 and the italic-only legend paragraphs (the web page already explains those in the explainer card), so the render doesn't repeat itself.""" out, rows = [], [] def flush_table(): if not rows: return cells = [[c.strip() for c in r.strip("|").split("|")] for r in rows] body = cells[2:] if len(cells) > 1 and set("".join(cells[1])) <= set("-: ") else cells[1:] head = cells[0] h = "".join(f"{_inline(c)}" for c in head) b = "".join("" + "".join(f"{_inline(c)}" for c in r) + "" for r in body) out.append(f"
{h}{b}
") rows.clear() for ln in md.splitlines(): if _TABLE_RE.match(ln): rows.append(ln) continue flush_table() s = ln.strip() if not s: continue italic_only = len(s) > 1 and s.startswith("_") and s.endswith("_") if terse and (s.startswith("# ") or s == "---" or italic_only): continue if s.startswith("### "): out.append(f"

{escape(s[4:])}

") elif s.startswith("## "): out.append(f"

{escape(s[3:])}

") elif s.startswith("# "): out.append(f"

{escape(s[2:])}

") elif s == "---": out.append("
") else: cls = "lead" if terse else "mut" out.append(f"

{_inline(s.replace('_', ''))}

") flush_table() return "\n".join(out) DIGESTS_DATASET = "sharpflowapp/digests" _digest_cache: dict = {"md": None, "ts": 0.0} _DIGEST_TTL = 300 # seconds — the daily cron only publishes once/day def _local_digest_md() -> str | None: files = sorted(cache_path(_cfg, ".").glob("digest_*.md")) return files[-1].read_text(encoding="utf-8") if files else None def _latest_digest_md() -> str | None: """Newest digest, fetched from the HF dataset (so publishing never rebuilds the Space) with a short TTL cache and a fallback to any baked-in seed file.""" import time now = time.time() if _digest_cache["md"] is not None and now - _digest_cache["ts"] < _DIGEST_TTL: return _digest_cache["md"] md = None token = os.environ.get("HF_TOKEN") try: from huggingface_hub import HfApi, hf_hub_download names = [f for f in HfApi(token=token).list_repo_files( DIGESTS_DATASET, repo_type="dataset") if f.startswith("digest_") and f.endswith(".md")] if names: path = hf_hub_download(DIGESTS_DATASET, sorted(names)[-1], repo_type="dataset", token=token) md = Path(path).read_text(encoding="utf-8") except Exception: md = None if md is None: md = _local_digest_md() # fallback: baked-in seed digest if md is not None: _digest_cache.update(md=md, ts=now) return md @app.route("/digest") def digest(): md = _latest_digest_md() if not md: return page(f"{BRAND} — digest", "

No digest yet

" "

Run python scripts/05_digest.py to generate one.

") body = DIGEST_EXPLAINER \ + f"
{_md_to_html(md, terse=True)}
" \ f"
Want it daily by email?" \ f"
" \ f"" \ f"
" return page( f"{BRAND} — Daily Polymarket smart-money digest", body, desc="The consistent mid-size Polymarket traders whale trackers skip, and " "their highest-conviction moves today — each scored for signal quality.", path="/digest") SUBSCRIBERS_DATASET = "sharpflowapp/subscribers" def _persist_subscriber(email: str, ts: str, kind: str = "digest") -> None: """Durably record a signup in a private HF dataset so it survives the Space's ephemeral filesystem. Append-only (one file per signup) to dodge races. `kind` tags intent (digest signup vs. a paid-tier waitlist) so we can measure willingness-to-pay. Best-effort: never let a storage hiccup break signup UX.""" token = os.environ.get("HF_TOKEN") if not token: return try: import hashlib import io import re as _re from huggingface_hub import HfApi safe = _re.sub(r"[^a-z0-9_]+", "", kind.lower())[:24] or "digest" key = hashlib.sha1(email.encode()).hexdigest()[:12] api = HfApi(token=token) api.upload_file( path_or_fileobj=io.BytesIO(f"{email},{ts},{safe}\n".encode()), path_in_repo=f"emails/{ts[:10]}_{safe}_{key}.csv", repo_id=SUBSCRIBERS_DATASET, repo_type="dataset", ) except Exception: pass @app.route("/subscribe", methods=["POST"]) def subscribe(): email = (request.form.get("email") or "").strip().lower() if "@" in email and "." in email: ts = datetime.now(timezone.utc).isoformat() path = cache_path(_cfg, "subscribers.csv") new = not path.exists() with path.open("a", newline="") as f: w = csv.writer(f) if new: w.writerow(["email", "ts_utc"]) w.writerow([email, ts]) _persist_subscriber(email, ts) msg = "You're in. First digest lands next run." else: msg = "That email didn't look right — try again." return page(f"{BRAND} — subscribed", f"

{escape(msg)}

" f"
{scorer_form()}" f"

Meanwhile, score any wallet above.

") def _waitlist_form(tier: str, cta: str) -> str: return (f"
" f"" f"" f"
") @app.route("/pricing") def pricing(): free_cta = (f"
" f"" f"
") tiers = f"""

Free

$0
Live now {free_cta}

Pro

$19/mo
Coming soon · join waitlist {_waitlist_form("pro", "Join the Pro waitlist")}

Trader

$49/mo
Coming soon · join waitlist {_waitlist_form("trader", "Join the Trader waitlist")}
""" body = f"""

Simple pricing

Start free today. The paid tiers are in build — join a waitlist and you'll be first in when real-time alerts go live, at this early-bird price.

{tiers}

Flow intelligence, not financial advice. Consistency scoring ≠ guaranteed profit. Waitlist just means we email you when the tier opens — no charge, no card, unsubscribe anytime.

""" return page( f"{BRAND} — Pricing", body, desc="SharpFlow pricing: a free daily Polymarket smart-money digest, plus Pro " "real-time alerts and a Trader API tier (coming soon — join the waitlist).", path="/pricing") @app.route("/waitlist", methods=["POST"]) def waitlist(): email = (request.form.get("email") or "").strip().lower() tier = (request.form.get("tier") or "pro").strip().lower() tier = tier if tier in ("pro", "trader") else "pro" if "@" in email and "." in email: ts = datetime.now(timezone.utc).isoformat() _persist_subscriber(email, ts, kind=f"waitlist_{tier}") msg = f"You're on the {tier.title()} waitlist." sub = ("We'll email you the moment it opens — at the early-bird price, no card " "needed now.") else: msg = "That email didn't look right — try again." sub = "Head back to pricing and re-enter it." return page(f"{BRAND} — waitlist", f"

{escape(msg)}

{escape(sub)}

" f"

Meanwhile, the free " f"digest is live today:

" f"
" f"" f"
", path="/pricing") if __name__ == "__main__": port = int(os.environ.get("PORT", "5055")) app.run(host="127.0.0.1", port=port, debug=False)