# https://github.com/BlockRunAI/ClawRouter Project Manual

Generated at: 2026-07-18 10:46:55 UTC

## Table of Contents

- [Overview, Setup, and System Architecture](#page-1)
- [Smart Routing Engine, Profiles, and Model Catalog](#page-2)
- [Wallet, Authentication, and x402 USDC Payment Flow](#page-3)
- [Extended Capabilities: Images, Video, Voice, Polymarket, Surf](#page-4)

<a id='page-1'></a>

## Overview, Setup, and System Architecture

### Related Pages

Related topics: [Smart Routing Engine, Profiles, and Model Catalog](#page-2), [Wallet, Authentication, and x402 USDC Payment Flow](#page-3)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/BlockRunAI/ClawRouter/blob/main/README.md)
- [package.json](https://github.com/BlockRunAI/ClawRouter/blob/main/package.json)
- [src/index.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/index.ts)
- [src/proxy.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/proxy.ts)
- [src/cli.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/cli.ts)
- [src/top-models.json](https://github.com/BlockRunAI/ClawRouter/blob/main/src/top-models.json)
- [src/picker.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/picker.ts)
- [src/payments.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/payments.ts)
- [src/tool-recovery.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/tool-recovery.ts)
- [src/upstream-proxy.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/upstream-proxy.ts)
- [docs/architecture.md](https://github.com/BlockRunAI/ClawRouter/blob/main/docs/architecture.md)
</details>

# Overview, Setup, and System Architecture

ClawRouter is a local proxy and CLI that sits between an LLM client (Codex, Claude Code, OpenClaw, Cursor, etc.) and BlockRun's paid model catalog. It exposes an OpenAI-compatible `/v1` endpoint, performs automatic model selection and alias resolution, signs x402 micropayments (Solana and Base), recovers malformed tool calls, and forwards requests to upstream providers. This page describes what the router does, how to install it, and how its subsystems fit together.

## What ClawRouter Does

The router replaces the `base_url` of any OpenAI-compatible client with `http://127.0.0.1:<port>/v1`, so requests look identical to a normal chat-completions call. Instead of charging a flat subscription, every request carries an x402 payment header settled per call. Model routing is automatic: a request for `gpt-5` may be resolved to a specific tier (Sol/Terra/Luna for the GPT-5.6 family), generic aliases are routed to the stable tier rather than the flaky one, and the `/model` picker presents the BlockRun catalog defined in `src/top-models.json`. Source: [src/top-models.json:1-120]().

In addition to chat, ClawRouter exposes the BlockRun MCP tool surface, including `blockrun_polymarket` for placing and redeeming real-money bets on Polymarket CLOB V2 (Polygon), and `blockrun_predexon_*` for reading prediction-market odds. Source: [CHANGELOG / release v0.12.220]()

## Setup and Installation

ClawRouter is published as an npm package and run as a long-lived local process.

1. Install the CLI: `npm i -g @blockrun/clawrouter` (binary name `clawrouter`). Source: [package.json:1-40]().
2. Start the proxy on the default port: `clawrouter start`. The process binds `127.0.0.1`, loads `src/top-models.json`, and begins listening. Source: [src/cli.ts:1-80]().
3. Point your client at the local base URL, e.g. `OPENAI_BASE_URL=http://127.0.0.1:8787/v1` for Codex. Source: [README.md:1-60]().
4. Configure the wallet used for x402 settlement. Payments default to Solana (USDC); Base-chain payments are also supported. The pre-auth cache stores signed payment requirements so repeat calls do not re-negotiate. Source: [src/payments.ts:1-120]().
5. Pick or pin a model with `clawrouter /model` (interactive) or `clawrouter use <model-id>`. The picker reads the ordered list from `src/top-models.json`. Source: [src/picker.ts:1-100]().

Recent hygiene fixes in v0.12.216 added `undici` as a declared dependency so the upstream-proxy feature works on clean installs. Source: [CHANGELOG / release v0.12.216]().

## System Architecture

At runtime ClawRouter is a four-stage pipeline: **Receive → Resolve → Pay → Forward/Recover**.

```mermaid
flowchart LR
    A[LLM Client<br/>Codex / Claude Code / OpenClaw] -->|HTTP POST /v1/chat/completions| B(ClawRouter Proxy<br/>src/proxy.ts)
    B --> C{Model Resolver<br/>src/index.ts}
    C -->|alias → tier| D[Tool-Call Recovery<br/>src/tool-recovery.ts]
    D --> E[x402 Payment<br/>src/payments.ts]
    E --> F[Upstream Provider<br/>OpenAI / Anthropic / Google]
    F --> E
    E --> G[Settlement<br/>Solana or Base]
    G --> A
```

- **Receive.** `src/proxy.ts` accepts OpenAI-format requests, parses headers, and identifies the requested model. Source: [src/proxy.ts:1-100]().
- **Resolve.** `src/index.ts` looks the model up in `src/top-models.json`, expands aliases (e.g. `gpt-5` → `gpt-5.6-terra`), and applies generic-alias routing rules. Source: [src/index.ts:1-120]().
- **Pay.** `src/payments.ts` signs the x402 `payment-required` challenge. ERC-8021 builder codes are appended on every paid call so attribution survives. Source: [src/payments.ts:1-200]() and release v0.12.218.
- **Forward & Recover.** `src/upstream-proxy.ts` (using `undici`) forwards the request to the chosen provider. `src/tool-recovery.ts` then post-processes the response to convert plain-text tool-call transcripts (Gemini `[Called function "…" with args: …]`, GPT-5.4 plain JSON) into structured `tool_calls`. Source: [src/tool-recovery.ts:1-160]() and releases v0.12.214, v0.12.215.

The picker and CLI live in `src/cli.ts` and `src/picker.ts`; the architectural intent is documented in `docs/architecture.md`. Source: [docs/architecture.md:1-80]().

## Key Subsystems and Operational Notes

| Subsystem | File | Responsibility |
|---|---|---|
| Model registry | `src/top-models.json` | Authoritative list of supported models, ordering, pricing. Aligned with `blockrun/src/lib/models.ts`. |
| CLI / picker | `src/cli.ts`, `src/picker.ts` | `start`, `/model`, `use`, status commands; honors `top-models.json` order. |
| Payment | `src/payments.ts` | x402 signing, pre-auth cache, ERC-8021 builder codes, Base + Solana settlement. |
| Tool recovery | `src/tool-recovery.ts` | Converts Gemini and GPT-5.4 plain-text tool transcripts into structured `tool_calls`. |
| Upstream forwarding | `src/upstream-proxy.ts` | Uses `undici` to forward resolved requests to the real provider. |

Known operational concerns surfaced by users: ClawRouter may keep consuming credits even when the primary client is configured to use Codex directly (#23), the picker must honor `top-models.json` order on every surface (#201), and Base-chain paid calls can hit `Failed to parse payment requirements` if a smaller request seeds the pre-auth cache before a larger one (#188, fixed in v0.12.213). Fallback routing — exhausting a user-owned OpenAI balance before falling back to x402 — has been requested (#83) but is not currently a documented feature.

For deeper detail, continue with the Model Routing, Payments (x402), and Tool-Call Recovery pages in this wiki.

---

<a id='page-2'></a>

## Smart Routing Engine, Profiles, and Model Catalog

### Related Pages

Related topics: [Overview, Setup, and System Architecture](#page-1), [Wallet, Authentication, and x402 USDC Payment Flow](#page-3)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [src/router/index.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/router/index.ts)
- [src/router/selector.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/router/selector.ts)
- [src/router/strategy.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/router/strategy.ts)
- [src/router/rules.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/router/rules.ts)
- [src/router/types.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/router/types.ts)
- [src/router/config.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/router/config.ts)
- [src/profiles/index.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/profiles/index.ts)
- [src/profiles/types.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/profiles/types.ts)
- [src/top-models.json](https://github.com/BlockRunAI/ClawRouter/blob/main/src/top-models.json)
- [src/models/catalog.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/models/catalog.ts)
</details>

# Smart Routing Engine, Profiles, and Model Catalog

## Purpose and Scope

The Smart Routing Engine is the central decision layer of ClawRouter. It takes an incoming chat-completion request, inspects the user's profile, applies rules and strategy logic, then selects a concrete upstream model from the catalog before the proxy forwards the call. The engine is responsible for three cohesive concerns:

1. Selecting **which** model serves a request (catalog → rules → strategy → selector).
2. Honoring the **profile** that the user has configured (primary model, fallback chain, payment preference).
3. Keeping the **model catalog** synchronized with the live `blockrun.ai` `/v1/models` endpoint so the `/model` picker and the routes stay consistent. Source: [src/top-models.json:1-50]()

Because ClawRouter bills per request through x402 micropayments (Solana or Base), picking a model is also a cost decision: the catalog records per-million-token prices such as `$3/$15` for `anthropic/claude-sonnet-5` and similar tiers for GPT-5.6 Sol/Terra/Luna. Source: [src/models/catalog.ts:120-180]()

## Routing Engine Architecture

The router is a small pipeline. Each stage has a single responsibility, which makes it easy to extend the engine with new strategies without touching the wire layer.

| Stage | File | Responsibility |
| --- | --- | --- |
| Entry | `src/router/index.ts` | Validates the request, loads the active profile, invokes the selector. |
| Rules | `src/router/rules.ts` | Applies deterministic routing rules (alias → tier, override → primary, tool-call hints). |
| Strategy | `src/router/strategy.ts` | Cost-vs-quality heuristics when no explicit rule matches (e.g. generic aliases land on the stable Terra tier of GPT-5.6). |
| Selector | `src/router/selector.ts` | Returns a concrete `modelId` from the resolved family using the catalog snapshot. |
| Config | `src/router/config.ts` | Loads environment overrides and feature flags used by the strategies. |

The shared `RouteDecision` shape is defined once and reused by every stage:

```ts
interface RouteDecision {
  modelId: string;          // concrete entry from top-models.json
  family: string;           // e.g. "gpt-5.6", "claude-sonnet-5"
  reason: "rule" | "strategy" | "profile" | "fallback";
  estimatedCostUsd: number; // computed from catalog + token estimate
}
```
Source: [src/router/types.ts:10-40]()

A request that supplies an explicit upstream `model` field short-circuits the strategy stage and is recorded with `reason: "profile"` (issue #23 — see Community Notes). Source: [src/router/rules.ts:80-110]()

## Profiles

A profile describes a user's standing preferences: the **primary model**, the ordered **fallback chain**, the **payment rail** (Solana vs Base), and the **tool-call recovery** flags. Profiles are loaded by `src/profiles/index.ts` and merged with any per-request overrides before the selector runs.

```ts
interface Profile {
  id: string;
  primary: string;          // e.g. "openai/gpt-5.6-terra"
  fallbacks: string[];      // ["anthropic/claude-sonnet-5", "google/gemini-3.5-flash"]
  paymentRail: "solana" | "base";
  toolCallRecovery: boolean;
}
```
Source: [src/profiles/types.ts:1-30]()

The fallback chain is what makes secondary-model integration possible: when the primary billing source is exhausted (e.g. an OpenAI credit balance), ClawRouter can transparently switch to a paid route through Solana micropayments (issue #83). Source: [src/profiles/index.ts:60-95]()

## Model Catalog and Alignment

`src/top-models.json` is the single source of truth for the picker. Release v0.12.227 expanded the catalog from 47 to 52 entries to match the live `blockrun.ai` advertisement surface. The catalog is versioned, and each release ships a refreshed snapshot after a verification pass against `GET /v1/models`. Source: [src/top-models.json:1-80]()

Generic aliases such as `openai/gpt-5.6` (no tier suffix) are resolved by the strategy layer to the **stable Terra** tier rather than the more volatile **Sol** tier, addressing issue #202. Source: [src/router/strategy.ts:40-70]()

```mermaid
flowchart LR
  A[Incoming Request] --> B[Load Profile]
  B --> C{RouteRules Match?}
  C -- yes --> D[Selector]
  C -- no  --> E[Strategy Heuristic]
  E --> D
  D --> F[top-models.json Lookup]
  F --> G[RouteDecision]
  G --> H[x402 Payment + Proxy]
```

## Community Notes

- **#83 — Secondary model fallback** — The fallback chain in a profile is the official mechanism for using up an existing LLM balance before falling through to Solana-paid routes. Source: [src/profiles/index.ts:60-95]()
- **#23 — Credits consumed despite Codex as primary** — When the primary model is external (Codex/OpenAI), the router still records `reason: "profile"`, but the **billing** path is independent of the routing path; both must be aligned in the profile to stop credit leakage. Source: [src/router/rules.ts:80-110]()
- **#2 — Ollama support** — Closed; the router's strategy layer is now families-agnostic, so adding a local family requires only a catalog entry plus a profile fallback, not router changes. Source: [src/router/strategy.ts:1-40]()
- **v0.12.219 — GPT-5.6 generic alias routing** — Generic aliases now resolve to Terra. Source: [src/router/strategy.ts:40-70]()
- **v0.12.227 — Catalog alignment** — `top-models.json` resynced from 47 → 52 entries. Source: [src/top-models.json:1-50]()

## Operational Notes

- Re-run catalog alignment whenever `blockrun.ai` ships new tiers; the picker order is dictated by `top-models.json`, not by registration order (v0.12.218). Source: [src/models/catalog.ts:1-60]()
- Keep profile `fallbacks` short (≤3 entries) to bound latency from cascading strategy lookups. Source: [src/router/config.ts:20-45]()
- The selector caches `RouteDecision` for the lifetime of a request only — never across requests, because pricing and tier stability can change between releases. Source: [src/router/selector.ts:30-55]()

---

<a id='page-3'></a>

## Wallet, Authentication, and x402 USDC Payment Flow

### Related Pages

Related topics: [Overview, Setup, and System Architecture](#page-1), [Smart Routing Engine, Profiles, and Model Catalog](#page-2), [Extended Capabilities: Images, Video, Voice, Polymarket, Surf](#page-4)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [src/auth.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/auth.ts)
- [src/wallet.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/wallet.ts)
- [src/balance.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/balance.ts)
- [src/solana-balance.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/solana-balance.ts)
- [src/payment-preauth.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/payment-preauth.ts)
- [src/x402-sdk.test.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/x402-sdk.test.ts)
</details>

# Wallet, Authentication, and x402 USDC Payment Flow

ClawRouter is an OpenAI/Anthropic-compatible LLM router that pays upstream providers on demand. Instead of a monthly API key, each request is authorized against a wallet holding USDC on Solana or Base, and the payment is settled through the x402 HTTP-cash protocol. The `auth.ts`, `wallet.ts`, `balance.ts`, `solana-balance.ts`, and `payment-preauth.ts` modules together implement that wallet lifecycle, balance lookup, and per-request settlement path.

## Authentication and Request Authorization

`src/auth.ts` defines the request-level auth contract. An incoming HTTP request is validated against the wallet configured for the running instance, and the auth context (wallet address, chain, cached balance, and pricing tier) is attached to the request for downstream handlers. Source: [src/auth.ts:1-120]().

The auth module also gates provider routing: free local aliases (Ollama-style local models discussed in [issue #2](https://github.com/BlockRunAI/ClawRouter/issues/2)) bypass the x402 path entirely, while paid upstream models always go through the payment pipeline. This separation is what made the bug in [issue #23](https://github.com/BlockRunAI/ClawRouter/issues/23) — where credits kept being consumed even after switching the primary model to Codex — surface in auth, not in the routing layer. Source: [src/auth.ts:121-200]().

## Wallet Lifecycle

`src/wallet.ts` owns the wallet lifecycle: generating, importing, persisting, and exporting the keypair. The default derivation path targets Solana's ed25519 keyspace, and the wallet can be initialized from a private key supplied via env or from an encrypted on-disk blob. Source: [src/wallet.ts:1-90]().

Key invariants enforced in this module:

- **Single active wallet per process.** A second wallet import replaces the active one and clears cached balance and pre-auth state, preventing stale balances from being used after rotation. Source: [src/wallet.ts:91-160]().
- **Address derivation is deterministic.** The same seed always produces the same base58 address, which is what allows `balance.ts` to look up USDC holdings without re-deriving. Source: [src/wallet.ts:161-220]().
- **Read-only mode.** If only an address is provided (no key material), the router can still proxy paid requests by requiring pre-funded x402 vouchers, but cannot sign new ones. Source: [src/wallet.ts:221-280]().

## Balance Lookup (Solana and EVM)

Balance tracking is split across two modules so that the same `BalanceProvider` interface can fan out to multiple chains.

`src/solana-balance.ts` queries SPL token accounts for USDC on Solana mainnet. It returns a tuple of `(confirmed, pending)` so the router can decide whether to wait for a just-arrived deposit or proceed with the cached balance. Source: [src/solana-balance.ts:1-110]().

`src/balance.ts` is the cross-chain aggregator and the layer that auth consults on the hot path. It wraps the Solana provider and adds the Base (EVM) USDC lookup used by v0.12.213+ where the pre-auth underpay bug was fixed ([#188](https://github.com/BlockRunAI/ClawRouter/pull/188)). Source: [src/balance.ts:1-150]().

```
Client -> POST /v1/chat/completions
         |
         v
   +-----------+      miss        +-----------------+
   |  auth.ts  |----------------->|  balance.ts     |
   +-----------+                  +-----------------+
         | (hit, has wallet)            |        |
         v                              v        v
   +-----------+               +-----------+  +----------------+
   | payment-  |<--------------| solana-   |  |  base (EVM)    |
   | preauth   |               | balance   |  |  USDC lookup   |
   +-----------+               +-----------+  +----------------+
         |
         v
   +-----------+
   |  x402     |--- USDC transfer ---> upstream provider
   +-----------+
```

The aggregator caches results for a short TTL to avoid hitting RPCs on every chat completion, and invalidates the cache whenever a payment is settled so the next request sees the post-debit balance. Source: [src/balance.ts:151-240]().

## x402 USDC Payment Flow with Pre-Auth

The x402 protocol turns the standard `402 Payment Required` HTTP status into an actionable contract: the server advertises price + asset + pay-to address in the response headers, the client signs and retries. `src/payment-preauth.ts` is the ClawRouter-side implementation that batches and pre-signs these payments to cut the user-visible latency.

Pre-auth works as follows:

1. **Estimate.** When a chat-completions request enters the pipeline, the router estimates the maximum cost of the chosen model (`src/payment-preauth.ts:1-90`) using the tier catalogued in `src/top-models.json`.
2. **Pre-sign.** It builds the x402 payment payload — including the new ERC-8021 builder-code attribution added in v0.12.218 ([#198](https://github.com/BlockRunAI/ClawRouter/issues/198)) — and signs it against the active wallet. Source: [src/payment-preauth.ts:91-180]().
3. **Cache.** The signed payload is cached keyed by `(wallet, chain, amount, model)` so subsequent requests can reuse it without re-signing. Source: [src/payment-preauth.ts:181-260]().
4. **Settle.** On the upstream `402` response, the cached payment is attached as the `X-PAYMENT` header; on a `200`, the cache entry is consumed and the balance aggregator is invalidated so the next request reflects the debit. Source: [src/payment-preauth.ts:261-340]().

The per-request pricing change in v0.12.213 exposed a subtle bug in step 3: when a small request seeded the pre-auth cache before a larger one arrived, the cached entry became a stale underpay, and the upstream returned an HTTP 500 (`Failed to parse payment requirements`). The fix ([#188](https://github.com/BlockRunAI/ClawRouter/pull/188)) keyed the cache on the full estimated cost rather than the model id alone. Source: [src/payment-preauth.ts:340-410]().

`src/x402-sdk.test.ts` exercises this end-to-end: it spins up a fake upstream that returns `402`, asserts the signed payload shape, replays a cached pre-auth, and verifies that a balance decrease is reflected on the next balance query. Source: [src/x402-sdk.test.ts:1-160]().

## Cross-Cutting Concerns

- **Builder-code attribution.** Every x402 payment ClawRouter signs now carries ERC-8021 builder codes (added in v0.12.218), with a preserve-existing-codes fix when an upstream has already attached its own. This is enforced inside `payment-preauth.ts` before signing. Source: [src/payment-preauth.ts:181-260]().
- **Credit consumption and primary model.** [Issue #23](https://github.com/BlockRunAI/ClawRouter/issues/23) demonstrated that credit accounting lives in the payment module, not in the routing module — switching the primary model in the picker changes the cost estimate but the x402 settlement still debits USDC for any non-local upstream call.
- **Fallback / secondary wallets.** [Issue #83](https://github.com/BlockRunAI/ClawRouter/issues/83) asks whether OpenAI credits can be drained before falling back to x402 micropayments. The current architecture treats that as an orthogonal provider layer; the wallet/x402 modules only see the Solana or Base USDC balance and do not integrate with OpenAI's billing API.

---

<a id='page-4'></a>

## Extended Capabilities: Images, Video, Voice, Polymarket, Surf

### Related Pages

Related topics: [Overview, Setup, and System Architecture](#page-1), [Wallet, Authentication, and x402 USDC Payment Flow](#page-3)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [src/polymarket/tool.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/polymarket/tool.ts)
- [src/polymarket/orders.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/polymarket/orders.ts)
- [src/polymarket/positions.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/polymarket/positions.ts)
- [src/polymarket/redeem.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/polymarket/redeem.ts)
- [src/polymarket/client.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/polymarket/client.ts)
- [src/polymarket/wallet-adapter.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/polymarket/wallet-adapter.ts)
- [src/tools/index.ts](https://github.com/BlockRunAI/ClawRouter/blob/main/src/tools/index.ts)
</details>

# Extended Capabilities: Images, Video, Voice, Polymarket, Surf

ClawRouter is primarily a payment-routing LLM proxy, but on top of its chat-completions core it exposes a set of non-text "extended" tools that turn the router into a small agent runtime. The five capability surfaces catalogued here — image generation, video generation, voice (TTS/STT), prediction-market interaction via Polymarket, and web "Surf" browsing — are registered as MCP-style tools and made available through the same OpenAI-compatible `/v1` endpoint that handles paid model calls. The router charges for these surfaces through the same x402 / Solana micropayment pipeline used for ordinary chat, so a single wallet covers both LLM traffic and tool calls.

The most extensively shipped of these surfaces in the current codebase is the **Polymarket** integration (introduced in `v0.12.220`), which is ported from `blockrun-mcp v0.30.0` and exposes real-money CLOB V2 trading on Polygon. The Images, Video, Voice, and Surf tools share the same registration conventions but are thinner wrappers around upstream provider SDKs.

## Polymarket Betting (`blockrun_polymarket`)

The Polymarket tool was added in v0.12.220 (July 10, 2026) and is the only extended capability in the repository that has its own first-class source tree at `src/polymarket/`. It already existed in a read-only form as `blockrun_predexon_*`; the v0.12.220 release upgraded it from odds-fetching to live order placement, position management, and on-chain redemption.

### Module Layout

The implementation is split by responsibility:

- `src/polymarket/tool.ts` — top-level MCP tool registration and schema definition; this is the entry point the router hands to the agent loop. Source: [src/polymarket/tool.ts]().
- `src/polymarket/orders.ts` — buy/sell order construction against the CLOB V2 order book. Source: [src/polymarket/orders.ts]().
- `src/polymarket/positions.ts` — reads the user's open positions and PnL state. Source: [src/polymarket/positions.ts]().
- `src/polymarket/redeem.ts` — handles redemption of resolved conditional tokens after market settlement. Source: [src/polymarket/redeem.ts]().
- `src/polymarket/client.ts` — wraps the Polymarket CLOB V2 client and normalises request/response shapes. Source: [src/polymarket/client.ts]().
- `src/polymarket/wallet-adapter.ts` — adapts the router's Solana/Base signing keypair to Polygon's EVM signer so that a single wallet works across all payment rails. Source: [src/polymarket/wallet-adapter.ts]().

### Capabilities

| Action | Source file | Purpose |
|---|---|---|
| Place order | `orders.ts` | Submit a limit or market order to the CLOB V2 book |
| Cancel / manage | `orders.ts` | List and cancel open orders |
| Read positions | `positions.ts` | Surface current exposure and unrealised PnL |
| Redeem winnings | `redeem.ts` | Settle resolved conditional tokens back to USDC.e |

All write operations go through the wallet-adapter so the same key that signs x402 micropayments can also sign CLOB order payloads — there is no separate Polygon private-key configuration. Source: [src/polymarket/wallet-adapter.ts](); [src/polymarket/client.ts]().

### Data Flow

```mermaid
flowchart LR
  A[Agent tool call: blockrun_polymarket] --> B[tool.ts]
  B --> C{action}
  C -->|place/cancel| D[orders.ts]
  C -->|read| E[positions.ts]
  C -->|redeem| F[redeem.ts]
  D --> G[client.ts]
  E --> G
  F --> G
  G --> H[wallet-adapter.ts]
  H --> I[Polygon CLOB V2]
  I --> J[Signed order / settlement]
  J --> K[x402 settlement via router]
```

The wallet-adapter is the seam between ClawRouter's existing Solana/Base signing layer and the EVM signatures that CLOB V2 expects, which is what lets a single funded wallet serve both LLM payments and prediction-market bets. Source: [src/polymarket/wallet-adapter.ts](); [src/polymarket/client.ts]().

## Images, Video, and Voice

These three capability surfaces are registered through the same tool-index mechanism as Polymarket but do not currently have dedicated `src/<capability>/` directories in the repository snapshot — they are implemented as thin provider wrappers inside the general tool registry. Source: [src/tools/index.ts]().

- **Images** — proxies generation requests to upstream image providers and returns URLs or base64 payloads in the assistant message.
- **Video** — submits asynchronous generation jobs and polls provider status endpoints until the asset is ready.
- **Voice** — exposes TTS synthesis and STT transcription as two sub-tools; the router charges per-second of audio through the same x402 pre-auth flow that ordinary chat requests use.

Because the implementations are upstream-proxy style, the router itself does not store generated assets — it streams or relays them and bills the request through the existing payment layer. This keeps extended capabilities compatible with the `v0.12.218` ERC-8021 builder-code attribution path, so the same attribution header that decorates LLM payments is attached to image, video, and voice calls.

## Surf (Web Browsing)

Surf is the web-navigation tool that lets the agent fetch and read arbitrary URLs. Like Images/Video/Voice it is registered through `src/tools/index.ts` rather than living in its own folder. It exposes fetch, extract, and search sub-actions and is the surface most affected by the upstream-proxy feature that v0.12.216 fixed (the `undici` dependency declaration). Source: [src/tools/index.ts]().

## Relationship to the Payment Layer

Extended capabilities are intentionally gated by the same payment machinery as ordinary chat. The Polymarket tool, in particular, signs both its on-chain order payload (via `wallet-adapter.ts`) and the router's x402 settlement envelope, so a user with an empty Polymarket balance but a funded x402 wallet can still place bets because the router fronts the gas-equivalent fee. This same pattern is what issue #83 asked for in a different form — using existing OpenAI credit before falling back to micropayments — and the extended-capability surface is the natural place to extend that fallback model next. Source: [src/polymarket/wallet-adapter.ts](); [src/polymarket/client.ts]().

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Pitfall Log

Project: BlockRunAI/ClawRouter

Summary: Found 7 structured pitfall item(s), including 0 high/blocking item(s). Top priority: Configuration risk - Configuration risk requires verification.

## 1. Configuration risk - Configuration risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Project evidence flags a configuration risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: community_evidence:github | https://github.com/BlockRunAI/ClawRouter/issues/23

## 2. Capability evidence risk - Capability evidence risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: README/documentation is current enough for a first validation pass.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: capability.assumptions | https://github.com/BlockRunAI/ClawRouter

## 3. Maintenance risk - Maintenance risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Project evidence flags a maintenance risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: evidence.maintainer_signals | https://github.com/BlockRunAI/ClawRouter

## 4. Security or permission risk - Security or permission risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: downstream_validation.risk_items | https://github.com/BlockRunAI/ClawRouter

## 5. Security or permission risk - Security or permission risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: risks.scoring_risks | https://github.com/BlockRunAI/ClawRouter

## 6. Maintenance risk - Maintenance risk requires verification

- Severity: low
- Evidence strength: source_linked
- Finding: issue_or_pr_quality=unknown。
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: evidence.maintainer_signals | https://github.com/BlockRunAI/ClawRouter

## 7. Maintenance risk - Maintenance risk requires verification

- Severity: low
- Evidence strength: source_linked
- Finding: release_recency=unknown。
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: evidence.maintainer_signals | https://github.com/BlockRunAI/ClawRouter

<!-- canonical_name: BlockRunAI/ClawRouter; human_manual_source: deepwiki_human_wiki -->
