aptos-x402 1.0.0 → 1.0.1

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