> For the complete documentation index, see [llms.txt](https://docs.greenowl.money/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.greenowl.money/x402-payments/x402/server_express.md).

# server-express

## Overview

The **x402 Payment Protocol Server** is an SOC2-compliant Express.js server that implements the x402 HTTP payment protocol for AI agents and applications to request payments in exchange for resources or services. Built specifically for the Owl Smart Wallet ecosystem, it enables autonomous agents to:

* **Request payments** for API access, data, or services via standard HTTP 402 responses
* **Accept USDC payments** on multiple EVM chains (Sepolia, Base, Arbitrum testnets and mainnets)
* **Issue USDL tokens** as settlement currency for cross-chain transactions
* **Verify payments on-chain** before granting access to protected resources

This server serves as a reference implementation for building x402-compatible payment endpoints that AI agents can interact with autonomously using the Owl Smart Wallet.

***

## Architecture Role

The x402 server fits into the Owl Smart Wallet ecosystem as follows:

```
AI Agent (OpenClaw) 
  ↓
MCP Server (owl-wallet)
  ↓
Owl Smart Wallet (ERC-4337)
  ↓
x402 Client (payment request)
  ↓
x402 Server (this component)
  ↓
Facilitator (payment verification)
  ↓
On-chain Settlement (USDC → USDL)
```

**Key Integration Points:**

* **AI Agent Layer**: Agents use MCP tools to automatically detect 402 responses and initiate payments
* **Smart Wallet Layer**: The Owl Smart Wallet signs and submits payment transactions via session keys
* **Protocol Layer**: x402 client/server negotiate payment terms and verify settlement on-chain
* **Settlement Layer**: USDC payments are converted to USDL tokens for the resource provider

***

## Key Features

### SOC2 Compliance

Enterprise-grade security and auditing for production deployments:

* **Rate Limiting**: 100 requests/minute per IP to prevent DDoS attacks
* **Structured Audit Logging**: JSON logs with correlation IDs for compliance tracking
* **Request Validation**: Input sanitization and 100KB size limits
* **Security Headers**: Helmet.js with HSTS, CSP, and X-Frame-Options
* **Graceful Shutdown**: Clean resource cleanup on process termination
* **Health Monitoring**: Memory and uptime checks with structured responses

### Multi-Chain Support

Accepts payments on six EVM networks:

| Network          | Chain ID | Type    | USDC Contract                                |
| ---------------- | -------- | ------- | -------------------------------------------- |
| Sepolia          | 11155111 | Testnet | `0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238` |
| Base Sepolia     | 84532    | Testnet | Network-specific                             |
| Arbitrum Sepolia | 421614   | Testnet | Network-specific                             |
| Ethereum Mainnet | 1        | Mainnet | Network-specific                             |
| Base Mainnet     | 8453     | Mainnet | Network-specific                             |
| Arbitrum Mainnet | 42161    | Mainnet | Network-specific                             |

Clients automatically select the optimal network based on available funds.

### Payment Flow

1. **Client requests resource** → Server responds with HTTP 402 Payment Required
2. **Client reviews payment terms** → Selects network and asset to pay with
3. **Client submits payment** → Smart wallet transfers USDC on-chain
4. **Server verifies payment** → Facilitator confirms transaction settlement
5. **Server grants access** → Returns requested resource with HTTP 200

***

## Setup

### Prerequisites

* **Node.js v20+** (install via [nvm](https://github.com/nvm-sh/nvm))
* **pnpm v10** (install via [pnpm.io/installation](https://pnpm.io/installation))
* **Facilitator URL** (deployed x402 facilitator service)
* **EVM Address** to receive USDL payments
* **USDC Tokens** on supported networks for testing

### Installation

1. Install dependencies:

```bash
pnpm install
```

2. Copy environment template:

```bash
cp .env.example .env
```

3. Configure environment variables in `.env`:

```bash
# Server Configuration
PORT=3000
NODE_ENV=development

# x402 Protocol
FACILITATOR_URL=https://facilitator.example.com
EVM_ADDRESS=0x742d35Cc6634C0532925a3b844Bc454e4438f44e

# Supported Networks (comma-separated chain IDs)
ENABLED_CHAINS=11155111,84532,421614
```

### Running the Server

**Development Mode** (hot reload):

```bash
pnpm dev
```

**Production Mode**:

```bash
pnpm build
pnpm start
```

On startup, the server performs a health check on the facilitator service and logs the connection status.

***

## API Reference

### GET /buy

Purchase USDL tokens by paying USDC on any supported chain.

**Query Parameters:**

| Parameter | Type   | Required | Description                                                 |
| --------- | ------ | -------- | ----------------------------------------------------------- |
| `amount`  | string | No       | USDC amount in smallest units (default: `1000000` = 1 USDC) |

**Example Request:**

```bash
curl "http://localhost:3000/buy?amount=1000000"
```

**Response: 402 Payment Required** (no prior payment):

```json
{
  "x402Version": 2,
  "error": "Payment required",
  "resource": {
    "url": "http://localhost:3000/buy?amount=1000000",
    "description": "Buy USDL tokens",
    "mimeType": "application/json"
  },
  "accepts": [
    {
      "scheme": "exact",
      "network": "eip155:11155111",
      "amount": "1000000",
      "asset": "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238",
      "payTo": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
      "maxTimeoutSeconds": 300,
      "extra": {
        "name": "USDC",
        "version": "2",
        "chainId": 11155111,
        "verifyingContract": "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"
      }
    }
  ]
}
```

**Response Fields:**

* **x402Version**: Protocol version (always `2`)
* **resource**: Details about the protected resource
* **accepts**: Array of payment options (one per enabled chain)
  * `scheme`: Payment scheme (`exact` = exact amount required)
  * `network`: CAIP-2 chain identifier (`eip155:<chainId>`)
  * `amount`: Payment amount in token's smallest unit (e.g., USDC has 6 decimals)
  * `asset`: ERC-20 token contract address
  * `payTo`: Recipient address for payment
  * `maxTimeoutSeconds`: Payment validity window

**Response: 200 OK** (payment verified):

```json
{
  "success": true,
  "transaction": "0xabcd1234...",
  "network": "eip155:11155111",
  "payer": "0x123...",
  "requirements": {
    "scheme": "exact",
    "network": "eip155:11155111",
    "amount": "1000000",
    "asset": "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238",
    "payTo": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
    "maxTimeoutSeconds": 300,
    "extra": {
      "name": "USDC",
      "version": "2",
      "chainId": 11155111,
      "verifyingContract": "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"
    }
  }
}
```

**AI Agent Integration:**

The OpenClaw agent automatically:

1. Detects the 402 response via MCP tools
2. Selects a payment option matching available wallet funds
3. Uses `owl_executeUserOperation` to transfer USDC
4. Retries the original request with payment proof headers

***

### GET /health

Health check endpoint for monitoring and load balancer probes.

**Example Request:**

```bash
curl http://localhost:3000/health
```

**Response: 200 OK**

```json
{
  "status": "healthy",
  "timestamp": "2025-01-15T12:00:00.000Z",
  "version": "1.0.0",
  "checks": {
    "memory": {
      "healthy": true,
      "status": "ok",
      "usage": 52428800
    }
  },
  "uptime": 3600.5,
  "environment": "production"
}
```

**Response Fields:**

* **status**: Overall health (`healthy` | `unhealthy`)
* **timestamp**: ISO 8601 timestamp of check
* **version**: Server version string
* **checks.memory**: Memory usage health indicator
* **uptime**: Server uptime in seconds
* **environment**: Deployment environment

***

## Configuration

### Environment Variables

| Variable          | Description               | Required | Default                 |
| ----------------- | ------------------------- | -------- | ----------------------- |
| `PORT`            | HTTP server port          | No       | `3000`                  |
| `FACILITATOR_URL` | x402 facilitator endpoint | **Yes**  | -                       |
| `EVM_ADDRESS`     | Payment recipient address | **Yes**  | -                       |
| `ENABLED_CHAINS`  | Comma-separated chain IDs | No       | `11155111,84532,421614` |
| `NODE_ENV`        | Environment mode          | No       | `development`           |

### Enabling Mainnet Networks

By default, only testnets are enabled (`11155111,84532,421614`). To accept mainnet payments:

1. Update `ENABLED_CHAINS` to include mainnet chain IDs:

```bash
ENABLED_CHAINS=11155111,84532,421614,1,8453,42161
```

2. Ensure your facilitator deployment supports the requested mainnets
3. Verify USDC contract addresses in `src/config.ts` for each mainnet
4. Test with small amounts before production deployment

***

## Security Architecture

### Rate Limiting

Protects against abuse and DDoS attacks:

* **Default**: 100 requests per minute per IP address
* **Algorithm**: Token bucket with configurable window
* **Response**: HTTP 429 Too Many Requests when exceeded

### Input Validation

All inputs are sanitized before processing:

* **Amount validation**: Regex pattern matching for numeric strings
* **Request size limits**: 100KB maximum body size
* **Header validation**: Strict x402 header parsing
* **Type checking**: Runtime validation of query parameters

### Audit Logging

Every request is logged with structured JSON:

```json
{
  "requestId": "req-abc123",
  "timestamp": "2025-01-15T12:00:00.000Z",
  "method": "GET",
  "path": "/buy",
  "query": { "amount": "1000000" },
  "ip": "203.0.113.1",
  "userAgent": "x402-client/2.0",
  "statusCode": 402,
  "duration": 45
}
```

**Correlation IDs** allow tracing a request across services for compliance audits.

### Security Headers

Helmet.js provides production-grade HTTP headers:

* **HSTS**: Force HTTPS connections
* **CSP**: Content Security Policy to prevent XSS
* **X-Frame-Options**: Prevent clickjacking
* **X-Content-Type-Options**: Prevent MIME sniffing
* **Referrer-Policy**: Control referrer information leakage

***

## Testing with AI Agents

### Using the OpenClaw Agent

The OpenClaw agent has built-in x402 support via MCP tools:

```typescript
// Agent automatically handles 402 responses
const response = await agent.fetchResource("http://localhost:3000/buy?amount=1000000");

// MCP server detects 402 → initiates payment → retries request
// Result: USDL tokens delivered after payment verification
```

### Manual Testing with x402 Client

```typescript
import { X402Client } from '@openclaw/x402-client';

const client = new X402Client({
  wallet: owlSmartWallet,
  chains: [sepolia, baseSepolia]
});

// Request resource → automatic payment if 402 received
const result = await client.fetch('http://localhost:3000/buy?amount=1000000');

console.log(result); // { success: true, transaction: '0x...' }
```

### Testing Payment Flow

1. **Deploy the server**:

```bash
pnpm dev
```

2. **Request a resource** (triggers 402):

```bash
curl -v "http://localhost:3000/buy?amount=1000000"
```

3. **Review payment options** in the 402 response JSON
4. **Submit payment** using your Smart Wallet (via MCP or directly):

```typescript
// Via MCP tool
await mcp.call_tool("owl_executeUserOperation", {
  to: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238", // USDC
  value: "0",
  data: transferCalldata, // ERC-20 transfer
  chainId: "11155111"
});
```

5. **Retry request** with payment proof headers (automatically added by client)
6. **Receive 200 response** with USDL token confirmation

***

## Production Deployment

### Pre-Deployment Checklist

* [ ] Configure production `FACILITATOR_URL`
* [ ] Set secure `EVM_ADDRESS` with cold wallet backup
* [ ] Enable only required chains in `ENABLED_CHAINS`
* [ ] Set `NODE_ENV=production`
* [ ] Configure reverse proxy (nginx/Caddy) with HTTPS
* [ ] Set up monitoring for `/health` endpoint
* [ ] Configure log aggregation (CloudWatch, Datadog, etc.)
* [ ] Test rate limiting under load
* [ ] Verify USDC contract addresses for each mainnet

### Recommended Architecture

```
Internet
  ↓
Load Balancer (AWS ALB / Cloudflare)
  ↓
API Gateway (rate limiting, DDoS protection)
  ↓
x402 Server (multiple instances)
  ↓
Facilitator Service (payment verification)
  ↓
EVM Networks (on-chain settlement)
```

### Monitoring

Key metrics to track:

* **Request rate**: Requests per second by endpoint
* **Payment success rate**: Percentage of 402 → 200 conversions
* **Response latency**: p50, p95, p99 latencies
* **Error rate**: 4xx and 5xx responses
* **Memory usage**: Heap size and garbage collection
* **Facilitator health**: Upstream availability

***

## Next Steps

* **Deploy a facilitator** for payment verification (see [Facilitator Documentation](https://github.com/greenowl-money/owl-wallet-docs/blob/main/facilitator/README.md))
* **Integrate with AI agents** using the MCP x402 tools
* **Add custom endpoints** with payment requirements for your services
* **Configure mainnet chains** for production token sales
* **Set up monitoring** and alerting for payment success rates
* **Implement webhook notifications** for payment events

***

## Additional Resources

* [x402 Protocol Specification](https://github.com/openclaw/x402)
* [Owl Smart Wallet Documentation](https://github.com/greenowl-money/owl-wallet-docs/blob/main/smart-contracts/README.md)
* [MCP Server Integration Guide](/mcp-servers/mcp-servers.md)
* [OpenClaw Agent Documentation](https://github.com/greenowl-money/owl-wallet-docs/blob/main/agents/openclaw.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.greenowl.money/x402-payments/x402/server_express.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
