# x402-batching

**Gas-free micropayments via Circle Gateway.**

This SDK allows you to add **gas-free payments** to your application using the open [x402 protocol](https://x402.org). Payments are signed off-chain and settled in batches by [Circle Gateway](https://developers.circle.com/gateway).

## Integration at a Glance

### 1. Simple Integration (Express)

Monetize any API route with **2 lines of code**:

```typescript
// Seller
const gateway = createGatewayMiddleware({ sellerAddress: '0x...' });
app.get('/premium', gateway.require('$0.01'), (req, res) => res.json({ ... }));
```

Pay for it **without gas**:

```typescript
// Buyer
const client = new GatewayClient({ chain: 'polygon', privateKey }); // or any supported chain
await client.pay('https://api.example.com/premium');
```

### 2. Using standard @x402/core?

If you already use the standard x402 library, just add Gateway support:

```typescript
import { x402ResourceServer } from '@x402/core/server';
import { BatchFacilitatorClient } from '@circle-fin/x402-batching/server';

const server = new x402ResourceServer([
  new BatchFacilitatorClient(),
]);

await server.initialize();
```

---

## Installation

```bash
npm install @circle-fin/x402-batching
```

This will also install the required peer dependencies (`@x402/core`, `viem`). The optional peer dependency `@x402/evm` is only needed if using `CompositeEvmScheme` or `GatewayEvmScheme`.

---

## Quick Start

### Seller Setup

Create an Express server that charges for a route:

```typescript
import express from 'express';
import { createGatewayMiddleware } from '@circle-fin/x402-batching/server';

const app = express();
const gateway = createGatewayMiddleware({ sellerAddress: '0xYOUR_ADDRESS' });

app.get('/premium', gateway.require('$0.01'), (req, res) => {
  res.json({ content: 'Premium content' });
});

app.listen(3000);
```

### Buyer Setup

Pay for a protected resource gas-freely:

```typescript
import { GatewayClient } from '@circle-fin/x402-batching/client';

const client = new GatewayClient({
  chain: 'polygon', // or 'arcTestnet' for testing
  privateKey: '0xYOUR_PRIVATE_KEY',
});

// One-time deposit (funds your Gateway balance)
await client.deposit('1.00');

// Pay for the resource — no gas needed
const response = await client.pay('http://localhost:3000/premium');
console.log(response.data);
```

> **Testing?** Get testnet USDC from the [Circle Faucet](https://faucet.circle.com) and use a testnet chain like `'arcTestnet'`.

#### Lifecycle hooks

`GatewayClient` exposes the standard x402 client [lifecycle hooks](https://docs.x402.org/advanced-concepts/lifecycle-hooks). They fire on the `pay()` buyer path, so you can enforce spending limits, log payments, or recover from failures:

```typescript
client
  .onBeforePaymentCreation(async (ctx) => {
    if (BigInt(ctx.selectedRequirements.amount) > 10_000_000n) {
      return { abort: true, reason: 'Payment exceeds spending limit' };
    }
  })
  .onAfterPaymentCreation(async (ctx) => {
    console.log('Signed payment', ctx.paymentPayload);
  })
  .onPaymentResponse(async (ctx) => {
    // Return `{ recovered: true }` to retry once with a fresh payload.
    console.log('Settlement', ctx.settleResponse);
  });

await client.pay('http://localhost:3000/premium');
```

---

## Supported Networks

Circle Gateway connects multiple blockchains for instant cross-chain liquidity.

- **Mainnet**: Arc, Arbitrum, Avalanche, Base, Ethereum, HyperEVM, Optimism, Polygon, Sei, Sonic, Unichain, World Chain
- **Testnet**: Arbitrum Sepolia, Arc Testnet, Avalanche Fuji, Base Sepolia, Ethereum Sepolia, HyperEVM Testnet, Optimism Sepolia, Polygon Amoy, Sei Atlantic, Sonic Testnet, Unichain Sepolia, World Chain Sepolia

See [Supported Networks](./docs/NETWORKS.md) for full details including chain IDs, USDC addresses, and deposit times.

---

## Learn More

- [x402 Protocol](https://x402.org)
- [Circle Gateway Documentation](https://developers.circle.com/gateway)
- [Circle Faucet](https://faucet.circle.com) (testnet USDC)

