Skip to main content
Glama
README.md
# SolGate

SolGate is an open-source x402-style HTTP 402 pay-per-call gateway and deterministic spending firewall for autonomous agents. It addresses the challenge of giving agents paid API access without allowing uncontrolled spend: each supported call requires a verifiable Solana Devnet USDC payment, and a server-enforced `$0.05` per-call ceiling blocks oversized requests. The app provides Firecrawl scraping, ElevenLabs text-to-speech, an MCP JSON-RPC interface, and a Supabase-backed audit and metrics console.

> **Devnet demonstration, not a production custody product.** Use a disposable test wallet only. The optional `AGENT_PRIVATE_KEY` is held by the server and signs Devnet transfers when an operator explicitly runs the agent playground. Never fund it with mainnet assets or reuse a production secret. Production deployment also requires authentication for publisher controls, rate limiting, operational monitoring, and review of provider, legal, and payment risks.

## Problem solved

Autonomous agents need pay-per-use access to external APIs, but unrestricted credentials and prepaid accounts can make it difficult to limit each task’s spend. SolGate places a payment challenge, agent budget check, and server-side spending policy between an agent and paid API tools.

## What it does

- Serves Firecrawl scraping and ElevenLabs text-to-speech behind a `$0.01` Devnet USDC payment challenge.
- Exposes those paid tools through both HTTP endpoints and an MCP JSON-RPC endpoint.
- Rejects unknown tools and the `$5.00` attack-test tool before payment verification or signing. The server-enforced per-call ceiling is `$0.05`.
- Verifies confirmed Devnet transactions, checks the exact USDC amount received by the configured merchant, and atomically claims the matching unexpired challenge.
- Records paid calls, policy blocks, failures, latency and payer information in Supabase. A bounded in-memory fallback supports metrics when Supabase logging is unavailable; payment challenges and claims fail closed without durable Supabase storage.
- Refreshes publisher analytics every five seconds.

## Architecture

```mermaid
flowchart LR
  A[Autonomous agent] -->|POST without signature| G[SolGate gateway]
  G -->|403 policy block| A
  G -->|402 x402 invoice| A
  A -->|Devnet USDC transfer; SOL pays fees| S[Solana Devnet]
  A -->|Retry + transaction signature| G
  G --> V[Transaction verification + replay claim]
  V -->|Verified| F[Firecrawl or ElevenLabs]
  F --> G
  G --> D[(Supabase api_logs)]
  D --> M[Publisher metrics dashboard]
```

The gateway evaluates the endpoint allowlist and amount cap before issuing an invoice. The agent runner checks the returned invoice against its per-run budget, then signs only calls within budget. The gateway independently verifies the confirmed transaction before calling the upstream provider.

For the full lifecycle and provider details, see [Architecture](./docs/ARCHITECTURE.md) and [Integrations](./docs/INTEGRATIONS.md).

## Requirements

- Node.js 20.9+ (Node 22 LTS recommended) and pnpm.
- A connected Supabase project (the integration migration creates `public.api_logs`).
- A disposable Solana Devnet agent keypair and a merchant wallet.
- Firecrawl and ElevenLabs API credentials for live provider execution.

## Setup

1. Install dependencies:

   ```sh
   pnpm install
   ```

2. Copy `.env.example` to `.env.local` (or `.env.development.local`) and set:
   - `NEXT_PUBLIC_MERCHANT_WALLET` to the receiving wallet.
   - `AGENT_PRIVATE_KEY` to a **Devnet-only** base58 secret key.
   - `FIRECRAWL_API_KEY` and `ELEVENLABS_API_KEY` to enable paid API calls.
   - Supabase variables are injected by the Vercel Supabase integration. The server uses `SUPABASE_SERVICE_ROLE_KEY` only in server modules; do not publish it.

3. Fund the disposable agent wallet with Devnet SOL for transaction fees and Devnet USDC for payments. SolGate’s USDC-denominated challenges do not accept SOL as payment. The SPL-USDC mint used here is `4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`.

4. Start the app:

   ```sh
   pnpm dev
   ```

5. Open the dashboard, select a provider, and run a request. The attack simulation asks for `$5.00`; it should receive HTTP 403 without signing or spending funds.

`NEXT_PUBLIC_SOLANA_RPC` is optional and defaults to `https://api.devnet.solana.com`; keep it pointed at Solana Devnet because the payment mint and Explorer links are Devnet-specific. The `$0.05` per-call ceiling is enforced in server code and is not configurable through an environment variable.

## API reference

### `POST /api/gateway/:tool`

Accepted tools: `scrape`, `voice`, their aliases `firecrawl` and `elevenlabs`, and the blocked `rogue-drain` test tool. The canonical request JSON uses `{ "input": "..." }`; scraping also accepts `url`, and text-to-speech accepts `text`.

- `scrape`: expects a public HTTP(S) URL and returns the Firecrawl response, Markdown and metadata.
- `voice`: expects text and returns a base64 `data:audio/mpeg` URI when ElevenLabs succeeds, or a `data:audio/wav` URI when the offline fallback is used.
- `rogue-drain`: always rejected by the allowlist and spending firewall.

Without both `x-payment-signature` and `x-payment-nonce`, a valid, configured tool returns HTTP 402 and an `x-payment-required: x402-solana` header. Its JSON invoice contains `amount_usdc`, `recipient`, `mint`, `network`, `nonce`, and `expires_at`. The retry’s confirmed transaction signature is verified against the Devnet RPC, merchant destination, exact amount, and nonce memo. Reused signatures are rejected.

Policy violations return HTTP 403 with `policyLimit` and `requestedAmount`. Missing upstream credentials or merchant configuration return HTTP 503 before accepting payment. Provider failures return HTTP 502 and include the transaction reference so a publisher can reconcile the paid call.

### `POST /api/agent-run`

Request: `{ "tool": "scrape", "input": "https://solana.com", "maxBudgetUsdc": 0.05 }`.

Returns timestamped `trace` steps, `result`, `txSignature`, `explorerUrl`, and `status`. The agent checks its budget before signing and will stop without sending a transaction on a 403, a budget mismatch, a missing wallet, or an unavailable service.

### `GET /api/metrics`

Returns `totalRevenueUsdc`, `totalPaidCalls`, `totalBlockedCalls`, `conversionRate`, `avgLatencyMs`, and up to 15 recent audit log rows. Aggregates are calculated from the most recent 10,000 database rows; use a production rollup for larger histories.

## Database and security

`supabase/schema.sql` documents the `api_logs` structure. The connected Supabase migration was applied with row-level security enabled and all table access revoked from `anon` and `authenticated`; only server-side service-role calls can read or write gateway logs. Keep the service-role key out of client bundles and logs.

The transaction signature column and non-null payment nonce each have unique indexes. After on-chain verification, the server atomically claims a challenge with a conditional update that requires the matching endpoint and nonce, `PAYMENT_REQUIRED` status, no prior signature, and an unexpired challenge. The unique transaction-signature constraint is an additional race guard. Policy decisions use the server-side `$0.05` ceiling, not the browser slider; the slider changes only the agent’s per-run approved budget.

## Development

```sh
pnpm dev       # development server
pnpm lint      # ESLint
pnpm build     # production build and TypeScript validation
```

## License

MIT © 2026 Vishnuraj. See [LICENSE](./LICENSE).