File size: 2,213 Bytes
c647bd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
Tiny FastAPI proxy for the Polymarket Control Deck.

- Serves index.html at /
- Proxies /api/events        -> https://gamma-api.polymarket.com/events
- Proxies /api/prices-history-> https://clob.polymarket.com/prices-history

The Gamma API whitelists CORS to https://polymarket.com only, so a browser
running on huggingface.co/spaces/... cannot call it directly. This proxy
sidesteps that by running on the same origin as the static frontend.
"""

from __future__ import annotations

import httpx
from fastapi import FastAPI, Request, Response
from fastapi.responses import FileResponse

GAMMA = "https://gamma-api.polymarket.com"
CLOB = "https://clob.polymarket.com"

app = FastAPI(title="Polymarket Control Deck")
client = httpx.AsyncClient(
    timeout=httpx.Timeout(20.0),
    headers={
        # Gamma responds to this origin with the right CORS headers; it also
        # happens to serve the canonical response, so we impersonate it here.
        "Origin": "https://polymarket.com",
        "Referer": "https://polymarket.com/",
        "User-Agent": (
            "Mozilla/5.0 polymarket-control-deck/1.0 (FastAPI proxy)"
        ),
    },
)


async def _proxy(upstream_url: str, request: Request) -> Response:
    params = dict(request.query_params)
    try:
        r = await client.get(upstream_url, params=params)
    except httpx.HTTPError as e:
        return Response(
            content=f'{{"error":"upstream_error","detail":"{type(e).__name__}"}}',
            status_code=502,
            media_type="application/json",
        )
    # Pass through JSON. Strip hop-by-hop headers.
    return Response(
        content=r.content,
        status_code=r.status_code,
        media_type=r.headers.get("content-type", "application/json"),
    )


@app.get("/api/events")
async def events(request: Request) -> Response:
    return await _proxy(f"{GAMMA}/events", request)


@app.get("/api/prices-history")
async def prices_history(request: Request) -> Response:
    return await _proxy(f"{CLOB}/prices-history", request)


@app.get("/api/health")
async def health() -> dict:
    return {"status": "nominal"}


@app.get("/")
async def root() -> FileResponse:
    return FileResponse("index.html")