{"_id":"@adipundir/aptos-x402","_rev":"7-74535abf10d8b8a4867df4572f0735b6","name":"@adipundir/aptos-x402","dist-tags":{"latest":"0.2.0"},"versions":{"0.1.0":{"name":"@adipundir/aptos-x402","version":"0.1.0","keywords":["x402","aptos","payment","micropayment","http-402","blockchain","cryptocurrency"],"author":{"name":"Adi Pundir"},"license":"MIT","_id":"@adipundir/aptos-x402@0.1.0","maintainers":[{"name":"adipundir","email":"pundir.aditya@outlook.com"}],"homepage":"https://aptos-x402.vercel.app","bugs":{"url":"https://github.com/adipundir/aptos-x402/issues"},"dist":{"shasum":"01d3b35a9fe243457bdd15312076ebcdd1c439d1","tarball":"https://registry.npmjs.org/@adipundir/aptos-x402/-/aptos-x402-0.1.0.tgz","fileCount":27,"integrity":"sha512-WqBONGfYu+1CyU8HNtskqd2X3Qmi2RAqs/6wSiwRaMeCZD3Oy+yeKYG/UTHgDj4cxntYJ4lP4fi+xyhiavQuiw==","signatures":[{"sig":"MEQCIAfYfSUlwn1nfFMbgqLfDWvTKck5a7YYELzuiLUP+HP6AiBNYBRSIJDUUmOpe5bjdvhwRs/vKh+lispa8yqkdrRQow==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":45587},"main":"dist/index.js","types":"dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","default":"./dist/index.js"},"./types":{"types":"./dist/types/index.d.ts","default":"./dist/types/index.js"},"./server":{"types":"./dist/server/index.d.ts","default":"./dist/server/index.js"}},"gitHead":"241aeb8f3992965102fc9f6b0037fed7275a7550","scripts":{"dev":"next dev --turbopack","demo":"tsx scripts/demo-agent.ts","test":"echo \"Tests coming soon\" && exit 0","build":"npm run build:sdk && npm run build:demo","start":"next start","build:sdk":"tsc -p tsconfig.sdk.json","build:demo":"next build --turbopack","prepublishOnly":"npm run build:sdk"},"_npmUser":{"name":"adipundir","email":"pundir.aditya@outlook.com"},"repository":{"url":"git+https://github.com/adipundir/aptos-x402.git","type":"git"},"_npmVersion":"10.9.3","description":"Official x402 Payment Protocol SDK for Aptos blockchain","directories":{},"_nodeVersion":"22.19.0","dependencies":{"zod":"^3.23.8","next":"15.5.4","react":"19.1.0","langchain":"^0.3.0","react-dom":"19.1.0","@langchain/core":"^0.3.0","@aptos-labs/ts-sdk":"^1.26.0","@langchain/google-genai":"^0.1.0"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.7.1","typescript":"^5","@types/node":"^20","tailwindcss":"^4","@types/react":"^19","@types/react-dom":"^19","@tailwindcss/postcss":"^4"},"peerDependencies":{"next":">=15.0.0","@aptos-labs/ts-sdk":">=1.26.0"},"_npmOperationalInternal":{"tmp":"tmp/aptos-x402_0.1.0_1759508371080_0.5056058756844573","host":"s3://npm-registry-packages-npm-production"},"deprecated":"Package no longer supported. Contact Support at https://www.npmjs.com/support for more info."},"0.1.1":{"name":"@adipundir/aptos-x402","version":"0.1.1","keywords":["x402","aptos","payment","micropayment","http-402","blockchain","cryptocurrency"],"author":{"name":"Adi Pundir"},"license":"MIT","_id":"@adipundir/aptos-x402@0.1.1","maintainers":[{"name":"adipundir","email":"pundir.aditya@outlook.com"}],"homepage":"https://aptos-x402.vercel.app","bugs":{"url":"https://github.com/adipundir/aptos-x402/issues"},"dist":{"shasum":"f01e2e60085e46d538849660220f86c1411ff832","tarball":"https://registry.npmjs.org/@adipundir/aptos-x402/-/aptos-x402-0.1.1.tgz","fileCount":27,"integrity":"sha512-4q2Qt5YJnJxrc3kF6u8vZgKkYCUqxwVEdpGBr40rZpG9VlaxoJZGqZAmR4Ql3oLzSCjznaljOn/P5rKaZJIBIA==","signatures":[{"sig":"MEYCIQC69Pib5ee3w2vx2VUYEWBeZgGTnSVZ9TfjjFOU6X9wyAIhAIHnp0k9b0iHRgG3I6XDjtYTFmVMRstkOzZzsbh5eWwX","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":48922},"main":"dist/index.js","types":"dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","default":"./dist/index.js"},"./types":{"types":"./dist/types/index.d.ts","default":"./dist/types/index.js"},"./server":{"types":"./dist/server/index.d.ts","default":"./dist/server/index.js"}},"gitHead":"241aeb8f3992965102fc9f6b0037fed7275a7550","scripts":{"dev":"next dev --turbopack","demo":"tsx scripts/demo-agent.ts","test":"echo \"Tests coming soon\" && exit 0","build":"npm run build:sdk && npm run build:demo","start":"next start","build:sdk":"tsc -p tsconfig.sdk.json","build:demo":"next build --turbopack","prepublishOnly":"npm run build:sdk"},"_npmUser":{"name":"adipundir","email":"pundir.aditya@outlook.com"},"repository":{"url":"git+https://github.com/adipundir/aptos-x402.git","type":"git"},"_npmVersion":"10.9.3","description":"Official x402 Payment Protocol SDK for Aptos blockchain","directories":{},"_nodeVersion":"22.19.0","dependencies":{"zod":"^3.23.8","next":"15.5.4","react":"19.1.0","langchain":"^0.3.0","react-dom":"19.1.0","@langchain/core":"^0.3.0","@aptos-labs/ts-sdk":"^1.26.0","@langchain/google-genai":"^0.1.0"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.7.1","typescript":"^5","@types/node":"^20","tailwindcss":"^4","@types/react":"^19","@types/react-dom":"^19","@tailwindcss/postcss":"^4"},"peerDependencies":{"next":">=15.0.0","@aptos-labs/ts-sdk":">=1.26.0"},"_npmOperationalInternal":{"tmp":"tmp/aptos-x402_0.1.1_1759509661451_0.4762859639075636","host":"s3://npm-registry-packages-npm-production"},"deprecated":"Package no longer supported. Contact Support at https://www.npmjs.com/support for more info."},"0.1.2":{"name":"@adipundir/aptos-x402","version":"0.1.2","keywords":["x402","aptos","payment","micropayment","http-402","blockchain","cryptocurrency"],"author":{"name":"Adi Pundir"},"license":"MIT","_id":"@adipundir/aptos-x402@0.1.2","maintainers":[{"name":"adipundir","email":"pundir.aditya@outlook.com"}],"homepage":"https://aptos-x402.vercel.app","bugs":{"url":"https://github.com/adipundir/aptos-x402/issues"},"dist":{"shasum":"8bdf57ff1da0345f4d1076171db774af1bb5e77d","tarball":"https://registry.npmjs.org/@adipundir/aptos-x402/-/aptos-x402-0.1.2.tgz","fileCount":27,"integrity":"sha512-Xc7yP9fCYqPyO2YbbhDw2xLab5zk5YpGcBRlLk0UJxiP9wDROPDqp9G8Lg09UF3SkSYpk02fx7ZlOwlHSqJO9g==","signatures":[{"sig":"MEUCIQC/4W+WVHeLGMvi4ZbRrzwuOM8xE6xzyIVUsz26ApIt/QIgQfq/zy0URO8Cs0RBcyoHjq/lkWCh9XFRRP+CLZ9F8zs=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":53453},"main":"dist/index.js","types":"dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","default":"./dist/index.js"},"./types":{"types":"./dist/types/index.d.ts","default":"./dist/types/index.js"},"./server":{"types":"./dist/server/index.d.ts","default":"./dist/server/index.js"}},"gitHead":"586f76ce127ce758b14aae9cc82e070e8b01e33c","scripts":{"dev":"next dev --turbopack","demo":"tsx scripts/demo-agent.ts","test":"echo \"Tests coming soon\" && exit 0","build":"npm run build:sdk && npm run build:demo","start":"next start","build:sdk":"tsc -p tsconfig.sdk.json","build:demo":"next build --turbopack","prepublishOnly":"npm run build:sdk"},"_npmUser":{"name":"adipundir","email":"pundir.aditya@outlook.com"},"repository":{"url":"git+https://github.com/adipundir/aptos-x402.git","type":"git"},"_npmVersion":"10.9.3","description":"Official x402 Payment Protocol SDK for Aptos blockchain","directories":{},"_nodeVersion":"22.19.0","dependencies":{"zod":"^3.23.8","next":"15.5.4","react":"19.1.0","langchain":"^0.3.0","react-dom":"19.1.0","@langchain/core":"^0.3.0","@aptos-labs/ts-sdk":"^1.26.0","@langchain/google-genai":"^0.1.0"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.7.1","typescript":"^5","@types/node":"^20","tailwindcss":"^4","@types/react":"^19","@types/react-dom":"^19","@tailwindcss/postcss":"^4"},"peerDependencies":{"next":">=15.0.0","@aptos-labs/ts-sdk":">=1.26.0"},"_npmOperationalInternal":{"tmp":"tmp/aptos-x402_0.1.2_1759517225671_0.13181306900083123","host":"s3://npm-registry-packages-npm-production"},"deprecated":"Package no longer supported. Contact Support at https://www.npmjs.com/support for more info."},"0.1.3":{"name":"@adipundir/aptos-x402","version":"0.1.3","keywords":["x402","aptos","payment","micropayment","http-402","blockchain","cryptocurrency"],"author":{"name":"Adi Pundir"},"license":"MIT","_id":"@adipundir/aptos-x402@0.1.3","maintainers":[{"name":"adipundir","email":"pundir.aditya@outlook.com"}],"homepage":"https://aptos-x402.vercel.app","bugs":{"url":"https://github.com/adipundir/aptos-x402/issues"},"dist":{"shasum":"8bd439976e4ab112499d02c3163fef4a5a92dd3a","tarball":"https://registry.npmjs.org/@adipundir/aptos-x402/-/aptos-x402-0.1.3.tgz","fileCount":63,"integrity":"sha512-b/Q/cRvxsgaSOnyW0gK1heGLHW9x7lqa5d68bVs7lavwFlomPyoUehr+liH5fPs1s/PjpqyeqWjBYicfz25Suw==","signatures":[{"sig":"MEYCIQCFeB0ywgCIfnB7z8/TNzFFmeOzchmYWiHqBnw66IcljwIhALgPWnXoFZIXlZT1TgzCjs1kZiRwk5YExKQGpxKmLk0G","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":165180},"main":"dist/index.js","types":"dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","default":"./dist/index.js"},"./types":{"types":"./dist/types/index.d.ts","default":"./dist/types/index.js"},"./server":{"types":"./dist/server/index.d.ts","default":"./dist/server/index.js"}},"gitHead":"bd11c1103d03bc959fbdab7579833faf58d0bc5f","scripts":{"dev":"next dev --turbopack","demo":"tsx scripts/demo-agent.ts","test":"echo \"Tests coming soon\" && exit 0","build":"npm run build:sdk && npm run build:demo","start":"next start","build:sdk":"tsc -p tsconfig.sdk.json","build:demo":"next build --turbopack","prepublishOnly":"npm run build:sdk"},"_npmUser":{"name":"adipundir","email":"pundir.aditya@outlook.com"},"repository":{"url":"git+https://github.com/adipundir/aptos-x402.git","type":"git"},"_npmVersion":"10.9.3","description":"Official x402 Payment Protocol SDK for Aptos blockchain","directories":{},"_nodeVersion":"22.19.0","dependencies":{"zod":"^3.23.8","next":">=15.0.0","axios":"^1.12.2","react":"19.1.0","langchain":"^0.3.0","react-dom":"19.1.0","x402-axios":"^0.6.6","lucide-react":"^0.548.0","@langchain/core":"^0.3.0","@vercel/analytics":"^1.5.0","@aptos-labs/ts-sdk":">=1.26.0","@langchain/google-genai":"^0.1.0"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.7.1","typescript":"^5","@types/node":"^20","tailwindcss":"^4","@types/react":"^19","@types/react-dom":"^19","@tailwindcss/postcss":"^4"},"peerDependencies":{"next":">=15.0.0","@aptos-labs/ts-sdk":">=1.26.0"},"_npmOperationalInternal":{"tmp":"tmp/aptos-x402_0.1.3_1761480690237_0.740902422266982","host":"s3://npm-registry-packages-npm-production"},"deprecated":"Package no longer supported. Contact Support at https://www.npmjs.com/support for more info."},"0.2.0":{"name":"@adipundir/aptos-x402","version":"0.2.0","keywords":["x402","aptos","payment","micropayment","http-402","blockchain","cryptocurrency","axios","axios-compatible","typescript","nextjs","middleware","ai-payments","machine-to-machine"],"author":{"name":"Adi Pundir"},"license":"MIT","_id":"@adipundir/aptos-x402@0.2.0","maintainers":[{"name":"adipundir","email":"pundir.aditya@outlook.com"}],"homepage":"https://aptos-x402.vercel.app","bugs":{"url":"https://github.com/adipundir/aptos-x402/issues"},"dist":{"shasum":"ffae1451888faa8f17e40e4e8af079d4e20053de","tarball":"https://registry.npmjs.org/@adipundir/aptos-x402/-/aptos-x402-0.2.0.tgz","fileCount":67,"integrity":"sha512-vxpPc0eg696iC1TxtoUaNxfTq2nHH+w3EI2Wz0z1Enjj/I1CJ66YUU4lwC9Z2js/9gUCjkmjpEIQcD2sCBqLCQ==","signatures":[{"sig":"MEYCIQChPKrNz/cO3tubP94eOBKC4L9aYlP9tDqpuYAzHT0xMQIhALRUVgHd50VmX/uVkqBoTAf+lU9ADbkw73lBcfI5rwmO","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":186526},"main":"dist/index.js","types":"dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","default":"./dist/index.js"},"./types":{"types":"./dist/types/index.d.ts","default":"./dist/types/index.js"},"./server":{"types":"./dist/server/index.d.ts","default":"./dist/server/index.js"}},"gitHead":"df38d91a491d52555208d5305710e0a4bfa6f89d","scripts":{"dev":"next dev --turbopack","demo":"tsx scripts/demo-agent.ts","test":"echo \"Tests coming soon\" && exit 0","build":"npm run build:sdk && npm run build:demo","start":"next start","build:sdk":"tsc -p tsconfig.sdk.json","build:demo":"next build --turbopack","prepublishOnly":"npm run build:sdk"},"_npmUser":{"name":"adipundir","email":"pundir.aditya@outlook.com"},"repository":{"url":"git+https://github.com/adipundir/aptos-x402.git","type":"git"},"_npmVersion":"10.9.3","description":"HTTP 402 Payment Protocol SDK for Aptos - Axios-compatible payment wrapper with automatic network detection and zero fallbacks","directories":{},"_nodeVersion":"22.19.0","dependencies":{"zod":"^3.23.8","clsx":"^2.1.1","next":">=15.0.0","axios":"^1.12.2","react":"19.1.0","shiki":"^3.14.0","langchain":"^0.3.0","react-dom":"19.1.0","x402-axios":"^0.6.6","lucide-react":"^0.548.0","tailwind-merge":"^3.3.1","@langchain/core":"^0.3.0","@vercel/analytics":"^1.5.0","@aptos-labs/ts-sdk":">=1.26.0","@radix-ui/react-slot":"^1.2.3","@radix-ui/react-tabs":"^1.1.13","@shikijs/transformers":"^3.14.0","@radix-ui/react-select":"^2.2.6","@langchain/google-genai":"^0.1.0","class-variance-authority":"^0.7.1","@radix-ui/react-separator":"^1.1.7","@radix-ui/react-scroll-area":"^1.2.10","@icons-pack/react-simple-icons":"^13.8.0","@radix-ui/react-use-controllable-state":"^1.2.2"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.7.1","typescript":"^5","@types/node":"^20","tailwindcss":"^4","@types/react":"^19","tw-animate-css":"^1.4.0","@types/react-dom":"^19","@tailwindcss/postcss":"^4"},"peerDependencies":{"next":">=15.0.0","@aptos-labs/ts-sdk":">=1.26.0"},"_npmOperationalInternal":{"tmp":"tmp/aptos-x402_0.2.0_1761690065374_0.042694852032607145","host":"s3://npm-registry-packages-npm-production"},"deprecated":"Package no longer supported. Contact Support at https://www.npmjs.com/support for more info."}},"time":{"created":"2025-10-03T16:19:31.013Z","modified":"2025-10-29T10:01:55.251Z","0.1.0":"2025-10-03T16:19:31.258Z","0.1.1":"2025-10-03T16:41:01.673Z","0.1.2":"2025-10-03T18:47:05.883Z","0.1.3":"2025-10-26T12:11:30.473Z","0.2.0":"2025-10-28T22:21:05.595Z"},"bugs":{"url":"https://github.com/adipundir/aptos-x402/issues"},"author":{"name":"Adi Pundir"},"license":"MIT","homepage":"https://aptos-x402.vercel.app","keywords":["x402","aptos","payment","micropayment","http-402","blockchain","cryptocurrency","axios","axios-compatible","typescript","nextjs","middleware","ai-payments","machine-to-machine"],"repository":{"url":"git+https://github.com/adipundir/aptos-x402.git","type":"git"},"description":"HTTP 402 Payment Protocol SDK for Aptos - Axios-compatible payment wrapper with automatic network detection and zero fallbacks","maintainers":[{"name":"adipundir","email":"pundir.aditya@outlook.com"},{"name":"samscasm","email":"sakshamtyagi2008@gmail.com"}],"readme":"# @adipundir/aptos-x402\n\n> x402 Payment Protocol SDK for Aptos blockchain\n\nHTTP 402 Payment Required for machine-to-machine micropayments on Aptos.\n\n[![npm version](https://img.shields.io/npm/v/@adipundir/aptos-x402.svg)](https://www.npmjs.com/package/@adipundir/aptos-x402)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n## 🎮 Try the Interactive Demo\n\nSee x402 in action with our interactive CLI demo:\n\n```bash\n# Clone the repo\ngit clone https://github.com/adipundir/aptos-x402\ncd aptos-x402\n\n# Install dependencies\nnpm install\n\n# Start the server\nnpm run dev\n\n# In another terminal, run the demo\nnpx tsx scripts/test-x402-axios.ts\n```\n\nThe demo will:\n1. Ask for your Aptos private key (testnet)\n2. Check your balance\n3. Make a request to a protected API endpoint\n4. **Automatically handle the payment** using x402-axios\n5. Show you the response and transaction details\n\n**Don't have testnet APT?** Generate an account and fund it:\n```bash\nnpx tsx scripts/generate-account.ts\nnpx tsx scripts/fund-account.ts <your-address>\n```\n\n## Quick Start (5 Minutes)\n\nAdd cryptocurrency payments to your Next.js API in just 3 steps:\n\n### Step 1: Install the Package\n\n```bash\nnpm install @adipundir/aptos-x402\n```\n\n## 🛒 For Buyers (Consuming Paid APIs)\n\nAccess paid APIs with automatic payment handling using our **axios-compatible** interface:\n\n```typescript\nimport { x402axios } from '@adipundir/aptos-x402';\n\n// Works exactly like axios - payment handled automatically!\nconst response = await x402axios.get('https://api.example.com/premium/data', {\n  privateKey: '0x...'  // Your Aptos private key\n});\n\nconsole.log(response.data);              // API response data\nconsole.log(response.paymentInfo);       // { transactionHash, amount, ... }\n```\n\n### Full Axios Compatibility\n\nx402axios supports all standard axios methods and features:\n\n```typescript\n// GET request\nconst response = await x402axios.get('https://api.example.com/data', {\n  privateKey: '0x...',\n  timeout: 5000,\n  headers: { 'Authorization': 'Bearer token' }\n});\n\n// POST request\nconst response = await x402axios.post('https://api.example.com/analyze', \n  { text: 'Hello world' },\n  { \n    privateKey: '0x...',\n    headers: { 'Content-Type': 'application/json' }\n  }\n);\n\n// Create instance with defaults\nconst api = x402axios.create({\n  baseURL: 'https://api.example.com',\n  timeout: 10000,\n  privateKey: '0x...'  // Default for all requests\n});\n\nconst response = await api.get('/premium/data');\n```\n\n**What happens automatically:**\n1. Makes initial request to the protected API\n2. Detects 402 Payment Required response\n3. Extracts payment requirements (amount, recipient, network)\n4. Builds and signs Aptos transaction\n5. Retries request with payment\n6. Returns data + payment info\n\n## 🏪 For Sellers (Creating Paid APIs)\n\n### Step 2: Create `middleware.ts` in Your Project Root\n\nCreate a file called `middleware.ts` in the root of your Next.js project (same level as `app/` or `pages/`):\n\n```typescript\n// middleware.ts\nimport { paymentMiddleware } from '@adipundir/aptos-x402';\n\nexport const middleware = paymentMiddleware(\n  process.env.PAYMENT_RECIPIENT_ADDRESS!,\n  {\n    // Configure which routes require payment\n    '/api/premium/weather': {\n      price: '1000000',  // 0.01 APT (in Octas)\n      network: 'testnet',\n      config: { description: 'Premium weather data' },\n    },\n  },\n  { \n    // Use public facilitator (perfect for testing)\n    url: 'https://aptos-x402.vercel.app/api/facilitator'\n  }\n);\n\nexport const config = {\n  matcher: ['/api/premium/:path*'],  // Apply to all /api/premium/* routes\n};\n```\n\n### Step 3: Set Environment Variable\n\nCreate `.env.local` in your project root:\n\n```env\n# Your Aptos wallet address (where payments go)\nPAYMENT_RECIPIENT_ADDRESS=0xYOUR_WALLET_ADDRESS_HERE\n```\n\n**How to get your wallet address:**\n1. Install [Petra Wallet](https://petra.app/) or [Martian Wallet](https://martianwallet.xyz/)\n2. Create a new wallet\n3. Copy your address (starts with `0x`)\n4. Paste it in `.env.local`\n\n**That's it!** Your API routes under `/api/premium/*` now require payment.\n\n### Your API Routes Stay Clean\n\n**Important:** You don't need to change anything in your API routes! The middleware handles everything.\n\n```typescript\n// app/api/premium/weather/route.ts\nimport { NextResponse } from 'next/server';\n\nexport async function GET() {\n  // This code only runs AFTER payment is verified and settled!\n  // No payment logic needed here.\n  \n  return NextResponse.json({\n    location: 'San Francisco',\n    temperature: 72,\n    condition: 'Sunny',\n  });\n}\n```\n\nThe middleware automatically:\n- Returns 402 for requests without payment\n- Verifies payment signatures\n- Settles payments on Aptos blockchain\n- Only allows API execution after successful payment\n- Adds payment receipt headers to responses\n\n### Next.js Requirements\n\n- **Next.js 15+** with App Router\n- TypeScript (recommended)\n- Node.js 20+\n\n### Complete Project Structure\n\nAfter setup, your Next.js project should look like this:\n\n```\nmy-nextjs-app/\n├── middleware.ts              ← Payment middleware (created in Step 2)\n├── .env.local                 ← Environment variables (created in Step 3)\n├── app/\n│   └── api/\n│       └── premium/           ← Protected routes (payment required)\n│           └── weather/\n│               └── route.ts   ← Your API route (no payment code needed!)\n├── package.json\n└── next.config.js\n```\n\n**Key Points:**\n- `middleware.ts` must be in the project root (not inside `app/`)\n- Applies to all routes matching `/api/premium/*` (configurable)\n- Your API routes need **zero** payment code\n- Works automatically on every request\n\n### Testing Your Setup\n\nAfter setup, test that payment protection is working:\n\n**1. Start your Next.js dev server:**\n```bash\nnpm run dev\n```\n\n**2. Try accessing your protected route without payment:**\n```bash\ncurl http://localhost:3000/api/premium/weather\n```\n\n**Expected Response (402 Payment Required):**\n```json\n{\n  \"x402Version\": 1,\n  \"accepts\": [{\n    \"scheme\": \"exact\",\n    \"network\": \"aptos-testnet\",\n    \"maxAmountRequired\": \"1000000\",\n    \"payTo\": \"0xYOUR_WALLET_ADDRESS\",\n    \"description\": \"Premium weather data\",\n    \"resource\": \"http://localhost:3000/api/premium/weather\"\n  }]\n}\n```\n\nIf you see this 402 response, your middleware is working perfectly!\n\n**3. For full payment testing:**\n- Use our [live demo](https://aptos-x402.vercel.app) to see the complete flow\n- Or implement client-side payment signing (see [Client Integration](#client-integration) below)\n\n## What is x402?\n\n[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.\n\n### Use Cases\n\n- **Pay-per-API-call** - Monetize your APIs without subscriptions\n- **AI Agent Payments** - Let AI agents pay for resources automatically\n- **Metered Services** - Charge exactly for what's consumed\n- **Decentralized Access Control** - No API keys, just payments\n- **Micropayments** - Enable sub-cent transactions economically\n\n## Features\n\n - **Axios-compatible** - Drop-in replacement for axios with x402 payment support\n - **Zero payment logic in your code** - Middleware handles everything\n - **Aptos native** - Built on Aptos's fast finality (~1-3s)\n - **Type-safe** - Full TypeScript support with proper interfaces\n - **x402 compliant** - Follows official Coinbase specification\n - **Next.js optimized** - Designed for Next.js 15+ (more frameworks coming)\n - **Production ready** - Comprehensive error handling and logging\n - **Backward compatible** - Old interface still works alongside new axios interface\n\n## How It Works\n\n```\n┌─────────┐                  ┌─────────┐                  ┌────────────┐\n│ Client  │                  │  Your   │                  │   Aptos    │\n│         │                  │  API    │                  │ Blockchain │\n└────┬────┘                  └────┬────┘                  └─────┬──────┘\n     │                            │                              │\n     │  1. GET /api/premium      │                              │\n     │──────────────────────────>│                              │\n     │                            │                              │\n     │  2. 402 Payment Required  │                              │\n     │<──────────────────────────│                              │\n     │   {accepts: [...]}         │                              │\n     │                            │                              │\n     │  3. Sign Transaction       │                              │\n     │   (client-side)            │                              │\n     │                            │                              │\n     │  4. GET /api/premium      │                              │\n     │     X-PAYMENT: <signed>   │                              │\n     │──────────────────────────>│                              │\n     │                            │  5. Verify (fast)            │\n     │                            │──────────────┐               │\n     │                            │              │               │\n     │                            │<─────────────┘               │\n     │                            │                              │\n     │                            │  6. Settle (submit tx)       │\n     │                            │─────────────────────────────>│\n     │                            │                              │\n     │                            │  7. Confirmed                │\n     │                            │<─────────────────────────────│\n     │                            │                              │\n     │  8. 200 OK + Resource     │                              │\n     │<──────────────────────────│                              │\n     │   X-Payment-Response       │                              │\n```\n\n## Installation & Setup\n\n### 1. Install Dependencies\n\n```bash\nnpm install @adipundir/aptos-x402 @aptos-labs/ts-sdk next\n```\n\n### 2. Environment Variables\n\n```env\n# Your wallet address (receives payments)\nPAYMENT_RECIPIENT_ADDRESS=0xYOUR_WALLET_ADDRESS_HERE\n\n# Facilitator URL (required)\n# Option 1: Use public demo facilitator (easiest for testing)\nFACILITATOR_URL=https://aptos-x402.vercel.app/api/facilitator\n\n# Option 2: Deploy your own for production\n# FACILITATOR_URL=https://yourdomain.com/api/facilitator\n```\n\n### 3. Create Middleware\n\n```typescript\n// middleware.ts\nimport { paymentMiddleware } from '@adipundir/aptos-x402';\n\nexport const middleware = paymentMiddleware(\n  process.env.PAYMENT_RECIPIENT_ADDRESS!,\n  {\n    // Configure your protected routes\n    '/api/premium/weather': {\n      price: '1000000',  // 0.01 APT\n      network: 'testnet',\n      config: {\n        description: 'Premium weather data',\n        mimeType: 'application/json',\n      },\n    },\n    '/api/premium/stocks': {\n      price: '5000000',  // 0.05 APT\n      network: 'testnet',\n      config: {\n        description: 'Real-time stock data',\n      },\n    },\n  },\n  {\n    // Facilitator handles blockchain interactions\n    url: process.env.FACILITATOR_URL!,\n  }\n);\n\nexport const config = {\n  matcher: ['/api/premium/:path*'],\n};\n```\n\n### 4. Create Your API Route\n\n```typescript\n// app/api/premium/weather/route.ts\nimport { NextResponse } from 'next/server';\n\nexport const dynamic = 'force-dynamic';\n\nexport async function GET(request: Request) {\n  // Payment already verified & settled by middleware!\n  // Just return your premium data\n  \n  return NextResponse.json({\n    location: 'San Francisco',\n    temperature: 72,\n    forecast: '5-day detailed forecast',\n    premium: true,\n  });\n}\n```\n\n### 5. Set Up Facilitator\n\nThe facilitator handles blockchain interactions. You need to deploy facilitator endpoints:\n\n```typescript\n// app/api/facilitator/verify/route.ts\n// app/api/facilitator/settle/route.ts\n```\n\nSee the [full facilitator implementation](https://github.com/adipundir/aptos-x402/tree/main/app/api/facilitator) in the repository.\n\n## API Reference\n\n### `paymentMiddleware(recipientAddress, routes, facilitatorConfig)`\n\nCreates x402 payment middleware for Next.js.\n\n#### Parameters\n\n- **`recipientAddress`** (string, required): Your Aptos wallet address\n- **`routes`** (object, required): Route configuration mapping\n  - **`path`** (string): API route path\n  - **`config`** (RouteConfig):\n    - `price` (string): Payment amount in Octas (1 APT = 100,000,000 Octas)\n    - `network` (string): `'testnet'` or `'mainnet'`\n    - `config.description` (string, optional): Resource description\n    - `config.mimeType` (string, optional): Response MIME type\n    - `config.maxTimeoutSeconds` (number, optional): Max timeout\n- **`facilitatorConfig`** (object, required):\n  - `url` (string): Facilitator base URL\n\n#### Returns\n\nNext.js middleware function\n\n## TypeScript Types\n\n```typescript\nimport type {\n  PaymentRequiredResponse,\n  PaymentRequirements,\n  PaymentPayload,\n  RouteConfig,\n  FacilitatorConfig,\n} from '@adipundir/aptos-x402/types';\n```\n\n### Core Types\n\n```typescript\ninterface RouteConfig {\n  price: string;              // Amount in Octas\n  network?: string;           // 'testnet' | 'mainnet'\n  config?: {\n    description?: string;\n    mimeType?: string;\n    outputSchema?: Record<string, any>;\n    maxTimeoutSeconds?: number;\n  };\n}\n\ninterface FacilitatorConfig {\n  url: string;  // Required facilitator URL\n}\n\ninterface PaymentRequiredResponse {\n  x402Version: number;\n  accepts: PaymentRequirements[];\n  error?: string;\n}\n```\n\n## Client Integration\n\n### Simple Approach: Use x402axios\n\nThe easiest way to consume protected APIs is with our **axios-compatible** wrapper:\n\n```typescript\nimport { x402axios } from '@adipundir/aptos-x402';\n\n// Automatic payment handling - works exactly like axios!\nconst response = await x402axios.get('https://api.example.com/premium/data', {\n  privateKey: '0x...'  // Your Aptos private key\n});\n\nconsole.log(response.data);              // API response data\nconsole.log(response.paymentInfo);       // Payment details\n```\n\n### Advanced: Manual Implementation\n\nIf you need more control, you can implement the payment flow manually:\n\n```typescript\nimport { Aptos, AptosConfig, Network, Account, Ed25519PrivateKey } from '@aptos-labs/ts-sdk';\n\nasync function callProtectedAPI(url: string, privateKey: string) {\n  // Step 1: Try without payment\n  let response = await fetch(url);\n  \n  if (response.status === 402) {\n    // Step 2: Parse payment requirements\n    const paymentReqs = await response.json();\n    const requirement = paymentReqs.accepts[0];\n    \n    // Step 3: Initialize Aptos client\n    const config = new AptosConfig({ \n      network: requirement.network === 'aptos-testnet' ? Network.TESTNET : Network.MAINNET \n    });\n    const aptos = new Aptos(config);\n    \n    // Step 4: Create account and build transaction\n    const account = Account.fromPrivateKey({\n      privateKey: new Ed25519PrivateKey(privateKey)\n    });\n    \n    const transaction = await aptos.transaction.build.simple({\n      sender: account.accountAddress,\n      data: {\n        function: '0x1::aptos_account::transfer',\n        functionArguments: [requirement.payTo, requirement.maxAmountRequired]\n      }\n    });\n    \n    // Step 5: Sign and create payment header\n    const authenticator = aptos.transaction.sign({ signer: account, transaction });\n    \n    const paymentPayload = {\n      x402Version: 1,\n      scheme: requirement.scheme,\n      network: requirement.network,\n      payload: {\n        signature: Buffer.from(authenticator.bcsToBytes()).toString('base64'),\n        transaction: Buffer.from(transaction.bcsToBytes()).toString('base64')\n      }\n    };\n    \n    // Step 6: Retry with payment\n    response = await fetch(url, {\n      headers: {\n        'X-PAYMENT': Buffer.from(JSON.stringify(paymentPayload)).toString('base64')\n      }\n    });\n  }\n  \n  // Step 11: Get the data\n  const data = await response.json();\n  console.log('Success!', data);\n  \n  // Step 12: Check payment receipt (optional)\n  const paymentResponse = response.headers.get('x-payment-response');\n  if (paymentResponse) {\n    const receipt = JSON.parse(Buffer.from(paymentResponse, 'base64').toString());\n    console.log('Payment settled:', receipt.settlement.txHash);\n  }\n  \n  return data;\n}\n\n// Usage\nawait callProtectedAPI(\n  'http://localhost:3000/api/premium/weather',\n  '0xYOUR_PRIVATE_KEY_HERE'\n);\n```\n\n### Quick Test with curl\n\n**1. Get payment requirements:**\n```bash\ncurl http://localhost:3000/api/premium/weather\n```\n\n**Response:**\n```json\n{\n  \"x402Version\": 1,\n  \"accepts\": [{\n    \"scheme\": \"exact\",\n    \"network\": \"aptos-testnet\",\n    \"maxAmountRequired\": \"1000000\",\n    \"payTo\": \"0xYOUR_WALLET_ADDRESS\",\n    \"resource\": \"http://localhost:3000/api/premium/weather\"\n  }]\n}\n```\n\n**2. Make payment request:**\n```bash\ncurl http://localhost:3000/api/premium/weather \\\n  -H \"X-PAYMENT: eyJ4NDAyVmVyc2lvbiI6MSwic2NoZW1lIjoi...\"\n```\n\n### Browser Integration\n\nFor browser applications, you can use wallet integrations:\n\n```typescript\n// Using Petra Wallet\nconst { signTransaction } = usePetraWallet();\nconst signedTx = await signTransaction(transaction);\n```\n\n### AI Agent Integration\n\n```typescript\nimport { x402axios } from '@adipundir/aptos-x402';\n\n// Agent automatically handles payments\nconst response = await x402axios.get('https://api.example.com/premium/data', {\n  privateKey: process.env.AGENT_KEY!\n});\n\nconst data = response.data;\n```\n\n## Examples\n\n### Example Projects in This Repo\n\n- **[examples/simple-seller/](./examples/simple-seller/)** - Basic middleware configuration\n- **[examples/facilitator/](./examples/facilitator/)** - Facilitator setup guide  \n- **[app/](./app/)** - Complete working demo with frontend\n\n### Live Demo\n\nVisit **https://aptos-x402.vercel.app** to see the complete payment flow in action:\n- Try requesting without payment (gets 402)\n- Sign transaction with demo account\n- See payment verification and settlement\n- View transaction on Aptos Explorer\n\n## Facilitator Setup\n\nThe facilitator is a critical component that handles blockchain interactions (verify and settle operations).\n\n### Why Separate Facilitator?\n\n- **Security**: Keeps blockchain keys separate from app servers\n- **Scalability**: Can be shared across multiple services\n- **x402 Compliance**: Follows the official protocol architecture\n\n### Options\n\n#### 1. Use Public Demo Facilitator (Easiest)\n\n```env\nFACILITATOR_URL=https://aptos-x402.vercel.app/api/facilitator\n```\n\nPerfect for:\n- Development and testing\n- Proof of concepts\n- Learning x402 protocol\n\n**Note**: For production, deploy your own for better control and reliability.\n\n#### 2. Deploy Your Own (Production)\n\nCopy the facilitator implementation from the repository:\n- `app/api/facilitator/verify/route.ts`\n- `app/api/facilitator/settle/route.ts`\n\nDeploy to:\n- Same Next.js app (simplest)\n- Separate microservice (recommended for scale)\n- Serverless functions (Vercel, AWS Lambda, etc.)\n\nSee [Facilitator Guide](https://github.com/adipundir/aptos-x402/blob/main/examples/facilitator) for full setup instructions.\n\n## FAQ\n\n### Why not just use API keys?\n\n- **No key management** - No secrets to rotate or leak\n- **Pay-per-use** - No subscriptions or upfront costs\n- **Decentralized** - No central auth server\n- **Monetization built-in** - Get paid automatically\n\n### How fast are payments?\n\n- **Verification**: < 50ms (cryptographic validation only)\n- **Settlement**: 1-3 seconds (Aptos blockchain finality)\n- **Total**: ~1-3 seconds for full payment confirmation\n\n### What are the costs?\n\n- **Client pays**: Transaction gas (~0.0001 APT) + your API price\n- **Server pays**: Nothing! Just host the facilitator\n- **Protocol fees**: None, x402 is free and open source\n\n### Can I use this with other blockchains?\n\nThis package is Aptos-specific. For other chains:\n- Ethereum: `@x402/ethereum` (coming soon)\n- Solana: `@x402/solana` (coming soon)\n- Sui: `@x402/sui` (coming soon)\n\n### Is this production-ready?\n\nYes! The protocol is designed for production use. However:\n- ⚠️ Start with testnet for development\n- ⚠️ Test thoroughly before mainnet deployment\n- ⚠️ Monitor facilitator health and security\n\n## Contributing\n\nContributions welcome! Feel free to open issues or submit pull requests.\n\n## License\n\nMIT © Aditya Pundir\n\n## Links\n\n- [GitHub Repository](https://github.com/adipundir/aptos-x402)\n- [NPM Package](https://www.npmjs.com/package/@adipundir/aptos-x402)\n- [x402 Protocol Spec](https://github.com/coinbase/x402)\n- [Aptos Developer Docs](https://aptos.dev)\n\n## Support\n\n- 🐛 [Report Issues](https://github.com/adipundir/aptos-x402/issues)\n- 💬 [Discussions](https://github.com/adipundir/aptos-x402/discussions)\n- 🐦 Twitter: [@adipundir](https://x.com/adipundir)\n\n---\n\nBuilt with ❤️ for the Aptos ecosystem\n\n","readmeFilename":"README.md"}