aptos-x402 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,228 +1,261 @@
1
- # aptos-x402
1
+ # Aptos x402
2
2
 
3
- > x402 Payment Protocol SDK for Aptos blockchain
3
+ <div align="center">
4
4
 
5
- HTTP 402 Payment Required for machine-to-machine micropayments on Aptos.
5
+ **HTTP 402 Payment Protocol SDK for Aptos Blockchain**
6
6
 
7
7
  [![npm version](https://img.shields.io/npm/v/aptos-x402.svg)](https://www.npmjs.com/package/aptos-x402)
8
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue.svg)](https://www.typescriptlang.org/)
9
+ [![Next.js](https://img.shields.io/badge/Next.js-15+-black.svg)](https://nextjs.org/)
9
10
 
10
- ## 🎮 Try the Interactive Demo
11
+ [Documentation](https://aptos-x402.vercel.app/docs) [API Reference](#api-reference) [Demo](https://aptos-x402.vercel.app)
11
12
 
12
- See x402 in action with our interactive CLI demo:
13
+ </div>
13
14
 
14
- ```bash
15
- # Clone the repo
16
- git clone https://github.com/adipundir/aptos-x402
17
- cd aptos-x402
15
+ ---
18
16
 
19
- # Install dependencies
20
- npm install
17
+ ## Overview
21
18
 
22
- # Start the server
23
- npm run dev
19
+ **Aptos x402** is a TypeScript SDK implementing the [x402 payment protocol](https://github.com/coinbase/x402) for the Aptos blockchain. Enable your APIs to require cryptocurrency payments before serving responses using the standardized HTTP 402 status code.
24
20
 
25
- # In another terminal, run the demo
26
- npx tsx scripts/test-x402-axios.ts
27
- ```
21
+ Built for **machine-to-machine micropayments**, this SDK provides zero-friction payment integration for Next.js applications with automatic payment handling, cryptographic verification, and **sub-second settlement times** (optimized from 2-3s to 200-500ms).
28
22
 
29
- The demo will:
30
- 1. Ask for your Aptos private key (testnet)
31
- 2. Check your balance
32
- 3. Make a request to a protected API endpoint
33
- 4. **Automatically handle the payment** using x402-axios
34
- 5. Show you the response and transaction details
23
+ > **Performance:** Latest optimizations deliver **5-10x faster** payments with verification caching, async confirmation, and smart deduplication. See [PERFORMANCE_OPTIMIZATIONS.md](./PERFORMANCE_OPTIMIZATIONS.md) for details.
24
+
25
+ <!-- ## Key Features
26
+
27
+ - **Sub-3s Settlement** - Aptos blockchain finality in 1-3 seconds
28
+ - **Cryptographically Secure** - Client-side signing, no key exposure
29
+ - **Axios-Compatible Client** - Drop-in replacement with automatic payment handling
30
+ - 🛡️ **Zero-Config Middleware** - Protect Next.js routes without touching API code
31
+ - 🤖 **AI Agent Ready** - Perfect for autonomous machine-to-machine payments
32
+ - 📦 **TypeScript Native** - Fully typed with comprehensive IntelliSense
33
+ - 🌐 **Production Ready** - Battle-tested with comprehensive error handling
34
+ - 💰 **Free Public Facilitator** - Start building immediately, no infrastructure required -->
35
+
36
+ ## Use Cases
37
+
38
+ | Use Case | Description |
39
+ |----------|-------------|
40
+ | **Pay-per-API-Call** | Monetize APIs without subscriptions or rate limits |
41
+ | **AI Agent Payments** | Enable autonomous agents to pay for resources |
42
+ | **Metered Services** | Charge exactly for what's consumed in real-time |
43
+ | **Micropayments** | Enable sub-cent transactions economically |
44
+ | **Decentralized Access** | Replace API keys with cryptographic payments |
45
+
46
+ ## Quick Start
47
+
48
+ ### Installation
35
49
 
36
- **Don't have testnet APT?** Generate an account and fund it:
37
50
  ```bash
38
- npx tsx scripts/generate-account.ts
39
- npx tsx scripts/fund-account.ts <your-address>
51
+ npm install aptos-x402
40
52
  ```
41
53
 
42
- ## Quick Start (5 Minutes)
54
+ ### Requirements
43
55
 
44
- Add cryptocurrency payments to your Next.js API in just 3 steps:
56
+ - **Next.js:** 15.0.0 or higher
57
+ - **Node.js:** 20.0.0 or higher
58
+ - **TypeScript:** 5.x (recommended)
59
+ - **Aptos SDK:** 1.26.0 or higher (included as peer dependency)
45
60
 
46
- ### Step 1: Install the Package
61
+ ---
62
+
63
+ ## 🤖 AI-Powered Setup (Cursor IDE)
64
+
65
+ Get started in seconds with AI-assisted integration:
47
66
 
48
67
  ```bash
49
- npm install aptos-x402
68
+ mkdir -p .cursor/rules
69
+ curl -o .cursor/rules/aptos-x402.mdc https://raw.githubusercontent.com/adipundir/aptos-x402/main/integration/aptos-x402.mdc
50
70
  ```
51
71
 
52
- ## 🛒 For Buyers (Consuming Paid APIs)
72
+ **Restart Cursor IDE**, then ask:
73
+ > "Set up Aptos x402 in my Next.js app with payment middleware and a test client component"
74
+
75
+ The MDC context file provides Cursor with complete API documentation, types, and examples for accurate code generation.
76
+
77
+ **Learn more:** [Cursor Integration Guide](./docs/guides/cursor-integration.md)
78
+
79
+ ---
80
+
81
+ ## 🛒 Client Integration (Consuming Paid APIs)
53
82
 
54
- Access paid APIs with automatic payment handling using our **axios-compatible** interface:
83
+ Access x402-protected APIs with zero configuration. The `x402axios` client automatically detects payment requirements, builds transactions, and handles the entire payment flow.
84
+
85
+ ### Basic Usage
55
86
 
56
87
  ```typescript
57
88
  import { x402axios } from 'aptos-x402';
58
89
 
59
- // Works exactly like axios - payment handled automatically!
60
90
  const response = await x402axios.get('https://api.example.com/premium/data', {
61
- privateKey: '0x...' // Your Aptos private key
91
+ privateKey: process.env.APTOS_PRIVATE_KEY
62
92
  });
63
93
 
64
- console.log(response.data); // API response data
65
- console.log(response.paymentInfo); // { transactionHash, amount, ... }
66
- ```
94
+ // Access response data
95
+ console.log(response.data);
67
96
 
68
- ### Full Axios Compatibility
97
+ // Verify payment details
98
+ console.log('Transaction:', response.paymentInfo?.transactionHash);
99
+ console.log('Amount:', response.paymentInfo?.amount);
100
+ ```
69
101
 
70
- x402axios supports all standard axios methods and features:
102
+ ### Supported HTTP Methods
71
103
 
72
104
  ```typescript
73
- // GET request
74
- const response = await x402axios.get('https://api.example.com/data', {
75
- privateKey: '0x...',
76
- timeout: 5000,
77
- headers: { 'Authorization': 'Bearer token' }
105
+ // GET with parameters
106
+ await x402axios.get('/data', {
107
+ privateKey: process.env.APTOS_PRIVATE_KEY,
108
+ params: { filter: 'active' }
78
109
  });
79
110
 
80
- // POST request
81
- const response = await x402axios.post('https://api.example.com/analyze',
82
- { text: 'Hello world' },
83
- {
84
- privateKey: '0x...',
85
- headers: { 'Content-Type': 'application/json' }
86
- }
111
+ // POST with body
112
+ await x402axios.post('/analyze',
113
+ { text: 'Content to analyze' },
114
+ { privateKey: process.env.APTOS_PRIVATE_KEY }
87
115
  );
88
116
 
89
- // Create instance with defaults
117
+ // PUT, PATCH, DELETE
118
+ await x402axios.put('/resource/123', data, { privateKey: '0x...' });
119
+ await x402axios.patch('/resource/123', updates, { privateKey: '0x...' });
120
+ await x402axios.delete('/resource/123', { privateKey: '0x...' });
121
+ ```
122
+
123
+ ### Instance Configuration
124
+
125
+ ```typescript
126
+ // Create configured instance
90
127
  const api = x402axios.create({
91
128
  baseURL: 'https://api.example.com',
92
129
  timeout: 10000,
93
- privateKey: '0x...' // Default for all requests
130
+ privateKey: process.env.APTOS_PRIVATE_KEY,
131
+ headers: { 'X-Client-Version': '1.0.0' }
94
132
  });
95
133
 
96
- const response = await api.get('/premium/data');
134
+ // Use instance for all requests
135
+ const weather = await api.get('/premium/weather');
136
+ const stocks = await api.get('/premium/stocks');
97
137
  ```
98
138
 
99
- **What happens automatically:**
100
- 1. Makes initial request to the protected API
101
- 2. Detects 402 Payment Required response
102
- 3. Extracts payment requirements (amount, recipient, network)
103
- 4. Builds and signs Aptos transaction
104
- 5. Retries request with payment
105
- 6. Returns data + payment info
139
+ ### How It Works
140
+
141
+ The client automatically handles the complete payment flow:
142
+
143
+ 1. **Initial Request** - Sends HTTP request to protected endpoint
144
+ 2. **402 Detection** - Identifies payment requirement from response
145
+ 3. **Transaction Building** - Constructs Aptos transfer transaction
146
+ 4. **Client Signing** - Signs transaction locally (keys never leave client)
147
+ 5. **Payment Retry** - Resubmits request with X-PAYMENT header
148
+ 6. **Settlement** - Server verifies and submits to blockchain
149
+ 7. **Response** - Receives data after confirmed payment
150
+
151
+ ---
106
152
 
107
- ## 🏪 For Sellers (Creating Paid APIs)
153
+ ## 🏪 Server Integration (Monetizing Your APIs)
108
154
 
109
- ### Step 2: Create `middleware.ts` in Your Project Root
155
+ Protect Next.js API routes with x402 middleware - zero payment code required in your route handlers.
156
+
157
+ ### Step 1: Configure Environment
158
+
159
+ Create `.env.local` in your project root:
160
+
161
+ ```env
162
+ PAYMENT_RECIPIENT_ADDRESS=0xYOUR_APTOS_WALLET_ADDRESS
163
+ FACILITATOR_URL=https://aptos-x402.vercel.app/api/facilitator
164
+ ```
110
165
 
111
- Create a file called `middleware.ts` in the root of your Next.js project (same level as `app/` or `pages/`):
166
+ > **Getting a Wallet Address:**
167
+ > Install [Petra Wallet](https://petra.app/) or generate programmatically with `@aptos-labs/ts-sdk`
168
+
169
+ ### Step 2: Create Middleware
170
+
171
+ Create `middleware.ts` in your project root (same level as `app/` directory):
112
172
 
113
173
  ```typescript
114
- // middleware.ts
115
174
  import { paymentMiddleware } from 'aptos-x402';
116
175
 
117
176
  export const middleware = paymentMiddleware(
118
177
  process.env.PAYMENT_RECIPIENT_ADDRESS!,
119
178
  {
120
- // Configure which routes require payment
121
179
  '/api/premium/weather': {
122
- price: '1000000', // 0.01 APT (in Octas)
180
+ price: '1000000', // 0.01 APT (1 APT = 100,000,000 Octas)
123
181
  network: 'testnet',
124
- config: { description: 'Premium weather data' },
182
+ config: {
183
+ description: 'Premium weather data access',
184
+ mimeType: 'application/json'
185
+ }
125
186
  },
187
+ '/api/premium/stocks': {
188
+ price: '5000000', // 0.05 APT
189
+ network: 'testnet',
190
+ config: { description: 'Real-time stock data' }
191
+ }
126
192
  },
127
193
  {
128
- // Use public facilitator (perfect for testing)
129
- url: 'https://aptos-x402.vercel.app/api/facilitator'
194
+ url: process.env.FACILITATOR_URL!
130
195
  }
131
196
  );
132
197
 
133
198
  export const config = {
134
- matcher: ['/api/premium/:path*'], // Apply to all /api/premium/* routes
199
+ matcher: ['/api/premium/:path*']
135
200
  };
136
201
  ```
137
202
 
138
- ### Step 3: Set Environment Variable
139
-
140
- Create `.env.local` in your project root:
141
-
142
- ```env
143
- # Your Aptos wallet address (where payments go)
144
- PAYMENT_RECIPIENT_ADDRESS=0xYOUR_WALLET_ADDRESS_HERE
145
- ```
146
-
147
- **How to get your wallet address:**
148
- 1. Install [Petra Wallet](https://petra.app/) or [Martian Wallet](https://martianwallet.xyz/)
149
- 2. Create a new wallet
150
- 3. Copy your address (starts with `0x`)
151
- 4. Paste it in `.env.local`
152
-
153
- **That's it!** Your API routes under `/api/premium/*` now require payment.
203
+ ### Step 3: Create Protected Routes
154
204
 
155
- ### Your API Routes Stay Clean
156
-
157
- **Important:** You don't need to change anything in your API routes! The middleware handles everything.
205
+ Your API routes require **zero payment logic** - the middleware handles everything:
158
206
 
159
207
  ```typescript
160
208
  // app/api/premium/weather/route.ts
161
209
  import { NextResponse } from 'next/server';
162
210
 
163
- export async function GET() {
164
- // This code only runs AFTER payment is verified and settled!
165
- // No payment logic needed here.
211
+ export const dynamic = 'force-dynamic';
212
+
213
+ export async function GET(request: Request) {
214
+ // Execution only reaches here AFTER successful payment settlement
166
215
 
167
216
  return NextResponse.json({
168
217
  location: 'San Francisco',
169
218
  temperature: 72,
170
219
  condition: 'Sunny',
220
+ forecast: '7-day detailed forecast data...'
171
221
  });
172
222
  }
173
223
  ```
174
224
 
175
- The middleware automatically:
176
- - Returns 402 for requests without payment
177
- - Verifies payment signatures
178
- - Settles payments on Aptos blockchain
179
- - Only allows API execution after successful payment
180
- - Adds payment receipt headers to responses
225
+ ### Middleware Behavior
181
226
 
182
- ### Next.js Requirements
227
+ | Scenario | Response |
228
+ |----------|----------|
229
+ | No payment header | **402 Payment Required** with payment instructions |
230
+ | Invalid payment | **403 Forbidden** with error details |
231
+ | Valid payment | **Verifies → Settles → Executes route → 200 OK** |
183
232
 
184
- - **Next.js 15+** with App Router
185
- - TypeScript (recommended)
186
- - Node.js 20+
233
+ ### Price Configuration
187
234
 
188
- ### Complete Project Structure
235
+ Aptos uses **Octas** as the smallest unit (like satoshis or wei):
189
236
 
190
- After setup, your Next.js project should look like this:
237
+ ```typescript
238
+ 1 APT = 100,000,000 Octas
191
239
 
192
- ```
193
- my-nextjs-app/
194
- ├── middleware.ts ← Payment middleware (created in Step 2)
195
- ├── .env.local ← Environment variables (created in Step 3)
196
- ├── app/
197
- │ └── api/
198
- │ └── premium/ ← Protected routes (payment required)
199
- │ └── weather/
200
- │ └── route.ts ← Your API route (no payment code needed!)
201
- ├── package.json
202
- └── next.config.js
240
+ Common prices:
241
+ 0.001 APT = 100,000 Octas
242
+ 0.01 APT = 1,000,000 Octas
243
+ 0.1 APT = 10,000,000 Octas
244
+ 1 APT = 100,000,000 Octas
203
245
  ```
204
246
 
205
- **Key Points:**
206
- - `middleware.ts` must be in the project root (not inside `app/`)
207
- - Applies to all routes matching `/api/premium/*` (configurable)
208
- - Your API routes need **zero** payment code
209
- - Works automatically on every request
247
+ ### Testing Your Integration
210
248
 
211
- ### Testing Your Setup
249
+ Start your development server and verify payment protection:
212
250
 
213
- After setup, test that payment protection is working:
214
-
215
- **1. Start your Next.js dev server:**
216
251
  ```bash
217
252
  npm run dev
218
- ```
219
253
 
220
- **2. Try accessing your protected route without payment:**
221
- ```bash
254
+ # Test without payment (should return 402)
222
255
  curl http://localhost:3000/api/premium/weather
223
256
  ```
224
257
 
225
- **Expected Response (402 Payment Required):**
258
+ Expected 402 response:
226
259
  ```json
227
260
  {
228
261
  "x402Version": 1,
@@ -231,275 +264,213 @@ curl http://localhost:3000/api/premium/weather
231
264
  "network": "aptos-testnet",
232
265
  "maxAmountRequired": "1000000",
233
266
  "payTo": "0xYOUR_WALLET_ADDRESS",
234
- "description": "Premium weather data",
267
+ "description": "Premium weather data access",
235
268
  "resource": "http://localhost:3000/api/premium/weather"
236
269
  }]
237
270
  }
238
271
  ```
239
272
 
240
- If you see this 402 response, your middleware is working perfectly!
241
-
242
- **3. For full payment testing:**
243
- - Use our [live demo](https://aptos-x402.vercel.app) to see the complete flow
244
- - Or implement client-side payment signing (see [Client Integration](#client-integration) below)
245
-
246
- ## What is x402?
247
-
248
- [x402](https://github.com/coinbase/x402) is an open protocol by Coinbase for machine-to-machine micropayments using HTTP 402 status code. This SDK implements x402 for the Aptos blockchain.
249
-
250
- ### Use Cases
273
+ Test with payment using the client:
274
+ ```typescript
275
+ import { x402axios } from 'aptos-x402';
251
276
 
252
- - **Pay-per-API-call** - Monetize your APIs without subscriptions
253
- - **AI Agent Payments** - Let AI agents pay for resources automatically
254
- - **Metered Services** - Charge exactly for what's consumed
255
- - **Decentralized Access Control** - No API keys, just payments
256
- - **Micropayments** - Enable sub-cent transactions economically
277
+ const response = await x402axios.get('http://localhost:3000/api/premium/weather', {
278
+ privateKey: process.env.APTOS_PRIVATE_KEY
279
+ });
280
+ ```
257
281
 
258
- ## Features
282
+ ---
259
283
 
260
- - **Axios-compatible** - Drop-in replacement for axios with x402 payment support
261
- - **Zero payment logic in your code** - Middleware handles everything
262
- - **Aptos native** - Built on Aptos's fast finality (~1-3s)
263
- - **Type-safe** - Full TypeScript support with proper interfaces
264
- - **x402 compliant** - Follows official Coinbase specification
265
- - **Next.js optimized** - Designed for Next.js 15+ (more frameworks coming)
266
- - **Production ready** - Comprehensive error handling and logging
267
- - **Backward compatible** - Old interface still works alongside new axios interface
284
+ ## Architecture
268
285
 
269
- ## How It Works
286
+ ### Protocol Flow
270
287
 
271
288
  ```
272
- ┌─────────┐ ┌─────────┐ ┌────────────┐
273
- Client │ Your │ Aptos
274
- API Blockchain │
275
- └────┬────┘ └────┬────┘ └─────┬──────┘
276
- │ │
277
- 1. GET /api/premium │
278
- │──────────────────────────>│
279
- │ │
280
- 2. 402 Payment Required
281
- │<──────────────────────────│
282
- {accepts: [...]}
283
- │ │
284
- 3. Sign Transaction
285
- (client-side)
286
- │ │
287
- 4. GET /api/premium │
288
- X-PAYMENT: <signed>
289
- │──────────────────────────>│
290
- │ │ 5. Verify (fast)
291
- │──────────────┐
292
- │ │ │ │
293
- │<─────────────┘
294
- │ │
295
- │ │ 6. Settle (submit tx)
296
- │─────────────────────────────>│
297
- │ │
298
- │ │ 7. Confirmed
299
- │<─────────────────────────────│
300
- │ │
301
- 8. 200 OK + Resource
302
- │<──────────────────────────│
303
- X-Payment-Response
289
+ ┌──────────┐ ┌──────────┐ ┌────────────┐ ┌───────────┐
290
+ Client │ API Facilitator│ │ Aptos
291
+ (Buyer) (Seller) │ │ Service │Blockchain │
292
+ └────┬─────┘ └────┬─────┘ └─────┬──────┘ └─────┬─────┘
293
+ │ │
294
+ │ GET /api/premium/data
295
+ │───────────────────────────>│
296
+ │ │
297
+ │ 402 Payment Required
298
+ │<───────────────────────────│
299
+ {scheme, amount, payTo}
300
+ │ │
301
+ [Build & Sign Transaction]
302
+ (Client-side, offline)
303
+ │ │
304
+ │ GET /api/premium/data
305
+ X-PAYMENT: <signed_tx>
306
+ │───────────────────────────>│
307
+ │ │
308
+ │ │ POST /verify │ │
309
+ │─────────────────────────>│
310
+ │ │ {isValid: true} │ │
311
+ │<─────────────────────────│
312
+ │ │
313
+ │ POST /settle │ │
314
+ │─────────────────────────>│
315
+ │ │ │ Submit Transaction
316
+ │ │────────────────────>│
317
+ │ │ Confirmed (1-3s) │
318
+ │<────────────────────│
319
+ │ {success, txHash} │ │
320
+ │<─────────────────────────│
321
+ │ │ │ │
322
+ │ 200 OK + Data │ │ │
323
+ │<───────────────────────────│ │ │
324
+ │ X-PAYMENT-RESPONSE: {...} │ │ │
325
+ │ │ │ │
304
326
  ```
305
327
 
306
- ## Installation & Setup
328
+ ### Components
307
329
 
308
- ### 1. Install Dependencies
330
+ | Component | Responsibility | Location |
331
+ |-----------|----------------|----------|
332
+ | **Client** | Request resources, sign transactions | Your application/agent |
333
+ | **Middleware** | Intercept requests, enforce payment | Your Next.js server |
334
+ | **Facilitator** | Verify & settle payments | Shared service or self-hosted |
335
+ | **Aptos Blockchain** | Final settlement & verification | Decentralized network |
309
336
 
310
- ```bash
311
- npm install aptos-x402 @aptos-labs/ts-sdk next
312
- ```
313
-
314
- ### 2. Environment Variables
337
+ ### Key Design Principles
315
338
 
316
- ```env
317
- # Your wallet address (receives payments)
318
- PAYMENT_RECIPIENT_ADDRESS=0xYOUR_WALLET_ADDRESS_HERE
339
+ - **Client-Side Signing** - Private keys never leave the client
340
+ - **Stateless Protocol** - No sessions, cookies, or stored state
341
+ - **Atomic Operations** - Payment settles or request fails (no partial states)
342
+ - **Transparent** - All transactions verifiable on-chain
343
+ - **HTTP Native** - Uses standard status codes and headers
319
344
 
320
- # Facilitator URL (required)
321
- # Option 1: Use public demo facilitator (easiest for testing)
322
- FACILITATOR_URL=https://aptos-x402.vercel.app/api/facilitator
345
+ ---
323
346
 
324
- # Option 2: Deploy your own for production
325
- # FACILITATOR_URL=https://yourdomain.com/api/facilitator
326
- ```
347
+ ## API Reference
327
348
 
328
- ### 3. Create Middleware
349
+ ### Server-Side API
329
350
 
330
- ```typescript
331
- // middleware.ts
332
- import { paymentMiddleware } from 'aptos-x402';
351
+ #### `paymentMiddleware()`
333
352
 
334
- export const middleware = paymentMiddleware(
335
- process.env.PAYMENT_RECIPIENT_ADDRESS!,
336
- {
337
- // Configure your protected routes
338
- '/api/premium/weather': {
339
- price: '1000000', // 0.01 APT
340
- network: 'testnet',
341
- config: {
342
- description: 'Premium weather data',
343
- mimeType: 'application/json',
344
- },
345
- },
346
- '/api/premium/stocks': {
347
- price: '5000000', // 0.05 APT
348
- network: 'testnet',
349
- config: {
350
- description: 'Real-time stock data',
351
- },
352
- },
353
- },
354
- {
355
- // Facilitator handles blockchain interactions
356
- url: process.env.FACILITATOR_URL!,
357
- }
358
- );
353
+ Creates Next.js middleware for x402 payment enforcement.
359
354
 
360
- export const config = {
361
- matcher: ['/api/premium/:path*'],
362
- };
355
+ **Signature:**
356
+ ```typescript
357
+ function paymentMiddleware(
358
+ recipientAddress: string,
359
+ routes: Record<string, RouteConfig>,
360
+ facilitatorConfig: FacilitatorConfig
361
+ ): NextMiddleware
363
362
  ```
364
363
 
365
- ### 4. Create Your API Route
366
-
367
- ```typescript
368
- // app/api/premium/weather/route.ts
369
- import { NextResponse } from 'next/server';
364
+ **Parameters:**
370
365
 
371
- export const dynamic = 'force-dynamic';
366
+ | Parameter | Type | Description |
367
+ |-----------|------|-------------|
368
+ | `recipientAddress` | `string` | Aptos wallet address to receive payments |
369
+ | `routes` | `Record<string, RouteConfig>` | Map of route paths to payment configs |
370
+ | `facilitatorConfig` | `FacilitatorConfig` | Facilitator service configuration |
372
371
 
373
- export async function GET(request: Request) {
374
- // Payment already verified & settled by middleware!
375
- // Just return your premium data
376
-
377
- return NextResponse.json({
378
- location: 'San Francisco',
379
- temperature: 72,
380
- forecast: '5-day detailed forecast',
381
- premium: true,
382
- });
372
+ **RouteConfig:**
373
+ ```typescript
374
+ interface RouteConfig {
375
+ price: string; // Amount in Octas
376
+ network?: 'testnet' | 'mainnet'; // Default: 'testnet'
377
+ config?: {
378
+ description?: string; // Human-readable description
379
+ mimeType?: string; // Response content type
380
+ outputSchema?: object; // Optional JSON schema
381
+ maxTimeoutSeconds?: number; // Request timeout
382
+ };
383
383
  }
384
384
  ```
385
385
 
386
- ### 5. Set Up Facilitator
387
-
388
- The facilitator handles blockchain interactions. You need to deploy facilitator endpoints:
389
-
386
+ **FacilitatorConfig:**
390
387
  ```typescript
391
- // app/api/facilitator/verify/route.ts
392
- // app/api/facilitator/settle/route.ts
388
+ interface FacilitatorConfig {
389
+ url: string; // Base URL (e.g., 'https://example.com/api/facilitator')
390
+ }
393
391
  ```
394
392
 
395
- See the [full facilitator implementation](https://github.com/adipundir/aptos-x402/tree/main/app/api/facilitator) in the repository.
396
-
397
- ## API Reference
398
-
399
- ### `paymentMiddleware(recipientAddress, routes, facilitatorConfig)`
400
-
401
- Creates x402 payment middleware for Next.js.
402
-
403
- #### Parameters
404
-
405
- - **`recipientAddress`** (string, required): Your Aptos wallet address
406
- - **`routes`** (object, required): Route configuration mapping
407
- - **`path`** (string): API route path
408
- - **`config`** (RouteConfig):
409
- - `price` (string): Payment amount in Octas (1 APT = 100,000,000 Octas)
410
- - `network` (string): `'testnet'` or `'mainnet'`
411
- - `config.description` (string, optional): Resource description
412
- - `config.mimeType` (string, optional): Response MIME type
413
- - `config.maxTimeoutSeconds` (number, optional): Max timeout
414
- - **`facilitatorConfig`** (object, required):
415
- - `url` (string): Facilitator base URL
416
-
417
- #### Returns
393
+ ### Client-Side API
418
394
 
419
- Next.js middleware function
395
+ #### `x402axios`
420
396
 
421
- ## TypeScript Types
397
+ Axios-compatible HTTP client with automatic x402 payment handling.
422
398
 
399
+ **Methods:**
423
400
  ```typescript
424
- import type {
425
- PaymentRequiredResponse,
426
- PaymentRequirements,
427
- PaymentPayload,
428
- RouteConfig,
429
- FacilitatorConfig,
430
- } from 'aptos-x402/types';
401
+ x402axios.get(url, config?)
402
+ x402axios.post(url, data?, config?)
403
+ x402axios.put(url, data?, config?)
404
+ x402axios.patch(url, data?, config?)
405
+ x402axios.delete(url, config?)
406
+ x402axios.request(config)
407
+ x402axios.create(defaultConfig)
431
408
  ```
432
409
 
433
- ### Core Types
434
-
410
+ **Configuration:**
435
411
  ```typescript
436
- interface RouteConfig {
437
- price: string; // Amount in Octas
438
- network?: string; // 'testnet' | 'mainnet'
439
- config?: {
440
- description?: string;
441
- mimeType?: string;
442
- outputSchema?: Record<string, any>;
443
- maxTimeoutSeconds?: number;
444
- };
445
- }
446
-
447
- interface FacilitatorConfig {
448
- url: string; // Required facilitator URL
412
+ interface X402AxiosConfig extends AxiosRequestConfig {
413
+ privateKey?: string; // Aptos private key (hex string)
414
+ account?: Account; // Or Aptos Account object
449
415
  }
416
+ ```
450
417
 
451
- interface PaymentRequiredResponse {
452
- x402Version: number;
453
- accepts: PaymentRequirements[];
454
- error?: string;
418
+ **Response:**
419
+ ```typescript
420
+ interface X402Response<T = any> extends AxiosResponse<T> {
421
+ paymentInfo?: {
422
+ transactionHash: string;
423
+ amount: string;
424
+ recipient: string;
425
+ network: string;
426
+ settled: boolean;
427
+ };
455
428
  }
456
429
  ```
457
430
 
458
- ## Client Integration
459
-
460
- ### Simple Approach: Use x402axios
431
+ ### TypeScript Types
461
432
 
462
- The easiest way to consume protected APIs is with our **axios-compatible** wrapper:
433
+ Import types for full type safety:
463
434
 
464
435
  ```typescript
465
- import { x402axios } from 'aptos-x402';
436
+ import type {
437
+ RouteConfig,
438
+ FacilitatorConfig,
439
+ PaymentRequiredResponse,
440
+ PaymentRequirements,
441
+ PaymentPayload
442
+ } from 'aptos-x402/types';
443
+ ```
466
444
 
467
- // Automatic payment handling - works exactly like axios!
468
- const response = await x402axios.get('https://api.example.com/premium/data', {
469
- privateKey: '0x...' // Your Aptos private key
470
- });
445
+ ---
471
446
 
472
- console.log(response.data); // API response data
473
- console.log(response.paymentInfo); // Payment details
474
- ```
447
+ ## Advanced Usage
475
448
 
476
- ### Advanced: Manual Implementation
449
+ ### Manual Payment Flow
477
450
 
478
- If you need more control, you can implement the payment flow manually:
451
+ For full control over the payment process:
479
452
 
480
453
  ```typescript
481
454
  import { Aptos, AptosConfig, Network, Account, Ed25519PrivateKey } from '@aptos-labs/ts-sdk';
482
455
 
483
- async function callProtectedAPI(url: string, privateKey: string) {
484
- // Step 1: Try without payment
456
+ async function manualPaymentFlow(url: string, privateKey: string) {
457
+ // 1. Request without payment
485
458
  let response = await fetch(url);
486
459
 
487
460
  if (response.status === 402) {
488
- // Step 2: Parse payment requirements
489
461
  const paymentReqs = await response.json();
490
462
  const requirement = paymentReqs.accepts[0];
491
463
 
492
- // Step 3: Initialize Aptos client
464
+ // 2. Initialize Aptos client
493
465
  const config = new AptosConfig({
494
466
  network: requirement.network === 'aptos-testnet' ? Network.TESTNET : Network.MAINNET
495
467
  });
496
468
  const aptos = new Aptos(config);
497
-
498
- // Step 4: Create account and build transaction
499
469
  const account = Account.fromPrivateKey({
500
470
  privateKey: new Ed25519PrivateKey(privateKey)
501
471
  });
502
472
 
473
+ // 3. Build and sign transaction
503
474
  const transaction = await aptos.transaction.build.simple({
504
475
  sender: account.accountAddress,
505
476
  data: {
@@ -508,9 +479,9 @@ async function callProtectedAPI(url: string, privateKey: string) {
508
479
  }
509
480
  });
510
481
 
511
- // Step 5: Sign and create payment header
512
482
  const authenticator = aptos.transaction.sign({ signer: account, transaction });
513
483
 
484
+ // 4. Create payment payload
514
485
  const paymentPayload = {
515
486
  x402Version: 1,
516
487
  scheme: requirement.scheme,
@@ -521,7 +492,7 @@ async function callProtectedAPI(url: string, privateKey: string) {
521
492
  }
522
493
  };
523
494
 
524
- // Step 6: Retry with payment
495
+ // 5. Retry with payment
525
496
  response = await fetch(url, {
526
497
  headers: {
527
498
  'X-PAYMENT': Buffer.from(JSON.stringify(paymentPayload)).toString('base64')
@@ -529,188 +500,211 @@ async function callProtectedAPI(url: string, privateKey: string) {
529
500
  });
530
501
  }
531
502
 
532
- // Step 11: Get the data
533
- const data = await response.json();
534
- console.log('Success!', data);
535
-
536
- // Step 12: Check payment receipt (optional)
537
- const paymentResponse = response.headers.get('x-payment-response');
538
- if (paymentResponse) {
539
- const receipt = JSON.parse(Buffer.from(paymentResponse, 'base64').toString());
540
- console.log('Payment settled:', receipt.settlement.txHash);
541
- }
542
-
543
- return data;
503
+ return await response.json();
544
504
  }
545
-
546
- // Usage
547
- await callProtectedAPI(
548
- 'http://localhost:3000/api/premium/weather',
549
- '0xYOUR_PRIVATE_KEY_HERE'
550
- );
551
505
  ```
552
506
 
553
- ### Quick Test with curl
507
+ ### Wallet Integration
554
508
 
555
- **1. Get payment requirements:**
556
- ```bash
557
- curl http://localhost:3000/api/premium/weather
558
- ```
509
+ For browser applications, integrate with Aptos wallets:
559
510
 
560
- **Response:**
561
- ```json
562
- {
563
- "x402Version": 1,
564
- "accepts": [{
565
- "scheme": "exact",
566
- "network": "aptos-testnet",
567
- "maxAmountRequired": "1000000",
568
- "payTo": "0xYOUR_WALLET_ADDRESS",
569
- "resource": "http://localhost:3000/api/premium/weather"
570
- }]
571
- }
511
+ ```typescript
512
+ // Petra Wallet
513
+ import { useWallet } from '@aptos-labs/wallet-adapter-react';
514
+
515
+ const { signTransaction } = useWallet();
516
+ const signedTx = await signTransaction(transaction);
572
517
  ```
573
518
 
574
- **2. Make payment request:**
519
+ ---
520
+
521
+ ## Examples & Demo
522
+
523
+ ### Interactive Demo
524
+
525
+ Try the complete payment flow: **[aptos-x402.vercel.app](https://aptos-x402.vercel.app)**
526
+
527
+ ### Example Code
528
+
529
+ | Example | Description | Path |
530
+ |---------|-------------|------|
531
+ | **Simple Seller** | Basic middleware setup | [`examples/simple-seller/`](./examples/simple-seller/) |
532
+ | **Facilitator** | Self-hosted facilitator guide | [`examples/facilitator/`](./examples/facilitator/) |
533
+ | **Full Demo** | Complete implementation | [`app/`](./app/) |
534
+
535
+ ### CLI Demo
536
+
575
537
  ```bash
576
- curl http://localhost:3000/api/premium/weather \
577
- -H "X-PAYMENT: eyJ4NDAyVmVyc2lvbiI6MSwic2NoZW1lIjoi..."
538
+ git clone https://github.com/adipundir/aptos-x402
539
+ cd aptos-x402
540
+ npm install
541
+ npm run dev # In one terminal
542
+
543
+ # In another terminal
544
+ npx tsx scripts/test-x402-axios.ts
578
545
  ```
579
546
 
580
- ### Browser Integration
547
+ ## Facilitator
581
548
 
582
- For browser applications, you can use wallet integrations:
549
+ The facilitator handles blockchain operations (verification and settlement) separately from your API server.
583
550
 
584
- ```typescript
585
- // Using Petra Wallet
586
- const { signTransaction } = usePetraWallet();
587
- const signedTx = await signTransaction(transaction);
588
- ```
551
+ ### Options
589
552
 
590
- ### AI Agent Integration
553
+ | Option | Best For | Setup |
554
+ |--------|----------|-------|
555
+ | **Public Facilitator** | Development, testing, POCs | `FACILITATOR_URL=https://aptos-x402.vercel.app/api/facilitator` |
556
+ | **Self-Hosted (Same App)** | Small to medium deployments | Copy facilitator routes to your Next.js app |
557
+ | **Self-Hosted (Separate)** | Production, high scale | Deploy as standalone service |
591
558
 
592
- ```typescript
593
- import { x402axios } from 'aptos-x402';
559
+ ### Why Separate?
594
560
 
595
- // Agent automatically handles payments
596
- const response = await x402axios.get('https://api.example.com/premium/data', {
597
- privateKey: process.env.AGENT_KEY!
598
- });
561
+ - **Security** - Isolate blockchain operations
562
+ - **Scalability** - Share across multiple APIs
563
+ - **Flexibility** - Upgrade independently
599
564
 
600
- const data = response.data;
601
- ```
565
+ See [Facilitator Setup Guide](./docs/guides/facilitator-setup.md) for detailed deployment instructions.
602
566
 
603
- ## Examples
567
+ ## FAQ
604
568
 
605
- ### Example Projects in This Repo
569
+ <details>
570
+ <summary><strong>Why use x402 instead of API keys?</strong></summary>
606
571
 
607
- - **[examples/simple-seller/](./examples/simple-seller/)** - Basic middleware configuration
608
- - **[examples/facilitator/](./examples/facilitator/)** - Facilitator setup guide
609
- - **[app/](./app/)** - Complete working demo with frontend
572
+ - No secrets to manage, rotate, or leak
573
+ - True pay-per-use with no subscriptions
574
+ - Decentralized with no auth server
575
+ - Instant monetization without payment processors
610
576
 
611
- ### Live Demo
577
+ </details>
612
578
 
613
- Visit **https://aptos-x402.vercel.app** to see the complete payment flow in action:
614
- - Try requesting without payment (gets 402)
615
- - Sign transaction with demo account
616
- - See payment verification and settlement
617
- - View transaction on Aptos Explorer
579
+ <details>
580
+ <summary><strong>How fast are payments?</strong></summary>
618
581
 
619
- ## Facilitator Setup
582
+ | Operation | Time |
583
+ |-----------|------|
584
+ | Verification | < 50ms |
585
+ | Settlement | 1-3 seconds |
586
+ | **Total** | **~1-3 seconds** |
620
587
 
621
- The facilitator is a critical component that handles blockchain interactions (verify and settle operations).
588
+ </details>
622
589
 
623
- ### Why Separate Facilitator?
590
+ <details>
591
+ <summary><strong>What are the costs?</strong></summary>
624
592
 
625
- - **Security**: Keeps blockchain keys separate from app servers
626
- - **Scalability**: Can be shared across multiple services
627
- - **x402 Compliance**: Follows the official protocol architecture
593
+ | Party | Cost |
594
+ |-------|------|
595
+ | **Client** | Gas (~$0.0001) + API price |
596
+ | **Server** | Facilitator hosting only |
597
+ | **Protocol** | Free, open source |
628
598
 
629
- ### Options
599
+ </details>
630
600
 
631
- #### 1. Use Public Demo Facilitator (Easiest)
601
+ <details>
602
+ <summary><strong>Is this production-ready?</strong></summary>
632
603
 
633
- ```env
634
- FACILITATOR_URL=https://aptos-x402.vercel.app/api/facilitator
635
- ```
604
+ Yes, with proper testing:
605
+ - Start on testnet for development
606
+ - Thorough testing before mainnet
607
+ - Monitor facilitator health
608
+ - Implement error handling
636
609
 
637
- Perfect for:
638
- - Development and testing
639
- - Proof of concepts
640
- - Learning x402 protocol
610
+ </details>
641
611
 
642
- **Note**: For production, deploy your own for better control and reliability.
612
+ <details>
613
+ <summary><strong>Can I use other blockchains?</strong></summary>
643
614
 
644
- #### 2. Deploy Your Own (Production)
615
+ This SDK is Aptos-specific. x402 protocol supports any blockchain. Other implementations coming soon.
645
616
 
646
- Copy the facilitator implementation from the repository:
647
- - `app/api/facilitator/verify/route.ts`
648
- - `app/api/facilitator/settle/route.ts`
617
+ </details>
649
618
 
650
- Deploy to:
651
- - Same Next.js app (simplest)
652
- - Separate microservice (recommended for scale)
653
- - Serverless functions (Vercel, AWS Lambda, etc.)
619
+ <details>
620
+ <summary><strong>Do I need a blockchain wallet?</strong></summary>
654
621
 
655
- See [Facilitator Guide](https://github.com/adipundir/aptos-x402/blob/main/examples/facilitator) for full setup instructions.
622
+ **Sellers:** Need wallet address to receive payments (no private key on server)
623
+ **Buyers:** Need funded wallet to make payments
656
624
 
657
- ## FAQ
625
+ Generate testnet wallets: `npx tsx scripts/generate-account.ts`
626
+
627
+ </details>
628
+
629
+ <details>
630
+ <summary><strong>How do AI agents use this?</strong></summary>
631
+
632
+ Agents can autonomously make payments:
633
+ ```typescript
634
+ const agent = createAgent({ privateKey: process.env.AGENT_KEY });
635
+ const data = await x402axios.get(apiUrl, { privateKey: agent.key });
636
+ ```
658
637
 
659
- ### Why not just use API keys?
638
+ No human intervention required.
660
639
 
661
- - **No key management** - No secrets to rotate or leak
662
- - **Pay-per-use** - No subscriptions or upfront costs
663
- - **Decentralized** - No central auth server
664
- - **Monetization built-in** - Get paid automatically
640
+ </details>
665
641
 
666
- ### How fast are payments?
642
+ ---
667
643
 
668
- - **Verification**: < 50ms (cryptographic validation only)
669
- - **Settlement**: 1-3 seconds (Aptos blockchain finality)
670
- - **Total**: ~1-3 seconds for full payment confirmation
644
+ ## Performance Monitoring
671
645
 
672
- ### What are the costs?
646
+ Track payment performance with built-in timing headers:
673
647
 
674
- - **Client pays**: Transaction gas (~0.0001 APT) + your API price
675
- - **Server pays**: Nothing! Just host the facilitator
676
- - **Protocol fees**: None, x402 is free and open source
648
+ ```typescript
649
+ const response = await x402axios.get(url, { privateKey });
677
650
 
678
- ### Can I use this with other blockchains?
651
+ // Check performance metrics
652
+ const verifyTime = response.headers['x-verification-time'];
653
+ const settleTime = response.headers['x-settlement-time'];
654
+ const cached = response.headers['x-cached'] === 'true';
679
655
 
680
- This package is Aptos-specific. For other chains:
681
- - Ethereum: `@x402/ethereum` (coming soon)
682
- - Solana: `@x402/solana` (coming soon)
683
- - Sui: `@x402/sui` (coming soon)
656
+ console.log(`Verification: ${verifyTime}ms`);
657
+ console.log(`Settlement: ${settleTime}ms`);
658
+ console.log(`Cached: ${cached}`);
659
+ ```
684
660
 
685
- ### Is this production-ready?
661
+ ### Performance Benchmarks
686
662
 
687
- Yes! The protocol is designed for production use. However:
688
- - ⚠️ Start with testnet for development
689
- - ⚠️ Test thoroughly before mainnet deployment
690
- - ⚠️ Monitor facilitator health and security
663
+ Run the included benchmark to measure your setup:
691
664
 
692
- ## Contributing
665
+ ```bash
666
+ APTOS_PRIVATE_KEY=0x... npx tsx scripts/benchmark-payment-flow.ts
667
+ ```
693
668
 
694
- Contributions welcome! Feel free to open issues or submit pull requests.
669
+ **Expected Performance:**
670
+ - First request (uncached): ~800-1000ms
671
+ - Cached requests: ~650-800ms
672
+ - Settlement alone: ~200-300ms
673
+ - Legacy (pre-optimization): ~2000-3000ms
695
674
 
696
- ## License
675
+ **Optimization Details:** See [PERFORMANCE_OPTIMIZATIONS.md](./PERFORMANCE_OPTIMIZATIONS.md) for complete breakdown of the **5-10x performance improvements**.
697
676
 
698
- MIT © Aditya Pundir
677
+ ---
678
+
679
+ ## Resources
699
680
 
700
- ## Links
681
+ ### Documentation
682
+ - [Full Documentation](https://aptos-x402.vercel.app/docs)
683
+ - [API Reference](./docs/api-reference/server-api.md)
684
+ - [Protocol Specification](https://github.com/coinbase/x402)
685
+ - [Performance Guide](./PERFORMANCE_OPTIMIZATIONS.md)
701
686
 
687
+ ### Links
702
688
  - [GitHub Repository](https://github.com/adipundir/aptos-x402)
703
689
  - [NPM Package](https://www.npmjs.com/package/aptos-x402)
704
- - [x402 Protocol Spec](https://github.com/coinbase/x402)
705
690
  - [Aptos Developer Docs](https://aptos.dev)
706
691
 
707
- ## Support
692
+ ### Support
693
+ - [Report Issues](https://github.com/adipundir/aptos-x402/issues)
694
+ - [Discussions](https://github.com/adipundir/aptos-x402/discussions)
695
+ - [Twitter: @aptos-x402](https://x.com/aptosx402)
696
+
697
+ ## Contributing
708
698
 
709
- - 🐛 [Report Issues](https://github.com/adipundir/aptos-x402/issues)
710
- - 💬 [Discussions](https://github.com/adipundir/aptos-x402/discussions)
711
- - 🐦 Twitter: [@adipundir](https://x.com/adipundir)
699
+ Contributions are welcome! Please feel free to submit issues, feature requests, or pull requests.
712
700
 
713
701
  ---
714
702
 
715
- Built with ❤️ for the Aptos ecosystem
703
+ <div align="center">
704
+
705
+ **Built for the Aptos Ecosystem**
706
+
707
+ [Documentation](https://aptos-x402.vercel.app) • [GitHub](https://github.com/adipundir/aptos-x402) • [NPM](https://www.npmjs.com/package/aptos-x402)
708
+
709
+ </div>
716
710