npm package: @moltspay/cloudflare-plugin
Description: MoltsPay UPP payment integration for Cloudflare Workers
Author: MoltsPay
Latest version: 0.1.0

# @moltspay/cloudflare-plugin

Accept crypto payments in Cloudflare Workers with UPP (Universal Payment Protocol).

Zero gas fees. Global edge deployment. Sub-millisecond cold starts.

## Features

- 🌍 **Global Edge** - Payments verified at 300+ locations worldwide
- ⚡ **Zero Cold Start** - V8 isolates, not containers
- 💸 **Zero Gas** - Gasless transactions via UPP (Universal Payment Protocol)
- 🔒 **Secure** - No private keys in Workers, verification via API
- 🤖 **Agent-Native** - Built for AI agent commerce

## Installation

```bash
npm install @moltspay/cloudflare-plugin
```

## Quick Start

```typescript
import { moltspay } from '@moltspay/cloudflare-plugin';

const app = moltspay({
  provider: {
    name: 'My Edge Service',
    wallet: '0xYourWalletAddress',
  },
  services: [{
    id: 'my-service',
    price: 0.10,
    currency: 'USDC',
  }],
});

app.service('my-service', async (ctx) => {
  // Payment already verified! ctx.payment contains:
  // - payer: address that paid
  // - amount: amount paid
  // - txHash: transaction hash
  
  const result = await doSomething();
  return Response.json({ result });
});

export default { fetch: app.fetch.bind(app) };
```

## How It Works

```
┌─────────────┐    GET /.well-known/agent-services.json
│   Client    │ ─────────────────────────────────────────►
│  (AI Agent) │    ◄──────── Service catalog + prices
│             │
│             │    POST /my-service (no payment)
│             │ ─────────────────────────────────────────►
│             │    ◄──────── 402 Payment Required
│             │
│             │    ═══════ UPP Payment (off-chain) ═══════
│             │
│             │    POST /my-service + X-Payment header
│             │ ─────────────────────────────────────────►
└─────────────┘    ◄──────── 200 OK + result
                              │
                   ┌──────────▼──────────┐
                   │  Cloudflare Worker  │
                   │  (Your Service)     │
                   │          │          │
                   │    ┌─────▼─────┐    │
                   │    │ MoltsPay  │    │
                   │    │   API     │    │
                   │    │ (verify)  │    │
                   │    └───────────┘    │
                   └─────────────────────┘
```

## API Reference

### `moltspay(config)`

Create a MoltsPay-enabled Worker application.

```typescript
const app = moltspay({
  provider: {
    name: 'Service Name',
    wallet: '0x...',           // Your receiving wallet
    description: 'Optional',
    website: 'https://...',
  },
  services: [{
    id: 'service-id',          // Unique identifier
    name: 'Display Name',      // Optional
    description: 'What it does',
    price: 0.10,               // Price in currency
    currency: 'USDC',          // USDC or USDT
    chain: 'base',             // base, polygon, base_sepolia
    path: '/custom-path',      // Optional, defaults to /{id}
  }],
  apiUrl: 'https://moltspay.com',  // Optional
  testnet: false,                   // Use testnets
});
```

### `app.service(id, handler)`

Register a handler for a service.

```typescript
app.service('my-service', async (ctx, env) => {
  // ctx.payment - Verified payment info
  // ctx.service - Service definition
  // ctx.request - Original Request object
  // env - Worker environment bindings
  
  return new Response('OK');
});
```

### `withPayment(service, handler)`

Simple wrapper for single-service Workers.

```typescript
import { withPayment } from '@moltspay/cloudflare-plugin';

const handler = withPayment(
  {
    id: 'simple',
    price: 0.01,
    wallet: '0x...',
  },
  async (request, payment) => {
    return Response.json({ paid: true });
  }
);

export default { fetch: handler };
```

### Utility Functions

```typescript
import {
  jsonResponse,      // Create JSON response with CORS
  getRequestBody,    // Parse request body
  formatUSDC,        // Format amount for display
  isValidAddress,    // Validate Ethereum address
  truncateAddress,   // 0x1234...5678
  generateRequestId, // UUID for logging
  retry,             // Retry with backoff
} from '@moltspay/cloudflare-plugin';
```

## Service Discovery

Workers automatically serve `/.well-known/agent-services.json`:

```json
{
  "provider": {
    "name": "My Service",
    "wallet": "0x..."
  },
  "services": [{
    "id": "translate",
    "name": "Text Translation",
    "price": 0.01,
    "currency": "USDC",
    "chain": "base",
    "endpoint": "/translate"
  }],
  "UPP": {
    "version": "1.0",
    "accepts": ["USDC"]
  }
}
```

## Examples

See [QUICK_START.md](./QUICK_START.md) for complete, runnable examples including:
- Simple single-service Worker
- Multi-service Worker with routing


## Pricing

Workers + MoltsPay is extremely cost-effective:

| Component | Cost |
|-----------|------|
| Workers (paid plan) | $5/month + $0.50/million requests |
| MoltsPay verification | Free |
| Payment processing | 0% (UPP protocol) |

**Example:** 100,000 requests/month at $0.01 each = $1,000 revenue, ~$5 infra cost.

## Security

- **No private keys** - Workers verify payments via MoltsPay API
- **Gasless** - Coinbase facilitator handles on-chain execution
- **Edge verification** - Low-latency payment checks worldwide
- **CORS enabled** - Safe for browser-based agents

## Support

- Documentation: https://moltspay.com/docs
- Discord: https://discord.gg/moltspay
- GitHub: https://github.com/moltspay/cloudflare

## License

MIT