Skip to main content
Glama
README.md
# PreFlight402 (`x402-preflight-api`)

Autonomous pre-trade Web3 risk, cross-DEX spread, counterparty screening, and x402 endpoint health API powered by **Cloudflare Workers** and the **x402 HTTP 402 Payment Protocol** on **Base Mainnet (`eip155:8453`, USDC)**.

- **Live production URL:** `https://x402-preflight-api.shellshelltorres.workers.dev` (listed on **x402scan** — 17 OpenAPI routes / 7 paid x402 endpoints)
- **Infrastructure cost:** `$0/month` (Cloudflare Workers Free Tier + zero-API-key upstream providers)
- **Payment model:** Permissionless pay-per-request USDC settled directly to `PAY_TO_ADDRESS`
- **Supported EVM chains:** `base` (8453), `ethereum` (1), `arbitrum` (42161), `polygon` (137), `bsc` (56), `optimism` (10)

---

## Paid Endpoints (Base USDC via x402)

| Method & Path | Price | Parameters | Description |
|---|---|---|---|
| `GET /v1/trade-preflight` | **$0.025** | `address` *(required)*, `chain` *(default: `base`)*, `amountUsd` *(default: `1000`)*, `maxSlippagePct` *(default: `2.0`)* | Single-call execution gate combining token safety, honeypot check, price impact estimate, gas USD fee, oracle deviation, and `GO` / `CAUTION` / `BLOCK` verdict. |
| `GET /v1/token-batch` | **$0.025** | `addresses` *(required, 2–5 CSV 0x addresses)*, `chain` *(default: `base`)* | Screens 2–5 EVM tokens in parallel using GoPlus, DexScreener batch pools, and DefiLlama prices ranked by risk score and liquidity. |
| `GET /v1/token-safety` | **$0.015** | `address` *(required)*, `chain` *(default: `base`)* | Aggregates GoPlus `token_security`, Honeypot.is v2, DexScreener liquidity, and EVM RPC bytecode/EIP-1967 checks into a `SAFE` / `CAUTION` / `DANGER` verdict (`riskScore` 0–100). |
| `GET /v1/dex-spread` | **$0.010** | `address` *(required)*, `chain` *(default: `base`)* | Compares cross-DEX liquidity pools against DefiLlama oracle pricing to return best buy/sell pools, gross spread %, bottleneck liquidity, and `isActionable`. |
| `GET /v1/wallet-profile` | **$0.010** | `address` *(required)*, `chain` *(default: `base`)* | Combines GoPlus `address_security` threat labels with live RPC bytecode size, nonce, and native balance. |
| `GET /v1/gas-oracle` | **$0.005** | `chain` *(default: `all`)* | Live RPC gas prices across all 6 EVM chains with USD fee estimates for ERC-20 transfer, DEX swap, and complex arbitrage + `cheapestChain`. |
| `GET /v1/x402-audit` | **$0.005** | `url` *(required `https://...`)* | SSRF-hardened live audit checking HTTP `402` challenge validity, `payTo` address, network ID, `/.well-known/x402.json` manifest, and latency. |

## Remote MCP Server (Streamable HTTP)

AI agents and MCP clients can connect directly without local installation or API keys (**9 tools**: `2` free + `7` paid):

- **Streamable HTTP endpoint:** `https://x402-preflight-api.shellshelltorres.workers.dev/mcp`
- **Free tools:** `preflight_catalog`, `preflight_sample`
- **Paid tools (`x402` v2 over MCP via `_meta["x402/payment"]` on Base USDC):** `trade_preflight` ($0.025), `token_batch` ($0.025), `token_safety` ($0.015), `dex_spread` ($0.010), `wallet_profile` ($0.010), `gas_oracle` ($0.005), `x402_audit` ($0.005)

```json
{
  "mcpServers": {
    "preflight402": {
      "type": "streamable-http",
      "url": "https://x402-preflight-api.shellshelltorres.workers.dev/mcp"
    }
  }
}
```

## Free Discovery & Sample Routes

- `GET /` — API metadata, pricing, and quickstart links
- `GET /health` — Worker status and wallet configuration check
- `GET /.well-known/x402` — x402scan discovery manifest (`version: 1`)
- `GET /.well-known/x402.json` — x402 v2 static discovery manifest (for x402scan & indexers)
- `GET /.well-known/mcp/server-card.json` — MCP Server Card (SEP-1649/SEP-2127)
- `GET /.well-known/agent-card.json` — A2A Agent Card for autonomous agent discovery
- `POST /mcp` — Stateless Streamable HTTP MCP endpoint (JSON-RPC 2.0 + x402 v2 over MCP)
- `GET /openapi.json` — OpenAPI 3.1.0 specification
- `GET /llms.txt` — Agent-readable documentation & pricing summary
- `GET /v1/sample/{tool}` — Free sample responses (`token-safety`, `dex-spread`, `wallet-profile`, `x402-audit`, `trade-preflight`, `token-batch`, `gas-oracle`)

### Quickstart for AI Agents (`@x402/fetch`)

```ts
import { wrapFetchWithPayment } from "@x402/fetch";

// Wrap fetch with your x402 EVM signer
const res = await fetchWithPay(
  "https://x402-preflight-api.shellshelltorres.workers.dev/v1/token-safety?chain=base&address=0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"
);
const report = await res.json();
console.log(report.verdict, report.riskScore, report.flags);
```

### Local Development & Verification

```bash
npm install
npm run typecheck
npm test
npm run dry-run
```

---

## Guia Rápido pelo Celular (Deploy Sem Programar — $0/mês)

> **Regra de segurança:** Use **apenas o endereço público (`0x...`) da rede Base** da sua carteira fria. **Nunca** digite seed phrase ou chave privada em nenhum painel ou arquivo.

1. **Publicar na Cloudflare (Grátis, direto do navegador do celular):**
   - Crie ou acesse sua conta gratuita em `dash.cloudflare.com` (plano Workers Free não exige cartão para Workers padrão).
   - Vá em **Compute (Workers) → Create → Import a repository** e selecione este repositório GitHub (`x402-preflight-api`).
   - Em **Build command**, deixe em branco (ou `npm install`) e em **Deploy command** deixe `npx wrangler deploy`.
2. **Configurar sua Carteira Fria (`PAY_TO_ADDRESS`):**
   - Após importar, abra o Worker criado → **Settings → Variables and Secrets → Add**.
   - Nome da variável: `PAY_TO_ADDRESS`
   - Valor: seu endereço **público** na rede Base (`0x...`) e salve/redeploy.
   - *(Opcional)* Confira se `X402_NETWORK` está como `eip155:8453` e `FACILITATOR_URL` como `https://facilitator.payai.network`.
3. **Testar no navegador do celular:**
   - Acesse `https://SEU-WORKER.workers.dev/health` → deve mostrar `"walletConfigured": true`.
   - Acesse `https://SEU-WORKER.workers.dev/.well-known/x402.json` → deve listar os 4 serviços pagos.
   - Acesse `https://SEU-WORKER.workers.dev/v1/token-safety?chain=base&address=0x833589fcd6edb6e08f4c7c32d4f71b54bda02913` → deve responder erro HTTP `402` (cobrança ativa!).
4. **Ativar a Indexação no x402 Bazaar / x402scan:**
   - Os catálogos de agentes listam automaticamente uma API após a **primeira chamada paga liquidada com sucesso** (~15 minutos após o pagamento).
   - Faça apenas **1 chamada real** no endpoint mais barato (`/v1/x402-audit`, **$0.005 USDC** = meio centavo de dólar) usando uma carteira/cliente x402 na rede Base.
   - Assim que o facilitador confirmar essa primeira transação na Base, os indexadores leem os metadados Bazaar + `/.well-known/x402.json` e sua API passa a aparecer para agentes autônomos e exploradores.