# Moltalyzer API v4.5.2

Real-time intelligence feeds for AI agents, **led by Polymarket prediction-market intelligence**: noise-filtered market movers, tracked-whale entries with hold-to-resolution calibration (follow/fade), order-book microstructure, markets resolving soon, on-demand single-market research, and a 4-hourly synthesized digest — computed signal, not raw odds. Plus hourly digests of AI agent discussions on [Moltbook](https://moltbook.com), daily GitHub trending repo digests, cross-source narrative intelligence via Pulse, a Master Intelligence Digest, and token intelligence (⚠️ **temporarily offline** — scoring migrating to self-hosted inference; free index/latest still up).

**Base URL:** `https://api.moltalyzer.xyz`

---

## Endpoints

### Moltbook Digests (Hourly)

| Endpoint | Price | Description |
|----------|-------|-------------|
| `GET /api` | Free | This documentation |
| `GET /api/moltbook/sample` | Free | Sample digest for testing (1 req/20min) |
| `GET /api/moltbook/digests/latest` | **Free** (5 req/min) | Most recent hourly digest |
| `GET /api/moltbook/digests?hours=6&limit=6` | **$0.02 USDC** | Historical digests (1-24 hours) |

### GitHub Digests (Daily)

| Endpoint | Price | Description |
|----------|-------|-------------|
| `GET /api/github/sample` | Free | Static sample GitHub digest for testing (1 req/20min) |
| `GET /api/github/digests/latest` | **Free** (5 req/min) | Most recent daily GitHub digest |
| `GET /api/github/digests?days=7&limit=7` | **$0.05 USDC** | Historical daily GitHub digests (1-30 days) |
| `GET /api/github/repos?limit=30&language=Python` | **$0.01 USDC** | Top trending repos from latest scan |

### Polymarket Predetermined Outcome Detection (Signal Feed)

| Endpoint | Price | Description |
|----------|-------|-------------|
| `GET /api/polymarket/index` | Free | Feed index — poll to detect new items |
| `GET /api/polymarket/pulse` | Free | Top-3 noise-filtered movers (24h) + digest teaser |
| `GET /api/polymarket/track-record` | Free | Verifiable whale-calibration scorecard — win rate, follow/fade ROI, per-odds-band breakdown, top-10 wallets (full addresses). Verify accuracy before paying for `/whales` |
| `GET /api/polymarket/latest` | **$0.01 USDC** (or 3/day free w/ API key) | Most recent typed feed item |
| `GET /api/polymarket/digest/brief` | Free | Digest title + summary teaser |
| `GET /api/polymarket/sample` | Free | Static samples of every paid shape, incl. `whatYouGet` + microstructure (1 req/20min) |
| `GET /api/polymarket/signal?index=N` | **$0.01 USDC** | One typed feed item: quality-gated mover (+microstructure) \| whale_entry (+microstructure, named whale) \| predetermined |
| `GET /api/polymarket/signals?since=N&type=` | **$0.03 USDC** | Batch up to 20 typed feed items (quality-gated movers + order-book microstructure) |
| `GET /api/polymarket/resolving?withinHours=24` | **$0.02 USDC** | Markets resolving within 1-72h: odds, convergence, microstructure |
| `GET /api/polymarket/whales` | **$0.05 USDC** | Whale calibration: win rates by odds band, mirror/fade ROI, labels |
| `GET /api/polymarket/digest` | **$0.10 USDC** | Full Intelligence Digest (4h, staleness-guarded) |
| `GET /api/polymarket/digest/history` | **$0.05 USDC** | Past digests (up to 7 days) |
| `GET /api/polymarket/research?market=slug` | **$1.00 USDC** | Single-market deep-dive (30min cache) |

### Pulse — Cross-Source Narrative Intelligence

Tracks how stories form across Reddit, Hacker News, Twitter, GitHub, and prediction markets. Narrative lifecycle: emerging → developing → peak → fading → archived.

| Endpoint | Price | Description |
|----------|-------|-------------|
| `GET /api/pulse/` | Free | Service discovery + discipline info |
| `GET /api/pulse/ai-business/index` | Free | Latest digest ID for polling |
| `GET /api/pulse/ai-business/digest/brief` | Free | Current digest title, summary, top insights |
| `GET /api/pulse/ai-business/digest/latest` | **Free** (5 req/min) | Full narrative intelligence digest |
| `GET /api/pulse/ai-business/narratives` | **$0.01 USDC** | Active narratives with lifecycle stage |
| `GET /api/pulse/ai-business/narratives/:id` | **$0.01 USDC** | Narrative detail with content items + history |
| `GET /api/pulse/ai-business/content/recent` | **$0.02 USDC** | Raw scraped content (last 4 hours) |
| `GET /api/pulse/sample` | Free | Sample digest (24hr delayed) |

### Deprecated Endpoints

The following endpoints have been moved. They now return HTTP 301 redirects to the new paths:

| Old Endpoint | New Endpoint |
|-------------|-------------|
| `GET /api/digests/latest` | `GET /api/moltbook/digests/latest` |
| `GET /api/digests` | `GET /api/moltbook/digests` |
| `GET /api/sample` | `GET /api/moltbook/sample` |

---

## How to Access Paid Endpoints

This API uses [x402](https://x402.org) - an open payment protocol built on HTTP 402. You pay per-request with USDC on **Base Mainnet**. No API keys, no accounts, no KYC.

Paid endpoints answer with a standard **x402 V2** 402: the full PaymentRequirements arrive in the base64 `PAYMENT-REQUIRED` response header (`x402Version: 2`, complete `accepts` array), so stock x402 clients (`@x402/fetch`, `@x402/axios`) pay them out-of-the-box. When submitting the signed payment, the server accepts either the `PAYMENT-SIGNATURE` (standard V2) or `X-PAYMENT` (legacy) request header.

### What You Need

1. An EVM wallet private key (any Ethereum-compatible wallet)
2. USDC on Base Mainnet (at least $0.02 to try both endpoints)
3. One of the x402 client libraries (handles payments automatically)

### Wallet Private Key

The x402 client needs your EVM wallet private key to sign payment authorizations. Different agent frameworks store this under different environment variable names. The code examples below check all common names automatically:

| Environment Variable | Used By |
|---|---|
| `EVM_PRIVATE_KEY` | Coinbase x402 official, most ClawHub skills, ElizaOS |
| `PRIVATE_KEY` | ERC-8004 SDK, x402 starter kit |
| `BLOCKRUN_WALLET_KEY` | ClawRouter |
| `WALLET_PRIVATE_KEY` | Virtuals Protocol ACP |

If you already have any of these set, the examples below will find it. If not, export one:
```bash
export EVM_PRIVATE_KEY="0xYourPrivateKeyHere"
```

### Fund Your Wallet

You need USDC on **Base Mainnet** (Chain ID: 8453). If you don't have any:
- Bridge USDC from Ethereum to Base via [bridge.base.org](https://bridge.base.org)
- Or buy USDC directly on Base through any major exchange

Even $1 of USDC covers 100 paid requests to `/api/polymarket/signal` ($0.01 each).

### Step 2: Install the Client Library

**TypeScript/Node.js:**
```bash
npm install @x402/fetch @x402/evm viem
```

**Python:**
```bash
pip install "x402[httpx]" eth_account
```

### Step 3: Make a Paid Request

**TypeScript (complete working example):**
```typescript
import { x402Client, wrapFetchWithPayment } from "@x402/fetch";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";

// Find wallet key from any common env var name
const key = process.env.EVM_PRIVATE_KEY
  || process.env.PRIVATE_KEY
  || process.env.BLOCKRUN_WALLET_KEY
  || process.env.WALLET_PRIVATE_KEY;

if (!key) throw new Error("No wallet key found. Set EVM_PRIVATE_KEY.");

const signer = privateKeyToAccount(key as `0x${string}`);

// Set up x402 client
const client = new x402Client();
registerExactEvmScheme(client, { signer });

// Wrap fetch - it now handles 402 payments automatically
const fetchWithPayment = wrapFetchWithPayment(fetch, client);

// Make a paid request - that's it!
const response = await fetchWithPayment(
  "https://api.moltalyzer.xyz/api/polymarket/signal"
);
const { data } = await response.json();

console.log(`Type: ${data.type}`);   // mover | whale_entry | predetermined
console.log(`Market: ${data.title}`);
```

**Python (complete working example):**
```python
import asyncio
import os
from eth_account import Account
from x402 import x402Client
from x402.http.clients import x402HttpxClient
from x402.mechanisms.evm import EthAccountSigner
from x402.mechanisms.evm.exact.register import register_exact_evm_client

# Find wallet key from any common env var name
key = (os.getenv("EVM_PRIVATE_KEY")
    or os.getenv("PRIVATE_KEY")
    or os.getenv("BLOCKRUN_WALLET_KEY")
    or os.getenv("WALLET_PRIVATE_KEY"))

if not key:
    raise ValueError("No wallet key found. Set EVM_PRIVATE_KEY.")

async def main():
    # Set up x402 client with your wallet
    client = x402Client()
    account = Account.from_key(key)
    register_exact_evm_client(client, EthAccountSigner(account))

    # Make a paid request - payment is automatic
    async with x402HttpxClient(client) as http:
        response = await http.get(
            "https://api.moltalyzer.xyz/api/polymarket/signal"
        )
        data = response.json()["data"]
        print(f"Type: {data['type']}")     # mover | whale_entry | predetermined
        print(f"Market: {data['title']}")

asyncio.run(main())
```

### Recommended Pattern: Poll Free, Pay on Change

Production callers use this loop — poll the **free** `/api/polymarket/index` to detect new feed items, then pay only when the index advances. Cost stays near zero on quiet markets; you never pay for data you've already seen.

**TypeScript:**
```typescript
let lastSeen = 0;
setInterval(async () => {
  // Free — no payment needed
  const { index } = await (await fetch("https://api.moltalyzer.xyz/api/polymarket/index")).json();
  if (index <= lastSeen) return;                       // nothing new
  // Paid ($0.03) — batch-fetch everything since lastSeen in one call
  const { data } = await (await fetchWithPayment(
    `https://api.moltalyzer.xyz/api/polymarket/signals?since=${lastSeen}`
  )).json();
  for (const item of data) handle(item);               // mover | whale_entry | predetermined
  lastSeen = index;
}, 40_000);
```

**Python:**
```python
last_seen = 0
while True:
    idx = (await http_free.get("https://api.moltalyzer.xyz/api/polymarket/index")).json()["index"]
    if idx > last_seen:
        # Paid ($0.03) — batch-fetch new items since last_seen
        resp = await http.get(f"https://api.moltalyzer.xyz/api/polymarket/signals?since={last_seen}")
        for item in resp.json()["data"]:
            handle(item)                                # mover | whale_entry | predetermined
        last_seen = idx
    await asyncio.sleep(40)
```

### Quick Check: Do You Already Have x402?

If you're running through **ClawRouter** (port 8402), x402 payments are already handled for you. Just fetch the endpoint directly — ClawRouter intercepts the 402 and pays automatically.

If you have `@x402/fetch` installed and a wallet key set, run this one-liner to test:
```bash
node -e "
const {x402Client,wrapFetchWithPayment}=require('@x402/fetch');
const {registerExactEvmScheme}=require('@x402/evm/exact/client');
const {privateKeyToAccount}=require('viem/accounts');
const k=process.env.EVM_PRIVATE_KEY||process.env.PRIVATE_KEY||process.env.BLOCKRUN_WALLET_KEY||process.env.WALLET_PRIVATE_KEY;
const c=new x402Client();registerExactEvmScheme(c,{signer:privateKeyToAccount(k)});
const f=wrapFetchWithPayment(fetch,c);
f('https://api.moltalyzer.xyz/api/moltbook/digests/latest').then(r=>r.json()).then(d=>console.log(d.data.title));
"
```

### How It Works Under the Hood

You don't need to understand this to use the API - the client libraries handle it all. But if you're curious:

1. Your code calls `fetchWithPayment("https://api.moltalyzer.xyz/api/moltbook/digests/latest")`
2. The server responds with a standard x402 V2 `402 Payment Required` + a base64 `PAYMENT-REQUIRED` header carrying the full PaymentRequirements (x402Version 2, complete `accepts` array with price, payment address, network)
3. The x402 library reads this, signs a USDC transfer authorization with your wallet
4. The library retries the request with the signed payment in the `PAYMENT-SIGNATURE` header (the server also accepts the legacy `X-PAYMENT` header)
5. The server verifies the payment, settles the USDC transfer, and returns the data

All of this happens in a single `await` call from your perspective.

---

## Response Format

### GET /api/moltbook/digests/latest

Returns the most recent completed hourly digest.

```json
{
  "success": true,
  "data": {
    "id": "abc123",
    "hourStart": "2026-02-06T18:00:00Z",
    "hourEnd": "2026-02-06T19:00:00Z",
    "title": "Agents Debate Quantum Computing and Trust Protocols",
    "summary": "Brief 2-3 sentence overview of the hour...",
    "fullDigest": "Detailed markdown analysis of all discussions...",
    "totalPosts": 1100,
    "qualityPosts": 790,
    "topTopics": ["quantum computing", "trust protocols", "DeFi"],
    "emergingNarratives": ["Quantum-inspired computing for optimization"],
    "continuingNarratives": ["AI autonomy debates"],
    "fadingNarratives": ["NFT speculation"],
    "hotDiscussions": [
      {
        "topic": "Quantum computing feasibility",
        "sentiment": "skeptical but curious",
        "description": "Agents debating whether quantum approaches are practical...",
        "notableAgents": ["QuantumPathfinder", "Doormat", "ClawdNew123"]
      }
    ],
    "overallSentiment": "philosophical",
    "sentimentShift": "stable",
    "createdAt": "2026-02-06T19:05:00Z"
  }
}
```

### GET /api/moltbook/digests?hours=6&limit=6

Same format as above, but returns an array of digests.

**Parameters:**
- `hours`: 1-24 (default: 24) - how far back to look
- `limit`: 1-24 (default: 24) - max number of digests to return

```json
{
  "success": true,
  "count": 6,
  "hours": 6,
  "limit": 6,
  "data": [ /* array of digest objects */ ]
}
```

### GET /api/moltbook/sample

Free sample digest for testing integration. Returns a digest that is at least 18 hours old. Rate limited to 1 request per 20 minutes.

---

## GitHub Endpoints

### GET /api/github/digests/latest

Returns the most recent daily GitHub digest — trending new repos, emerging tools, language trends.

```json
{
  "success": true,
  "data": {
    "id": "string",
    "digestDate": "2026-02-12T05:00:00.000Z",
    "title": "GitHub Daily Digest — 2026-02-12",
    "summary": "AI-driven development dominates today's new repositories...",
    "fullAnalysis": "## Categories of Work\n\n...",
    "topCategories": [],
    "emergingTools": [],
    "languageTrends": [],
    "notableProjects": [],
    "totalReposAnalyzed": 20,
    "overallSentiment": "mixed",
    "volumeMetrics": { "totalReposCreated": 277911, "totalWithStars": 5246, "..." : "..." },
    "createdAt": "2026-02-13T16:01:25.174Z"
  }
}
```

### GET /api/github/digests?days=7&limit=7

Same format as above, returns an array of daily digests.

**Parameters:**
- `days`: 1-30 (default: 7) — how far back to look
- `limit`: 1-30 (default: 7) — max number of digests to return

### GET /api/github/repos?limit=30&language=Python

Top trending repos from the most recent daily scan, sorted by stars.

**Parameters:**
- `limit`: 1-100 (default: 30) — max repos to return
- `language`: filter by programming language (case-insensitive, optional)

### GET /api/github/sample

Free static sample GitHub digest for testing. Rate limited to 1 request per 20 minutes.

---

## Polymarket Endpoints

**v4 (2026-06-12):** rebuilt on a live 42K-market pipeline (60s price snapshots, order books, tracked-whale wallets, international news). One index-polled feed carries three item types; plus a whale calibration table, a 4-hourly synthesized digest, and on-demand deep-dive research.

**v4.3.0 (2026-06-24):** movers are quality-gated — surfaced only when 24h volume >= $10k AND order-book depth-within-5c >= $2.5k (or volume >= $25k when the book is uncomputable). Thin-book wiggles are filtered out (~16-20 quality movers/day instead of ~39); every mover is a tradeable repricing in a market with a standable order book. Order-book microstructure (depth-within-5c, spread, best bid/ask, USD-impact-to-move-5c) is attached to every mover and whale_entry, whale items resolve known trader names (e.g. "Domer"), and the predetermined classifier no longer flags diplomatic/government scheduling questions.

### GET /api/polymarket/index

Free poll target. When `index` advances, fetch new items with `/signals?since=<lastSeen>`.

```json
{ "success": true, "status": "live", "index": 1076,
  "lastUpdated": "2026-06-12T19:31:09.000Z", "totalToday": 75,
  "todayByType": { "whale_entry": 72, "mover": 3 } }
```

### GET /api/polymarket/signal?index=N — $0.01

One typed feed item. Envelope: `{feedIndex, type, title, createdAt, data}`.

- `type: "mover"` — quality-gated repricing (vol >= $10k AND depth-within-5c >= $2.5k, or vol >= $25k when book uncomputable): `data = { question, slug, window, priceStart, priceNow, delta, direction, liquidityUsd, volumeUsd, microstructure: { depthWithin5cUsd, spread, bestBid, bestAsk, usdImpactToMove5c } }`
- `type: "whale_entry"` — tracked-whale entry (cost >= $1k): `data = { pseudonym (resolved trader name, e.g. "Domer"), market, slug, outcome, entryOdds, costBasisUsd, entryAt, microstructure: { depthWithin5cUsd, spread, bestBid, bestAsk, usdImpactToMove5c }, walletCalibration: { resolvedEntries, winRate, holdToResolutionRoi, fadeRoi, label } }`
- `type: "predetermined"` — AI-detected predetermined-outcome market: `data = { question, confidence, reasoning, predeterminedType, knowledgeHolder, outcomePrices, volumeUsd, liquidityUsd }` (diplomatic/government scheduling questions are no longer flagged — they're future choices, not sealed records)

### GET /api/polymarket/signals?since=N&count=10&type= — $0.03

Batch of up to 20 typed feed items. `type` filter: `mover`, `whale_entry`, or `predetermined`.

### GET /api/polymarket/resolving — $0.02

Markets whose event ends within `?withinHours` (1-72, default 24): current odds, convergence
state, liquidity, and order-book microstructure for the 10 nearest expiries. Mechanical
short-interval markets excluded by default (`?includeNoise=1` to include). End dates are
event-level and Polymarket-scheduled.

### GET /api/polymarket/whales — $0.05

Per-wallet whale calibration, updated hourly: win rate overall + by odds band (longshot/mid/favorite), mirror-ROI, fade-ROI, follow/fade/neutral label (min 30 resolved). **Measures entries held to resolution, not trader P&L** — exits are not tracked.

### GET /api/polymarket/digest — $0.10 (brief free, history $0.05)

Synthesized 4-hourly digest: What Moved and Why / Whale Positioning (calibration-weighted) / Watchlist, plus structured topMovers, whaleActivity, newsContext. 503 instead of stale data, always. `/digest/brief` is the free teaser; `/digest/history?hours=24&limit=6` (max 7 days).

### GET /api/polymarket/research?market=<slug> — $1.00

Single-market deep-dive: 7d price action, live order book, whale positioning with calibration, related international news, synthesized `thesis/risks/confidence/bottomLine`. Accepts market slug or 0x conditionId. 10-60s generation, cached 30 minutes.

### GET /api/polymarket/sample

Free static sample signal for testing. Rate limited to 1 request per 20 minutes.

---

### Token Intelligence (Real-Time Signal Feed) — ⚠️ TEMPORARILY OFFLINE

**This product is paused.** The advertised hybrid rule+LLM scoring is migrating to self-hosted inference — the LLM half went dark when the OpenRouter path was retired, leaving signals rule-only, so the feed was paused. Paid endpoints (`/signal`, `/signals`, `/history`) return **503 with `status:"offline"` and NO x402 challenge — nothing is charged.** Free endpoints (`/index`, `/latest`, `/sample`) stay up and carry `status:"offline"` plus a notice. Poll `/index`; `status` returns to `"live"` on relaunch.

| Endpoint | Price | Description |
|----------|-------|-------------|
| `GET /api/tokens/index` | Free | Up; carries `status:"offline"`. Current signal index / relaunch poll |
| `GET /api/tokens/sample` | Free | Up; carries `status:"offline"`. One 24hr+ old signal for testing (1 req/20min) |
| `GET /api/tokens/latest` | **Free** (5 req/min) | Up; carries `status:"offline"`. Most recent token signal |
| `GET /api/tokens/signal?index=N` | **$0.01 USDC** (when live) | **Offline: 503, no charge.** Single token signal — latest or by index |
| `GET /api/tokens/signals?since=N&count=5` | **$0.05 USDC** (when live) | **Offline: 503, no charge.** Batch up to 20 signals (filterable) |
| `GET /api/tokens/history?from=YYYY-MM-DD` | **$0.03 USDC** (when live) | **Offline: 503, no charge.** Historical signals by date range (up to 7 days, paginated) |

### GET /api/tokens/history

⚠️ **Temporarily offline — returns 503 with `status:"offline"` and no x402 charge.** When live, returns historical token signals within a date range. Paginated, max 7-day range per request.

**Parameters:**
- `from` (required): ISO date or YYYY-MM-DD, inclusive
- `to` (optional, default: now): ISO date or YYYY-MM-DD, exclusive
- `chain`: filter by chain (ethereum, base, bsc)
- `tier`: filter by tier (meme, longterm)
- `minScore`: minimum hybrid score 0-100 (default: 0)
- `page`: page number (default: 1)
- `limit`: results per page, 1-100 (default: 20)

---

## API Versioning

All responses include a `_meta` object with the current API version and a link to the changelog:

```json
{
  "_meta": {
    "apiVersion": "4.5.2",
    "changelog": "https://api.moltalyzer.xyz/api/changelog"
  }
}
```

Fetch `GET /api/changelog` for a structured list of changes by version.

## Rate Limits

- **General:** 10 requests/second, 50 requests/10 seconds burst
- **Sample endpoints:** 1 request per 20 minutes

Rate limit headers included: `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset`, `Retry-After`

## Errors

| Status | Meaning |
|--------|---------|
| 301 | Endpoint moved (deprecated — check `newEndpoint` field) |
| 400 | Invalid parameters |
| 402 | Payment required (see setup guide above) |
| 404 | Resource not found |
| 429 | Rate limited |
| 500 | Server error |
| 502 | Paid compute failed after settlement — a refund is auto-queued (paid compute routes only). Body carries `{"refund":"queued"}`; non-2xx passthroughs carry an `x-refund-queued: 1` header |
| 503 | Feed temporarily offline (e.g. Token Intelligence) or data stale. Body carries `status` / `retryAfter`; no x402 charge |

## Payment Details

- **Network:** Base Mainnet (eip155:8453)
- **Currency:** USDC
- **Protocol:** x402 v2
- **More info:** [x402.org](https://x402.org) | [GitHub](https://github.com/coinbase/x402)

**Paid-compute reliability guarantee (v4.5.1):** the paid compute routes — `POST /api/moltbook/advisor`, `GET /api/polymarket/research`, `GET /api/polymarket/resolving`, `GET /api/polymarket/whales` — carry a written guarantee: if your payment settles but the result can't be delivered, a refund is automatically queued (no request needed). Detect it via a `502` with body `{"refund":"queued"}`, or an `x-refund-queued: 1` header on non-2xx responses. You are still only charged for delivered compute.
