From 749e23ba62480dbfe5f0b50425893cd63ed12e56 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Sat, 8 Nov 2025 14:38:41 +0100 Subject: [PATCH 01/30] add Federico as instructor --- content/common/intro/instructors.tsx | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/content/common/intro/instructors.tsx b/content/common/intro/instructors.tsx index 192b153b913..9396b5eeab7 100644 --- a/content/common/intro/instructors.tsx +++ b/content/common/intro/instructors.tsx @@ -103,6 +103,14 @@ const instructors: Instructor[] = [ x: "https://x.com/alejandro99so", linkedin: "https://www.linkedin.com/in/alejandro99so/", github: "https://github.com/alejandro99so", + }, + { + name: "Federico Nardelli", + title: "Developer Relations Engineer", + image: "https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/instructors/federico-nardelli.jpeg", + x: "https://x.com/federico_nardo7", + linkedin: "https://www.linkedin.com/in/federico-nardelli-a2969b26a/", + github: "https://github.com/federiconardelli7", } ]; From e59b49b071fcb9a760be1a8f3aa14cd162057916 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Sat, 8 Nov 2025 14:43:24 +0100 Subject: [PATCH 02/30] add x402 course --- content/courses.tsx | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/content/courses.tsx b/content/courses.tsx index 801b8c03931..11f9285b55c 100644 --- a/content/courses.tsx +++ b/content/courses.tsx @@ -40,6 +40,19 @@ const officialCourses: Course[] = [ category: "Fundamentals", certificateTemplate: "https://qizat5l3bwvomkny.public.blob.vercel-storage.com/AvalancheAcademy_Certificate.pdf" }, + { + name: "x402 Payment Infrastructure", + description: "Learn about the x402 protocol for instant, permissionless HTTP-native payments on Avalanche", + slug: "x402-payment-infrastructure", + icon: , + status: "featured", + duration: "2 hours", + languages: ["JavaScript", "Typescript"], + tools: ["Thirdweb x402", "PayAI", "Ultravioleta DAO", "x402-rs"], + instructors: ["Federico Nardelli"], + category: "Fundamentals", + certificateTemplate: "https://qizat5l3bwvomkny.public.blob.vercel-storage.com/AvalancheAcademy_Certificate.pdf" + }, { name: "Interchain Messaging", description: "Utilize Avalanche Interchain Messaging to build cross-chain dApps in the Avalanche network", From 012c94ae721ecac121eccdff2ec1dcc5bf43c423 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Sat, 8 Nov 2025 14:44:13 +0100 Subject: [PATCH 03/30] add x402 course in learning path as foundamental after avalanche (for the moment) --- .../avalanche-developer.config.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/components/academy/learning-path-configs/avalanche-developer.config.ts b/components/academy/learning-path-configs/avalanche-developer.config.ts index 1b5d1bf731f..4a61a982670 100644 --- a/components/academy/learning-path-configs/avalanche-developer.config.ts +++ b/components/academy/learning-path-configs/avalanche-developer.config.ts @@ -34,6 +34,16 @@ export const avalancheLearningPaths: CourseNode[] = [ position: { x: 20, y: 150 }, mobileOrder: 9 }, + { + id: "x402-payment-infrastructure", + name: "x402 Payment Infrastructure", + description: "Learn about instant, permissionless HTTP-native payments on Avalanche", + slug: "x402-payment-infrastructure", + category: "Fundamentals", + dependencies: ["avalanche-fundamentals"], + position: { x: 80, y: 150 }, + mobileOrder: 10 + }, // Third Layer - Branching paths { From 28a24c137e7c8055a446399267ca64e5e5089e75 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Sun, 9 Nov 2025 13:22:42 +0100 Subject: [PATCH 04/30] add x402 course to academy content --- content/academy/meta.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/content/academy/meta.json b/content/academy/meta.json index b7d9b9b55d4..2f8e2624a5f 100644 --- a/content/academy/meta.json +++ b/content/academy/meta.json @@ -10,6 +10,7 @@ "interchain-token-transfer", "icm-chainlink", "avacloudapis", - "encrypted-erc" + "encrypted-erc", + "x402-payment-infrastructure" ] } \ No newline at end of file From 642938a4456042f1f8266abf3aaf13c61b300519 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Sun, 9 Nov 2025 15:36:26 +0100 Subject: [PATCH 05/30] add welcome to the course and meta structure file of the course --- .../x402-payment-infrastructure/index.mdx | 42 +++++++++++++++++++ .../x402-payment-infrastructure/meta.json | 17 ++++++++ 2 files changed, 59 insertions(+) create mode 100644 content/academy/x402-payment-infrastructure/index.mdx create mode 100644 content/academy/x402-payment-infrastructure/meta.json diff --git a/content/academy/x402-payment-infrastructure/index.mdx b/content/academy/x402-payment-infrastructure/index.mdx new file mode 100644 index 00000000000..0c14e414b14 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/index.mdx @@ -0,0 +1,42 @@ +--- +title: Welcome to the Course +description: Learn about the x402 protocol for instant, permissionless HTTP-native payments on Avalanche. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: Coins +--- + +## Why Take This Course? + +The x402 protocol is revolutionizing how payments work on the internet by activating HTTP 402 "Payment Required" status code for instant, permissionless transactions. Built on blockchain technology, x402 enables seamless machine-to-machine payments, making it perfect for AI agents, micropayments, and API monetization. + +Traditional payment systems are slow, expensive, and require accounts, KYC, and complex integrations. x402 eliminates these friction points with 2-second settlement times, zero protocol fees, and no account requirements. Payments are gasless for end users—facilitators sponsor the minimal blockchain gas fees (~\$0.001 on Avalanche with current network conditions). For developers building on Avalanche, x402 leverages the network's low fees and fast finality to create an ideal environment for high-frequency micropayments. + +## Course Content + +- [Introduction to x402](/academy/x402-payment-infrastructure/02-introduction/01-what-is-x402) +- [Technical Architecture](/academy/x402-payment-infrastructure/03-technical-architecture/01-payment-flow) +- [x402 on Avalanche](/academy/x402-payment-infrastructure/04-x402-on-avalanche/01-why-avalanche) +- [Implementation Guide](/academy/x402-payment-infrastructure/05-implementation/01-setup) + +## Prerequisites + +Before taking this course, you should have: + +- **Blockchain Fundamentals:** Basic understanding of blockchain technology and how transactions work. +- **Avalanche Fundamentals:** Familiarity with the Avalanche network, particularly the C-Chain. +- **HTTP/APIs:** Understanding of HTTP protocols, status codes, and API development. +- **Programming:** Basic knowledge of JavaScript/TypeScript or another programming language. +- **Smart Contracts (Optional):** Helpful but not required for understanding payment verification. + +## Learning Outcomes + +By the end of this course, you will: + +- Understand the x402 protocol and how it activates HTTP 402 for internet-native payments. +- Learn the complete payment flow from request to settlement, including facilitator roles. +- Discover why Avalanche is ideal for x402 implementations with its low fees and fast finality. +- Explore different x402 facilitator implementations available on Avalanche (Thirdweb, PayAI, Ultravioleta DAO, x402-rs). +- Implement x402 middleware in your own applications and configure endpoint pricing. +- Build use cases for AI agent payments, micropayments, and API monetization. +- Master security best practices and scaling considerations for production deployments. diff --git a/content/academy/x402-payment-infrastructure/meta.json b/content/academy/x402-payment-infrastructure/meta.json new file mode 100644 index 00000000000..ccc3856d90c --- /dev/null +++ b/content/academy/x402-payment-infrastructure/meta.json @@ -0,0 +1,17 @@ +{ + "title": "x402 Payment Infrastructure", + "icon": "Coins", + "root": true, + "pages": [ + "index", + "---Introduction to x402---", + "...02-introduction", + "---Technical Architecture---", + "...03-technical-architecture", + "---x402 on Avalanche---", + "...04-x402-on-avalanche", + "---Implementation Guide---", + "...05-implementation", + "get-certificate" + ] +} From 7cd4bb04c7ec1d59ebd6793bd3e7c4c8e030204f Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Sun, 9 Nov 2025 15:37:09 +0100 Subject: [PATCH 06/30] add get-certificate after finishing the course --- .../get-certificate.mdx | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 content/academy/x402-payment-infrastructure/get-certificate.mdx diff --git a/content/academy/x402-payment-infrastructure/get-certificate.mdx b/content/academy/x402-payment-infrastructure/get-certificate.mdx new file mode 100644 index 00000000000..42bc5227e57 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/get-certificate.mdx @@ -0,0 +1,14 @@ +--- +title: Course Completion Certificate +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: BadgeCheck +--- + +import CertificatePage from '@/components/quizzes/certificates'; + +Congratulations! You've completed the x402 Payment Infrastructure course. Let's verify your progress and get your certificate. + + + +Thank you for taking this course! You now have the knowledge to build instant, permissionless payment infrastructure on Avalanche using the x402 protocol. We hope you'll use what you've learned to create innovative payment-enabled applications and contribute to the future of machine-to-machine commerce. From c854a4ba05d0bd16ff8ec9e436c19f2bc5658743 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Sun, 9 Nov 2025 16:25:18 +0100 Subject: [PATCH 07/30] Add the introduction for the x402 course --- .../02-introduction/01-what-is-x402.mdx | 111 ++++++ .../02-introduction/02-payment-problem.mdx | 199 ++++++++++ .../02-introduction/03-use-cases.mdx | 374 ++++++++++++++++++ 3 files changed, 684 insertions(+) create mode 100644 content/academy/x402-payment-infrastructure/02-introduction/01-what-is-x402.mdx create mode 100644 content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx create mode 100644 content/academy/x402-payment-infrastructure/02-introduction/03-use-cases.mdx diff --git a/content/academy/x402-payment-infrastructure/02-introduction/01-what-is-x402.mdx b/content/academy/x402-payment-infrastructure/02-introduction/01-what-is-x402.mdx new file mode 100644 index 00000000000..742732fe597 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/02-introduction/01-what-is-x402.mdx @@ -0,0 +1,111 @@ +--- +title: What is x402? +description: Understanding the x402 protocol and HTTP 402 activation for internet-native payments. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: BookOpen +--- + +## Introduction + +The x402 protocol is an open standard that activates the HTTP 402 "Payment Required" status code, enabling instant, permissionless payments directly through HTTP requests. This revolutionary approach makes payments a native part of internet communication, eliminating the friction associated with traditional payment systems. + +## HTTP 402: A Long-Awaited Activation + +The HTTP 402 status code has existed since the early days of the internet but was never fully implemented. It was reserved for "future use" as a way to require payment before accessing content or services. The x402 protocol finally brings this vision to life by: + +- **Activating HTTP 402**: Making payment a standard HTTP response code +- **Blockchain Settlement**: Using blockchain technology for instant, permissionless transactions +- **Open Protocol**: Anyone can implement or extend the standard + +## How x402 Works + +At its core, x402 transforms how payments are requested and fulfilled on the web: + +1. **Client Requests Resource**: A user or AI agent sends an HTTP request to access content or an API endpoint +2. **Server Returns 402**: Instead of returning the content, the server responds with HTTP 402 "Payment Required" +3. **Payment Submitted**: The client automatically pays using stablecoins (like USDC) on the blockchain +4. **Access Granted**: Once payment is confirmed, the server releases the requested content + +This entire process happens in approximately 2 seconds, creating a seamless payment experience. + +![The x402 payment cycle](/tmpimagesx402/paumentcyclex402.png) + +## Key Characteristics + +### Open and Permissionless + +Unlike traditional payment systems that require: +- Creating accounts +- Completing KYC verification +- Managing API keys +- Setting up merchant accounts + +x402 requires **none of these**. Anyone can start accepting payments immediately by implementing the protocol. + +### Instant Settlement + +Traditional payment systems can take days to settle transactions. x402 settles payments in approximately 2 seconds, enabled by blockchain technology and Avalanche's fast finality. + +### Zero Protocol Fees + +There are no protocol-level fees with x402. The cost structure is: + +**For Users (Payers)**: +- **\$0 gas fees** - completely gasless for end users +- No subscription fees +- No processing fees +- Only pay the actual payment amount + +**For Facilitators**: +- Minimal blockchain gas fees (~\$0.001 per transaction on Avalanche with current network conditions) +- Facilitators sponsor gas on behalf of users using EIP-3009 gasless payments + +This gasless model means users don't need to hold AVAX or any native blockchain tokens - they only need the payment token (like USDC). + +### HTTP-Native + +x402 integrates directly with HTTP, making it compatible with existing web infrastructure. Developers can add payment requirements to their APIs with minimal code changes, often just one line of middleware. + +## Why x402 Matters + +The x402 protocol enables entirely new business models and use cases: + +- **AI-to-AI Payments**: AI agents can autonomously pay for services without human intervention +- **Micropayments**: Charge fractions of a cent per API request or piece of content +- **Pay-Per-Use**: Users only pay for what they consume, no subscriptions required +- **Instant Monetization**: Developers can monetize APIs and services immediately + +## x402 vs Traditional Payments + +| Feature | Traditional Payments | x402 Protocol | +|---------|---------------------|---------------| +| Setup Time | Days to weeks | Minutes | +| Settlement | 2-7 days | ~2 seconds | +| Protocol Fees | 2-3% + fixed fees | ~\$0.001 gas | +| KYC Required | Yes | No | +| Account Required | Yes | No | +| API Keys | Required | Optional | +| Micropayments | Not feasible | Optimized | +| Autonomous Payments | Not possible | Native support | + +## The Protocol Ecosystem + +x402 is supported by an ecosystem of **facilitators**—services that handle payment verification and submission on behalf of merchants. These facilitators: + +- Verify payment authenticity +- Submit transactions to the blockchain +- Handle settlement with merchants +- Provide developer tools and SDKs + +Popular facilitators on Avalanche include Thirdweb x402, PayAI, Ultravioleta DAO, and x402-rs. We'll explore these in detail in later lessons. + +## Summary + +The x402 protocol activates HTTP 402 to enable instant, permissionless, HTTP-native payments. By leveraging blockchain technology, x402 eliminates the friction of traditional payment systems while enabling new use cases like AI agent payments and micropayments. With approximately 2-second settlement, zero protocol fees, and no account requirements, x402 is revolutionizing how we think about internet payments. + +## Additional Resources + +- [x402.org](https://www.x402.org/) - Official x402 protocol website +- [x402 Whitepaper](https://www.x402.org/x402-whitepaper.pdf) - Technical specification +- [GitHub Repository](https://github.com/coinbase/x402) - Open source implementation diff --git a/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx b/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx new file mode 100644 index 00000000000..326ec52abb8 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx @@ -0,0 +1,199 @@ +--- +title: The Traditional Payment Problem +description: Understanding the limitations and friction points of traditional payment systems. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: TriangleAlert +--- + +## The Payment Friction Problem + +Traditional payment systems create significant friction for both users and developers, especially when dealing with digital services, APIs, and content. This friction manifests in multiple ways, making it difficult to implement efficient payment models for modern applications. + +## The Five-Step Friction Model + +Every traditional payment interaction requires users to complete at least five time-consuming steps: + +### 1. Create Account + +Before making any payment, users must: +- Sign up for a service account +- Provide personal information +- Verify email addresses +- Set up passwords and security + +**Time Impact**: 5-15 minutes per service
+**User Experience**: High abandonment rates during signup + +### 2. Add Payment Method + +After creating an account, users must: +- Enter credit card details +- Complete bank verification +- Wait for payment method approval +- Navigate complex payment forms + +**Time Impact**: 3-10 minutes
+**User Experience**: Security concerns and data privacy issues + +### 3. Complete KYC (Know Your Customer) + +Many services require additional identity verification: +- Submit government-issued ID +- Provide proof of address +- Complete video verification +- Wait for manual approval + +**Time Impact**: Hours to days
+**User Experience**: Privacy concerns and verification delays + +### 4. Buy Credits or Subscribe + +Traditional payment models force prepayment: +- Purchase credits you may not use +- Subscribe to monthly plans +- Commit to minimum purchases +- Lock in before trying the service + +**Time Impact**: Variable
+**User Experience**: Financial commitment before knowing value + +### 5. Manage API Keys + +For API access, developers must: +- Generate and store API keys +- Implement key rotation policies +- Secure keys in environment variables +- Monitor for key compromise + +**Time Impact**: Ongoing maintenance
+**User Experience**: Security risk and complexity + +## Cost Structure Problems + +Traditional payment processors impose significant fees that make micropayments impractical: + +### High Percentage Fees + +- Credit card processors: 2.9% + \$0.30 per transaction +- PayPal: 3.49% + fixed fee +- Stripe: 2.9% + \$0.30 per transaction + +**Impact on Micropayments**: +For a \$0.01 API request, traditional fees would be \$0.32 (3,200% overhead) + +### Fixed Fee Floor + +The fixed fee component (\$0.30) makes transactions under \$10 economically unviable for merchants. + +### Settlement Delays + +Payment processors hold funds for 2-7 days, creating cash flow challenges for merchants and limiting real-time business models. + +## Barriers to Automation + +Traditional payments were designed for human-to-merchant interactions, not for automated systems. This creates fundamental barriers: + +- **Manual Account Setup**: Automated systems cannot complete human-centric signup flows (CAPTCHA, email verification, identity checks) +- **Credential Management**: Storing payment credentials creates security and compliance risks +- **Pre-Approval Requirements**: Automated payments require human authorization, preventing autonomous operation + +These barriers make it impossible for AI agents and automated systems to participate in the payment economy. + +## The Micropayment Impossibility + +Traditional payment systems make micropayments economically impossible: + +``` +Transaction Value: $0.01 (1 cent API request) +Processing Fee: 2.9% + $0.30 +Total Fee: $0.30029 +Net to Merchant: -$0.29029 (loss of 2,903%) + +Result: Merchant loses money on every transaction +``` + +This economic reality forces developers into subscription models even when pay-per-use would better serve users. + +## The API Monetization Challenge + +Developers face a painful choice when monetizing APIs: + +### Option 1: Free with Rate Limits +- No revenue +- Abuse potential +- Resource waste +- Unsustainable scaling + +### Option 2: Monthly Subscriptions +- High user commitment barrier +- Revenue from unused capacity +- All-or-nothing pricing +- Poor user experience for occasional users + +### Option 3: Traditional Payments +- High fees eliminate profitability +- Complex integration +- Slow settlement +- User friction + +**None of these options are optimal**, creating a gap in the market for pay-per-use API models. + +## The AI Agent Problem + +As AI agents become more prevalent, traditional payment systems create impossible barriers: + +### AI Agents Cannot: +1. **Create Accounts**: Most signup flows require human verification (CAPTCHA, email confirmation) +2. **Complete KYC**: Identity verification is designed for humans, not autonomous agents +3. **Store Credentials Securely**: API keys and payment tokens create security vulnerabilities +4. **Make Autonomous Decisions**: Pre-approved payment methods limit AI flexibility +5. **Handle Micropayments**: Transaction fees make small payments impossible + +### What AI Agents Need: +- Instant, permissionless access to resources +- Pay-per-use pricing with no minimums +- Autonomous payment execution +- No account creation or KYC +- Micropayment support (fractions of a cent) + +![AI agents blocked by traditional payment systems](/tmpimagesx402/x402_ai_agents.png) + +## Real-World Impact + +These limitations have real consequences: + +### For Developers +- Cannot monetize APIs effectively +- Forced into subscription models +- High payment processing overhead +- Limited business model flexibility + +### For Users +- Must prepay for uncertain value +- Create accounts for one-time use +- Share payment details with many services +- Pay for unused capacity + +### For AI Builders +- Cannot create autonomous payment systems +- Limited to pre-approved payment rails +- Unable to enable AI-to-AI commerce +- Forced into complex workarounds + +## The Need for a New Approach + +Traditional payment systems were designed for a different era—before micropayments, before API economies, and before AI agents. We need a payment protocol that: + +1. **Eliminates Account Requirements**: Instant, permissionless access +2. **Supports Micropayments**: Economically viable payments of any size +3. **Enables Automation**: AI agents can pay autonomously +4. **Settles Instantly**: No 2-7 day delays +5. **Charges Fairly**: No percentage fees or high fixed costs +6. **Works with HTTP**: Native integration with web infrastructure + +This is exactly what the x402 protocol provides. + +## Summary + +Traditional payment systems create insurmountable barriers for modern digital commerce through account requirements, high fees, settlement delays, and automation limitations. These systems make micropayments impossible, force developers into suboptimal business models, and prevent AI agents from participating in the economy. The x402 protocol addresses all of these limitations by providing instant, permissionless, HTTP-native payments with minimal fees. diff --git a/content/academy/x402-payment-infrastructure/02-introduction/03-use-cases.mdx b/content/academy/x402-payment-infrastructure/02-introduction/03-use-cases.mdx new file mode 100644 index 00000000000..ec593e6b36a --- /dev/null +++ b/content/academy/x402-payment-infrastructure/02-introduction/03-use-cases.mdx @@ -0,0 +1,374 @@ +--- +title: x402 Use Cases +description: Exploring practical applications of the x402 protocol for AI agents, micropayments, and content monetization. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: Lightbulb +--- + +## Overview + +The x402 protocol unlocks entirely new business models and use cases that were previously impossible with traditional payment systems. By enabling instant, permissionless micropayments, x402 creates opportunities across AI agents, content creation, API monetization, and more. + +## AI Agent Payments + +AI agents represent one of the most compelling use cases for x402, enabling autonomous machine-to-machine commerce. + +### Autonomous Resource Access + +AI agents can operate autonomously in the x402 economy without human intervention. This enables entirely new capabilities: + +- **Real-Time Data Feeds**: Pay for market data, weather information, or sensor readings on-demand +- **Compute Resources**: Purchase processing power dynamically based on workload needs +- **Premium APIs**: Access services without pre-approval or account creation +- **Training Datasets**: Acquire machine learning data through pay-per-use models +- **Cloud Services**: Utilize infrastructure with simple, transparent pricing + +This fundamentally transforms how AI systems interact with digital resources and services. + +**Example Scenario**: +``` +An AI agent analyzing market trends needs real-time financial data. + +Traditional Approach (Impossible): +1. Agent would need to create account (can't complete CAPTCHA) +2. Agent would need to complete KYC (can't verify identity) +3. Agent would need to subscribe monthly (can't predict usage) +4. Agent needs human intervention for setup + +x402 Approach (Seamless): +1. Agent sends HTTP request for data +2. Server responds with 402 "Payment Required" +3. Agent automatically pays $0.0001 in USDC +4. Data returned in 2 seconds +``` + +![x402 payment flow for AI agents](/tmpimagesx402/payment%20flow.png) + +### Inter-Agent Commerce + +x402 enables a thriving AI-to-AI economy where specialized agents monetize their services to other agents: + +- **Data Agents**: Sell curated datasets to analysis agents +- **Compute Agents**: Rent processing power to resource-constrained systems +- **Specialized Agents**: Offer expert analysis to general-purpose AI +- **Storage Agents**: Provide decentralized storage solutions to data-heavy applications + +This creates an entire autonomous machine-to-machine economy that traditional payment systems—with their KYC requirements and subscription models—could never support. + +### Dynamic Cost Optimization + +AI agents leverage x402's transparent pricing to intelligently manage costs: + +- **Price Comparison**: Compare rates across multiple service providers in real-time +- **Dynamic Switching**: Automatically move to better providers based on pricing and performance +- **Success-Based Payment**: Pay only for successful operations, not failed attempts +- **Value Optimization**: Balance cost and quality autonomously without human oversight +- **Budget Management**: Track spending and adjust resource usage automatically + +## Micropayment Business Models + +x402 makes micropayments economically viable, enabling pay-per-use models that were previously impossible. + +### Pay-Per-API-Request + +Developers can charge minimal amounts per API call: +- \$0.0001 per geocoding request +- \$0.001 per image processing operation +- \$0.01 per AI inference call +- \$0.10 per complex computation + +These micro-amounts are economically viable with x402's ultra-low transaction costs, unlike traditional payment systems where fees exceed the payment value itself. + +![Traditional vs x402 payment economics](/tmpimagesx402/problemsolved.png) + +**Economics Comparison**: +``` +Traditional Payment: +API request value: $0.001 +Processing fee: $0.30 +Net to merchant: -$0.299 (99,700% loss) + +x402 Payment: +API request value: $0.001 +Gas fee: $0.0001 +Net to merchant: $0.0009 (10% fee, sustainable) +``` + +This dramatic difference makes micropayments economically viable for the first time, enabling entirely new business models that were impossible with traditional payment infrastructure. + +### Usage-Based Infrastructure Pricing + +Services can charge exactly for what users consume: +- Cloud storage: \$0.0001 per MB per day +- Compute time: \$0.001 per CPU-minute +- Network bandwidth: \$0.00001 per MB transferred +- Database queries: \$0.0001 per query + +Users only pay for actual consumption, not estimated capacity. + +## Content Monetization + +x402 enables flexible, granular monetization for content creators through pay-per-content models. + +### Flexible Pricing Models + +Instead of forcing \$10/month subscriptions, creators can implement various pricing strategies: + +**Per-Content Pricing:** +- Articles and blog posts: \$0.05-\$0.25 per read +- Videos and podcasts: \$0.10-\$0.50 per view +- Tutorials and courses: \$0.25-\$2.00 per module +- Research papers: \$0.50-\$5.00 per download + +**Tiered Access:** +- Free tier: Basic content available to all +- Standard tier (\$0.10-\$0.25): Regular premium content +- Premium tier (\$0.50-\$1.00): In-depth analysis and exclusive content +- Expert tier (\$2.00+): Specialized research and consulting + +**Dynamic Pricing:** +- Demand-based: Higher prices for trending or popular content +- Time-based: Lower prices for older content or off-peak access +- User-based: Discounts for frequent readers or bulk purchases +- Value-based: Each piece priced according to depth and complexity + +**Benefits for Users:** +- Pay only for content you actually consume +- Try individual pieces before committing to subscriptions +- No recurring charges or cancellation hassles +- Granular control over spending + +**Benefits for Creators:** +- Monetize every piece of content, not just loyal subscribers +- Lower barrier to first payment increases conversion +- Revenue from casual readers who won't subscribe +- Direct payments without platform fees taking 30-50% + +## API Monetization + +Developers can monetize APIs in ways that were previously impossible. + +### No-Subscription API Access + +Instead of forcing users into monthly plans: +- Pay per request +- No minimum commitment +- No API key management +- No account creation + +**Example**: +``` +Image Processing API + +Traditional Model: +- Free: 100 requests/month (insufficient for many users) +- Pro: $29/month for 10,000 requests (too expensive for casual users) +- Enterprise: Custom pricing (high commitment) + +x402 Model: +- $0.001 per request +- No monthly fee +- Pay exactly for what you use +- Instant activation +``` + +### Tiered Service Quality + +APIs can implement sophisticated tiered pricing based on service quality and performance guarantees: + +- **Standard Tier**: $0.001 per request with best-effort latency +- **Priority Tier**: $0.005 per request with guaranteed sub-100ms response times +- **Exclusive Tier**: $0.01 per request with dedicated resources for critical workloads +- **Dynamic Adjustment**: Users pay precisely for the quality they need +- **Flexible Spending**: Adjust tier based on current requirements and budget + +This flexibility allows users to balance cost and performance dynamically. + +### Metered Resource Access + +Beyond simple per-request pricing, APIs can implement metered charging based on actual consumption: + +- **Computational Complexity**: Heavy computations cost more than simple queries +- **Response Time Guarantees**: Premium pricing for faster processing +- **Data Volume**: Charges scale with amount of data returned +- **Result Accuracy**: Higher precision costs more than approximations +- **Fair Pricing**: Natural market incentives for efficient API design and usage + +## Web3 and DeFi Applications + +x402 integrates seamlessly with blockchain-based applications, enabling new monetization models for decentralized services. + +### Decentralized Data Markets + +Oracle services and price feeds can monetize their infrastructure through granular pricing: + +- **Per-Query Pricing**: Charge for each data request instead of subscriptions +- **Update Billing**: Bill per data refresh or update cycle +- **Historical Data**: Offer pay-per-record access to historical datasets +- **Real-Time Streams**: Price streaming data per second of access +- **Lower Barriers**: Make data accessible to smaller consumers + +This aligns payment directly with value delivered. + +### Account-Free DApp Access + +Decentralized applications can offer premium features through instant micropayments: + +- **Portfolio Tracking**: $0.10 per analysis +- **Trade Simulation**: $0.50 per backtest execution +- **Yield Optimization**: $1.00 per strategy execution +- **Risk Analysis**: $0.25 per assessment +- **No Authentication**: No user accounts or complex authentication required + +Users pay only for the specific analyses they need, when they need them. + +### Cross-Chain Service Access + +x402's payment layer enables seamless cross-chain transactions: + +- **Accept on Multiple Chains**: Receive payments on one blockchain (like Avalanche) +- **Operate on Any Chain**: Run services on a different blockchain +- **No Bridge Complexity**: Avoid complex bridge infrastructure +- **No Wrapped Tokens**: Direct payment without token wrapping +- **Seamless Experience**: Users don't worry about chain compatibility + +## Enterprise Applications + +x402 transforms B2B interactions by enabling frictionless, usage-based commerce between organizations. + +### Inter-Company API Access + +Companies can share APIs across organizational boundaries without complex contracts: + +- **Instant Integration**: Partners connect and start using APIs immediately +- **Exact Usage Billing**: Charge for actual consumption, not estimated capacity +- **Real-Time Settlement**: Payments settle instantly, no invoicing delays +- **No Procurement Cycles**: Eliminate lengthy B2B sales processes +- **Fair Compensation**: Providers paid based on actual value delivered + +This eliminates the overhead of traditional B2B sales cycles. + +### Microservice Monetization + +Internal services can implement chargeback models based on actual consumption: + +- **Department Billing**: Share infrastructure with automatic usage-based billing +- **Accurate Cost Allocation**: Track spending without manual overhead +- **Real-Time Monitoring**: Budget tracking and alerts in real-time +- **Resource Optimization**: Identify cost-saving opportunities automatically +- **Shared Infrastructure**: Business units collaborate efficiently with clear accounting + +Organizations can optimize resource utilization and control costs precisely. + +### Data Marketplace + +Enterprises can monetize proprietary data assets through micropayments: + +- **Real-Time Intelligence**: Sell live business data per query +- **Historical Transactions**: Offer historical data on pay-per-record basis +- **Market Research**: Monetize research findings per download +- **Industry Benchmarks**: Share benchmarks per dataset accessed +- **New Revenue Streams**: Generate income from existing data infrastructure + +## Novel Use Cases + +x402 unlocks entirely new possibilities across emerging technology sectors. + +### Pay-Per-Minute Cloud Resources + +Cloud providers can implement true usage-based pricing with granular billing: + +- **VM Billing**: Per-second billing for virtual machines +- **GPU Access**: On-demand GPU charged by the minute +- **Serverless Functions**: Billed per invocation +- **Storage**: Priced by the millisecond of usage +- **No Over-Provisioning**: Customers pay only for what they consume + +This granular pricing eliminates waste while enabling cost-effective access to expensive compute resources. + +### Knowledge Economy + +AI and knowledge services can monetize at unprecedented granularity: + +- **Expert Systems**: Charge per query for specialized knowledge +- **Language Models**: Bill per token generated +- **Image Generators**: Price per image creation +- **Code Assistants**: Charge per suggestion or completion +- **Accessible AI**: Users get advanced capabilities without expensive subscriptions + +This enables sustainable business models for AI services. + +### Internet of Things (IoT) + +x402 enables autonomous machine-to-machine payments in IoT ecosystems: + +- **Bandwidth Payments**: Devices independently pay for network connectivity +- **Data Processing**: Sensors purchase processing capacity as needed +- **Control Signals**: Actuators pay for control commands +- **Packet Delivery**: Networks charge per packet delivered +- **Self-Sustaining Networks**: Devices manage economic relationships autonomously + +This creates IoT networks that operate without human payment intervention. + +### Gaming and Virtual Worlds + +Virtual economies can implement sophisticated payment models: + +- **Pay-Per-Session**: Gaming charged by time played +- **Item Rentals**: Temporary access to in-game items +- **Virtual Real Estate**: Access fees for digital property +- **NPC Services**: Non-player characters that charge for services +- **Dynamic Markets**: Value exchange mirrors real-world economics + +This creates more realistic and dynamic virtual economies. + +## Economic Impact + +The x402 protocol enables a **true pay-per-use economy**: + +### For Consumers + +Consumers benefit from a payment model that eliminates waste and commitment: + +- **No Unused Capacity**: Pay only for services actually consumed +- **Try Before Committing**: Test services without long-term subscriptions +- **Granular Cost Control**: Track spending at the individual transaction level +- **No Subscription Fatigue**: Eliminate managing multiple recurring payments +- **Flexible Usage**: Scale consumption up or down without penalties + +This creates a truly user-centric payment experience. + +### For Developers + +Developers gain unprecedented flexibility in monetizing their services: + +- **Monetize Any Service**: From tiny APIs to large platforms, any size works +- **No Processing Overhead**: Minimal fees don't eat into profit margins +- **Instant Revenue**: Payments settle in real-time, not days later +- **Flexible Pricing**: Implement any strategy from simple to complex tiered models +- **No Infrastructure Limits**: Payment system doesn't constrain business models + +Revenue recognition happens instantly as payments settle in real-time. + +### For AI Builders + +AI builders can create truly autonomous economic systems: + +- **Autonomous Commerce**: AI agents operate independently without human intervention +- **Self-Sustaining Agents**: Create agents that manage their own budgets +- **AI-to-AI Marketplaces**: Build platforms where specialized services trade automatically +- **No Authorization Friction**: Eliminate human approval from machine transactions +- **Budget-Aware Systems**: AI optimizes spending based on value and constraints + +This enables the first truly autonomous AI economy. + +## Summary + +The x402 protocol unlocks use cases that span AI agent commerce, micropayment business models, content monetization, API access, Web3 applications, enterprise solutions, and novel applications across industries. By making micropayments economically viable and enabling autonomous payments, x402 creates opportunities for entirely new digital economies built on instant, permissionless transactions. + +## Additional Resources + +- [x402 Whitepaper](https://www.x402.org/x402-whitepaper.pdf) - Technical specification and use cases +- [x402 GitHub Repository](https://github.com/coinbase/x402) - Open source implementation and examples +- [PayAI Documentation](https://docs.payai.network) - Facilitator integration guides From 3833c845772a8226b562c2255ed80e3771d8f8b1 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Sun, 9 Nov 2025 16:56:41 +0100 Subject: [PATCH 08/30] add the payment flow on the technical architecture chapter --- .../01-payment-flow.mdx | 359 ++++++++++++++++++ 1 file changed, 359 insertions(+) create mode 100644 content/academy/x402-payment-infrastructure/03-technical-architecture/01-payment-flow.mdx diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/01-payment-flow.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/01-payment-flow.mdx new file mode 100644 index 00000000000..39214bb46c8 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/01-payment-flow.mdx @@ -0,0 +1,359 @@ +--- +title: x402 Payment Flow +description: Understanding the complete payment cycle from request to settlement. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: ArrowRightLeft +--- + +## The 4-Step Core Payment Flow + +The x402 protocol operates through a simple yet powerful 4-step flow that enables instant, permissionless payments: + +### Step 1: Client Requests Resource + +A client (user, application, or AI agent) sends an HTTP GET request to access a resource: + +```http +GET /api/premium-data HTTP/1.1 +Host: example.com +``` + +This is a standard HTTP request—nothing special required from the client at this stage. + +### Step 2: Server Returns 402 Payment Required + +Instead of returning the requested content, the server responds with HTTP status code 402 "Payment Required" and a JSON body containing payment requirements: + +```http +HTTP/1.1 402 Payment Required +Content-Type: application/json + +{ + "x402Version": 1, + "accepts": [ + { + "scheme": "exact", + "network": "avalanche-fuji", + "maxAmountRequired": "10000", + "resource": "/api/premium-data", + "description": "Access to premium data API", + "payTo": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", + "asset": "0x5425890298aed601595a70AB815c96711a31Bc65", + "maxTimeoutSeconds": 60 + } + ], + "error": "X-PAYMENT header is required" +} +``` + +This response tells the client: +- Payment is required to access this resource +- The maximum amount needed (10000 base units = 0.01 USDC) +- Where to send payment (`payTo` address) +- Which blockchain to use (`avalanche-fuji`) +- Which token contract to use (`asset`) +- Payment scheme to use (`exact` = EIP-3009) + +### Step 3: Client Retries Request with Signed Payment + +The client creates and signs a payment authorization, then retries the request with the `X-PAYMENT` header: + +```http +GET /api/premium-data HTTP/1.1 +Host: example.com +X-PAYMENT: eyJ4NDAyVmVyc2lvbiI6MSwic2NoZW1lIjoiZXhhY3QiLCJuZXR3b3JrIjoiYXZhbGFuY2hlLWZ1amkiLCJwYXlsb2FkIjp7InNpZ25hdHVyZSI6IjB4MTIzNC4uLiIsImF1dGhvcml6YXRpb24iOnsiZnJvbSI6IjB4MTIzNC4uLiIsInRvIjoiMHg3NDJkMzUuLi4iLCJ2YWx1ZSI6IjEwMDAwIiwidmFsaWRBZnRlciI6IjE3NDA2NzIwODkiLCJ2YWxpZEJlZm9yZSI6IjE3NDA2NzIxNTQiLCJub25jZSI6IjB4MzQ1Ni4uLiJ9fX0= +``` + +The client does NOT submit a blockchain transaction. The authorization is gasless—the server or facilitator will submit it. For details on the `X-PAYMENT` header structure, see [HTTP Headers](./02-http-headers#x-payment-header). + +### Step 4: Server Verifies, Settles, and Returns Resource + +The server (potentially with a facilitator's help): + +1. **Verifies** the EIP-712 signature is valid +2. **Settles** the payment by submitting the authorization to the blockchain +3. **Returns** the requested resource with an `X-PAYMENT-RESPONSE` header: + +```http +HTTP/1.1 200 OK +Content-Type: application/json +X-PAYMENT-RESPONSE: eyJzdWNjZXNzIjp0cnVlLCJ0cmFuc2FjdGlvbiI6IjB4OGYzZC4uLiIsIm5ldHdvcmsiOiJhdmFsYW5jaGUtZnVqaSIsInBheWVyIjoiMHgxMjM0Li4uIiwiZXJyb3JSZWFzb24iOm51bGx9 + +{ + "data": "...premium content..." +} +``` + +The `X-PAYMENT-RESPONSE` header (decoded) contains: +```json +{ + "success": true, + "transaction": "0x8f3d1a2b4c5e6f7a...", + "network": "avalanche-fuji", + "payer": "0x1234567890abcdef...", + "errorReason": null +} +``` + +The client now has access to the resource, and the entire cycle completed in approximately 2 seconds. + +## Detailed 12-Step Technical Flow + +For a deeper understanding, here's the complete technical flow including facilitator interactions: + +![Detailed x402 payment flow](/tmpimagesx402/paymentflow2.png) + +### Phase 1: Initial Request + +**Step 1**: Client sends GET request to server + +```http +GET /api/data?query=market-trends HTTP/1.1 +Host: api.example.com +Accept: application/json +``` + +**Step 2**: Server returns 402 "Payment required" with payment details + +```http +HTTP/1.1 402 Payment Required +Content-Type: application/json + +{ + "x402Version": 1, + "accepts": [{ + "scheme": "exact", + "network": "avalanche-fuji", + "maxAmountRequired": "10000", + "payTo": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", + "asset": "0x5425890298aed601595a70AB815c96711a31Bc65", + "resource": "/api/data" + }], + "error": "X-PAYMENT header is required" +} +``` + +### Phase 2: Payment Creation + +**Step 3**: Client selects payment requirements and creates payment payload + +The client chooses from the `accepts` array and creates authorization: + +```javascript +// Select payment option +const paymentReq = response.data.accepts[0]; + +// Create authorization object (EIP-3009 format) +const authorization = { + from: userWalletAddress, + to: paymentReq.payTo, + value: paymentReq.maxAmountRequired, + validAfter: Math.floor(Date.now() / 1000).toString(), + validBefore: (Math.floor(Date.now() / 1000) + 300).toString(), + nonce: ethers.hexlify(ethers.randomBytes(32)) +}; + +// Sign authorization with EIP-712 +const signature = await wallet.signTypedData(domain, types, authorization); + +// Create payment payload +const paymentPayload = { + x402Version: 1, + scheme: paymentReq.scheme, + network: paymentReq.network, + payload: { + signature: signature, + authorization: authorization + } +}; +``` + +### Phase 3: Payment Submission and Verification + +**Step 4**: Client includes X-PAYMENT header with request + +```http +GET /api/data?query=market-trends HTTP/1.1 +Host: api.example.com +X-PAYMENT: +``` + +**Step 5**: Server verifies payload (locally or via facilitator) + +The server validates the EIP-712 signature and authorization: + +```javascript +// Server can verify locally or use facilitator +POST https://facilitator.payai.network/verify +{ + "x402Version": 1, + "scheme": "exact", + "network": "avalanche-fuji", + "payload": { + "signature": "0x1234...", + "authorization": {...} + } +} +``` + +**Step 6**: Facilitator validates and returns verification response + +The facilitator checks: +- ✓ Is the EIP-712 signature valid? +- ✓ Is the authorization correctly formatted? +- ✓ Is the `validBefore` timestamp still valid? +- ✓ Has this nonce been used before? + +Response: +```json +{ + "isValid": true, + "invalidReason": null +} +``` + +**Step 7**: Server fulfills request if valid, returns 402 if invalid + +If verification passes, server proceeds to settlement. If not, returns new 402 response. + +### Phase 4: Blockchain Settlement + +**Step 8**: Server settles payment (directly or via facilitator) + +The server submits the signed authorization to the blockchain: + +```javascript +// Server uses facilitator to settle +POST https://facilitator.payai.network/settle +{ + "x402Version": 1, + "scheme": "exact", + "network": "avalanche-fuji", + "payload": { + "signature": "0x1234...", + "authorization": { + "from": "0x1234...", + "to": "0x742d35...", + "value": "10000", + "validAfter": "1740672089", + "validBefore": "1740672154", + "nonce": "0x3456..." + } + } +} +``` + +**Step 9**: Facilitator submits to blockchain + +The facilitator calls the USDC contract's `transferWithAuthorization` function (EIP-3009): + +```solidity +// USDC.transferWithAuthorization on Avalanche Fuji +transferWithAuthorization( + from: 0x1234..., // Payer + to: 0x742d35..., // Recipient + value: 10000, // 0.01 USDC (6 decimals) + validAfter: 1740672089, + validBefore: 1740672154, + nonce: 0x3456..., + v: 27, + r: 0x..., + s: 0x... +) +``` + +**Step 10**: Blockchain confirms transaction + +Avalanche's sub-second finality confirms the transaction in \<1 second. + +### Phase 5: Settlement Response + +**Step 11**: Facilitator returns payment execution response + +The facilitator returns settlement status to the server: + +```json +{ + "success": true, + "error": null, + "txHash": "0x8f3d1a2b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a...", + "networkId": "avalanche-fuji" +} +``` + +**Step 12**: Server returns resource with X-PAYMENT-RESPONSE header + +```http +HTTP/1.1 200 OK +Content-Type: application/json +X-PAYMENT-RESPONSE: + +{ + "marketTrends": [...] +} +``` + +The `X-PAYMENT-RESPONSE` (decoded): +```json +{ + "success": true, + "transaction": "0x8f3d1a2b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a...", + "network": "avalanche-fuji", + "payer": "0x1234567890abcdef...", + "errorReason": null +} +``` + +## Flow Timing + +The entire flow completes remarkably fast: + +| Step | Duration | Cumulative | +|------|----------|------------| +| 1-2: Initial request + 402 response | ~100ms | 100ms | +| 3-4: Payment method selection | ~200ms | 300ms | +| 5-7: Payment submission + verification | ~300ms | 600ms | +| 8-10: Blockchain transaction + confirmation | ~1400ms | 2000ms | +| 11-12: Settlement + content delivery | ~100ms | 2100ms | + +**Total Time: ~2 seconds** from initial request to content delivery. + +## Key Design Principles + +### 1. HTTP-Native + +x402 uses standard HTTP headers and status codes. No custom protocols or specialized infrastructure required. + +### 2. Facilitator-Mediated + +Facilitators handle the complex blockchain interactions, making integration simple for merchants. + +### 3. Blockchain-Settled + +All payments settle on-chain, providing: +- Transparency +- Immutability +- Cryptographic proof +- Decentralization + +### 4. Stateless Protocol + +Each payment is independent. No sessions, no stored state, no account management required. + +### 5. Idempotent Requests + +Payment proofs can only be used once. Replay attacks are prevented by on-chain verification. + +For comprehensive security details, see [Security Considerations](./05-security-considerations). + +## Summary + +The x402 payment flow transforms HTTP 402 into a functional payment request mechanism through a 4-step cycle (or 12-step detailed flow) that completes in approximately 2 seconds. By using facilitators to mediate blockchain interactions and leveraging Avalanche's fast finality, x402 makes instant, permissionless payments a reality while maintaining security and simplicity. + +## Next Steps + +In the following lessons, we'll dive deeper into: +- HTTP headers and their structure +- The facilitator's role in detail +- Blockchain settlement mechanics From d3896c9f20659b5eec141a62ea6e42cc697b556a Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Sun, 9 Nov 2025 17:55:56 +0100 Subject: [PATCH 09/30] add the HTTP headers on the technical architecture chapter --- .../02-http-headers.mdx | 417 ++++++++++++++++++ 1 file changed, 417 insertions(+) create mode 100644 content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-headers.mdx diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-headers.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-headers.mdx new file mode 100644 index 00000000000..acde84fe374 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-headers.mdx @@ -0,0 +1,417 @@ +--- +title: HTTP Headers in x402 +description: Understanding X-PAYMENT and X-PAYMENT-RESPONSE headers for payment communication. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: Code +--- + +## Overview + +The x402 protocol uses custom HTTP headers to communicate payment requirements and verification between clients and servers. These headers make payments a native part of HTTP communication. + +## HTTP 402 Payment Required Response + +When a server requires payment for a resource, it responds with **HTTP 402 Payment Required** and includes payment details in the **response body** as JSON (not in a custom header). + +### Response Structure + +```http +HTTP/1.1 402 Payment Required +Content-Type: application/json + +{ + "x402Version": 1, + "accepts": [ + { + "scheme": "exact", + "network": "avalanche-fuji", + "maxAmountRequired": "10000", + "resource": "/api/premium-data", + "description": "Real-time market analysis", + "payTo": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", + "asset": "0x5425890298aed601595a70AB815c96711a31Bc65", + "maxTimeoutSeconds": 60 + } + ], + "error": "X-PAYMENT header is required" +} +``` + +### Field Definitions + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `x402Version` | number | Yes | Protocol version (currently 1) | +| `accepts` | array | Yes | Array of accepted payment options | +| `error` | string | No | Error message explaining why payment is required | + +### Payment Requirements Object (`accepts` array) + +Each payment option in the `accepts` array contains: + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `scheme` | string | Yes | Payment scheme | +| `network` | string | Yes | Blockchain network identifier | +| `maxAmountRequired` | string | Yes | Maximum payment amount required (in token base units) | +| `resource` | string | Yes | Resource path being requested | +| `payTo` | string | Yes | Recipient blockchain address | +| `asset` | string | Yes | Token contract address | +| `maxTimeoutSeconds` | number | No | Maximum time to complete payment | +| `description` | string | No | Human-readable description | + +### Amount Specification + +Amounts are always strings representing **base units** (smallest denomination): + +```javascript +// For USDC (6 decimals): 10000 = 0.01 USDC +"maxAmountRequired": "10000" + +// For USDC (6 decimals): 1000000 = 1.0 USDC +"maxAmountRequired": "1000000" +``` + +**Important**: USDC has 6 decimals, so: +- 1 USDC = 1,000,000 base units +- 0.01 USDC = 10,000 base units +- 0.0001 USDC = 100 base units + +### Asset (Token Contract Address) + +The `asset` field contains the smart contract address of the payment token: + +```javascript +// USDC on Avalanche Fuji testnet +"asset": "0x5425890298aed601595a70AB815c96711a31Bc65" + +// USDC on Avalanche C-Chain mainnet +"asset": "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E" + +// USDC on Ethereum mainnet +"asset": "0xA0b86991C6218b36c1d19D4a2e9Eb0cE3606EB48" +``` + +**Note**: The asset is identified by contract address, not by symbol like "USDC". + +### Network Identifiers + +Standard network identifiers for Avalanche and other chains: + +```javascript +"network": "avalanche-c-chain" // Avalanche C-Chain Mainnet +"network": "avalanche-fuji" // Avalanche Fuji Testnet +"network": "ethereum-mainnet" // Ethereum Mainnet +"network": "base-mainnet" // Base Mainnet +"network": "base-sepolia" // Base Sepolia Testnet +``` + +### Payment Schemes + +The `scheme` field specifies how payments are settled. x402 supports multiple schemes to handle different payment models: + +**`exact` Scheme (Implemented)**: +- Fixed payment amount known upfront +- Use cases: Pay $0.10 to read an article, fixed-price API calls +- Implementations: EVM (EIP-3009), Solana, Sui +- Example: `"scheme": "exact", "maxAmountRequired": "100000"` + +**`up-to` Scheme (Proposed)**: +- Variable payment based on resource consumption +- Use cases: LLM token-based pricing, pay-per-token generation, usage-metered services +- Status: Not yet implemented - under development +- Example use: Pay up to $1.00, actual charge depends on tokens consumed + +The protocol is designed to be extensible, allowing new schemes to be added as payment models evolve. Current implementations focus on the `exact` scheme across multiple blockchains. + +**Reference**: See [x402 Schemes Specification](https://github.com/coinbase/x402/tree/main/specs/schemes) for technical details. + +### Multiple Payment Options + +Servers can offer multiple payment options (different networks or tokens): + +```json +{ + "x402Version": 1, + "accepts": [ + { + "scheme": "exact", + "network": "avalanche-fuji", + "maxAmountRequired": "10000", + "payTo": "0x742d35...", + "asset": "0x5425890...", + "resource": "/api/data" + }, + { + "scheme": "exact", + "network": "base-sepolia", + "maxAmountRequired": "10000", + "payTo": "0x742d35...", + "asset": "0x036CbD...", + "resource": "/api/data" + } + ] +} +``` + +## X-PAYMENT Header + +When making a payment, the client includes the `X-PAYMENT` header with the request. This header contains a **base64-encoded JSON payload** with the payment authorization. + +### Header Structure + +```http +GET /api/premium-data HTTP/1.1 +Host: example.com +X-PAYMENT: +``` + +### Payment Payload Structure (before base64 encoding) + +```json +{ + "x402Version": 1, + "scheme": "exact", + "network": "avalanche-fuji", + "payload": { + "signature": "0x1234567890abcdef...", + "authorization": { + "from": "0x1234567890abcdef1234567890abcdef12345678", + "to": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", + "value": "10000", + "validAfter": "1740672089", + "validBefore": "1740672154", + "nonce": "0x3456789012345678901234567890123456789012345678901234567890123456" + } + } +} +``` + +### Field Definitions + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `x402Version` | number | Yes | Protocol version (currently 1) | +| `scheme` | string | Yes | Payment scheme ("exact" for EVM) | +| `network` | string | Yes | Blockchain network used | +| `payload` | object | Yes | Scheme-specific payment data | + +### Payload for "exact" Scheme (EVM Chains) + +The payload for EVM chains using the "exact" scheme contains: + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `signature` | string | Yes | EIP-712 signature of the authorization | +| `authorization` | object | Yes | Payment authorization details | + +### Authorization Object + +The authorization object follows EIP-3009 TransferWithAuthorization: + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `from` | string | Yes | Payer's wallet address | +| `to` | string | Yes | Recipient's wallet address | +| `value` | string | Yes | Amount in token base units | +| `validAfter` | string | Yes | Unix timestamp (seconds) - payment valid after this time | +| `validBefore` | string | Yes | Unix timestamp (seconds) - payment expires after this time | +| `nonce` | string | Yes | Unique 32-byte hex string for replay protection | + +### EIP-712 Signature + +The signature field contains an EIP-712 signature of the authorization object: + +```javascript +// The user's wallet signs the authorization using EIP-712 +const signature = await wallet.signTypedData({ + domain: { + name: "USD Coin", + version: "2", + chainId: 43113, // Avalanche Fuji + verifyingContract: "0x5425890298aed601595a70AB815c96711a31Bc65" + }, + types: { + TransferWithAuthorization: [ + { name: "from", type: "address" }, + { name: "to", type: "address" }, + { name: "value", type: "uint256" }, + { name: "validAfter", type: "uint256" }, + { name: "validBefore", type: "uint256" }, + { name: "nonce", type: "bytes32" } + ] + }, + primaryType: "TransferWithAuthorization", + message: authorization +}); +``` + +This signature: +- ✓ Proves user consent without requiring a transaction +- ✓ Cannot be forged (cryptographically secure) +- ✓ Includes all payment details in the signature +- ✓ Enables gasless payments (server submits the transaction) + +### Complete Example + +```javascript +// 1. Client receives 402 response with payment requirements +const paymentReq = response.data.accepts[0]; + +// 2. Client creates authorization object +const authorization = { + from: userAddress, + to: paymentReq.payTo, + value: paymentReq.maxAmountRequired, + validAfter: Math.floor(Date.now() / 1000).toString(), + validBefore: (Math.floor(Date.now() / 1000) + 300).toString(), // 5 minutes + nonce: ethers.randomBytes(32) +}; + +// 3. User signs authorization +const signature = await wallet.signTypedData(...); + +// 4. Client creates payment payload +const paymentPayload = { + x402Version: 1, + scheme: paymentReq.scheme, + network: paymentReq.network, + payload: { + signature: signature, + authorization: authorization + } +}; + +// 5. Base64 encode and send +const encoded = btoa(JSON.stringify(paymentPayload)); +await fetch('/api/premium-data', { + headers: { + 'X-PAYMENT': encoded + } +}); +``` + +## X-PAYMENT-RESPONSE Header + +After verifying and settling payment, the server includes the `X-PAYMENT-RESPONSE` header in its response. This header is also **base64-encoded JSON**. + +### Header Structure + +```http +HTTP/1.1 200 OK +Content-Type: application/json +X-PAYMENT-RESPONSE: +``` + +### Settlement Response Structure (before base64 encoding) + +```json +{ + "success": true, + "transaction": "0x8f3d1a2b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a", + "network": "avalanche-fuji", + "payer": "0x1234567890abcdef1234567890abcdef12345678", + "errorReason": null +} +``` + +### Field Definitions + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `success` | boolean | Yes | Whether settlement was successful | +| `transaction` | string | Yes (if success) | Transaction hash on blockchain | +| `network` | string | Yes | Network where transaction was settled | +| `payer` | string | Yes | Address of the payer | +| `errorReason` | string | Yes (if failed) | Error message if settlement failed | + +### Success Response + +When payment is successfully verified and settled: + +```json +{ + "success": true, + "transaction": "0x8f3d1a2b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a", + "network": "avalanche-fuji", + "payer": "0x1234567890abcdef1234567890abcdef12345678", + "errorReason": null +} +``` + +The transaction hash can be used to: +- ✓ Verify the transaction on a block explorer +- ✓ Check transaction details (amount, timestamp, block number) +- ✓ Provide proof of payment to users +- ✓ Audit payment history + +### Payment Failure Response + +When payment verification or settlement fails, the server returns **HTTP 402 Payment Required** with both a JSON body containing payment requirements and an `X-PAYMENT-RESPONSE` header with failure details: + +```http +HTTP/1.1 402 Payment Required +Content-Type: application/json +X-PAYMENT-RESPONSE: eyJzdWNjZXNzIjpmYWxzZSwidHJhbnNhY3Rpb24iOm51bGwsIm5ldHdvcmsiOiJhdmFsYW5jaGUtZnVqaSIsInBheWVyIjoiMHgxMjM0NTY3ODkwYWJjZGVmMTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4IiwiZXJyb3JSZWFzb24iOiJJbnN1ZmZpY2llbnQgYXV0aG9yaXphdGlvbiBhbW91bnQifQ== + +{ + "x402Version": 1, + "accepts": [{ + "scheme": "exact", + "network": "avalanche-fuji", + "maxAmountRequired": "10000", + "payTo": "0x742d35...", + "asset": "0x5425890...", + "resource": "/api/data" + }], + "error": "Insufficient payment: required 10000, received 5000" +} +``` + +The `X-PAYMENT-RESPONSE` header (when decoded) contains: + +```json +{ + "success": false, + "transaction": null, + "network": "avalanche-fuji", + "payer": "0x1234567890abcdef1234567890abcdef12345678", + "errorReason": "Insufficient authorization amount" +} +``` + +**Common error reasons**: +- `"Insufficient authorization amount"` - Payment amount too low +- `"Authorization expired"` - validBefore timestamp passed +- `"Invalid signature"` - Signature verification failed +- `"Nonce already used"` - Replay attack detected +- `"Insufficient balance"` - Payer doesn't have enough tokens + +**Why both body and header?** +- **JSON body**: Provides new payment requirements so the client can retry +- **X-PAYMENT-RESPONSE header**: Communicates what went wrong with the settlement attempt + +## Header Best Practices + +### For Servers + +1. **Support multiple networks**: Include options for different blockchains in `accepts` array +2. **Set reasonable timeouts**: Use `maxTimeoutSeconds` to prevent stale payments +3. **Use base units consistently**: Always specify amounts in smallest token denomination +4. **Validate signatures carefully**: Use EIP-712 verification libraries +5. **Implement replay protection**: Track used nonces to prevent double-spending + +### For Clients + +1. **Decode and parse carefully**: Base64 decode and JSON parse all headers +2. **Check authorization expiry**: Don't sign authorizations with past `validBefore` timestamps +3. **Generate unique nonces**: Use cryptographically secure random 32-byte values +4. **Store transaction receipts**: Keep `X-PAYMENT-RESPONSE` data for proof of payment +5. **Handle errors gracefully**: Implement retry logic with exponential backoff + +For detailed security considerations including signature validation, nonce-based replay prevention, and authorization timing validation, see [Security Considerations](./05-security-considerations) + +## Summary + +The x402 protocol uses HTTP 402 responses with JSON bodies and two custom HTTP headers (`X-PAYMENT` and `X-PAYMENT-RESPONSE`) to enable payment communication. When a payment is required, the server responds with HTTP 402 and a JSON body containing payment requirements. The client submits a signed authorization in the base64-encoded `X-PAYMENT` header. After settlement, the server returns the resource with an `X-PAYMENT-RESPONSE` header containing the transaction hash. All payloads are base64-encoded JSON structures following the EIP-3009 TransferWithAuthorization standard for secure, verifiable blockchain payments. From bbe6c0943796afdc313fcd799591c09c1355e1a1 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Sun, 9 Nov 2025 18:47:36 +0100 Subject: [PATCH 10/30] add facilitator role --- .../03-facilitator-role.mdx | 313 ++++++++++++++++++ 1 file changed, 313 insertions(+) create mode 100644 content/academy/x402-payment-infrastructure/03-technical-architecture/03-facilitator-role.mdx diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/03-facilitator-role.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/03-facilitator-role.mdx new file mode 100644 index 00000000000..0c10621130d --- /dev/null +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/03-facilitator-role.mdx @@ -0,0 +1,313 @@ +--- +title: The Facilitator Role +description: Understanding how facilitators enable seamless payment verification and settlement in x402. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: Users +--- + +## What is a Facilitator? + +A **facilitator** is a service that handles payment verification and blockchain settlement on behalf of merchants and clients in the x402 protocol. Facilitators act as trusted intermediaries that: + +- Verify payment authenticity +- Submit transactions to the blockchain +- Handle merchant whitelisting +- Manage settlement processes +- Provide developer tools and SDKs + +Think of facilitators as the "payment processors" of the x402 ecosystem—but unlike traditional processors, they charge minimal fees and settle instantly. + +## Why Facilitators Are Necessary + +While blockchain payments are permissionless, integrating them directly creates challenges: + +### Without Facilitators + +Merchants would need to: +- ❌ Run blockchain nodes +- ❌ Monitor transactions in real-time +- ❌ Handle gas price optimization +- ❌ Manage wallet infrastructure +- ❌ Implement replay attack prevention +- ❌ Build payment verification logic +- ❌ Handle multi-chain complexity + +### With Facilitators + +Merchants simply: +- ✅ Add one line of middleware code +- ✅ Configure payment amounts +- ✅ Receive instant verification +- ✅ Get automatic settlement +- ✅ Access multi-chain support +- ✅ Use simple REST APIs + +Facilitators abstract away blockchain complexity while maintaining the benefits of permissionless payments. + +## Core Facilitator Responsibilities + +### 1. Merchant Whitelisting + +Facilitators maintain a whitelist of approved merchants to prevent fraud: + +```javascript +// Merchant registration +POST /facilitator/register +{ + "merchantAddress": "0x742d35...", + "businessName": "Premium API Service", + "website": "https://api.example.com", + "acceptedCurrencies": ["USDC", "USDT"], + "chains": ["avalanche-fuji", "base-sepolia"] +} + +// Response +{ + "status": "approved", + "merchantId": "merchant_123", + "apiKey": "fac_live_...", + "whitelistStatus": "active" +} +``` + +**Whitelist Benefits**: +- Prevents malicious merchants +- Reduces payment fraud +- Builds user trust +- Enables dispute resolution + +### 2. User Approval Verification + +Before submitting payments, facilitators verify user consent: + +```javascript +// User signs approval +const approval = await wallet.signMessage({ + facilitator: "thirdweb", + merchantAddress: "0x742d35...", + amount: "0.01", + currency: "USDC", + timestamp: Date.now(), + nonce: generateNonce() +}); + +// Facilitator verifies signature +POST /facilitator/verify-approval +{ + "signature": "0x9a8b...", + "approvalData": {...} +} + +// Response +{ + "valid": true, + "expiresAt": "2025-11-03T10:35:00Z" +} +``` + +**Verification Steps**: +1. Check signature cryptographic validity +2. Verify signer matches payer address +3. Confirm approval hasn't expired +4. Ensure nonce hasn't been used before + +### 3. Payment Verification + +When a merchant requests verification, facilitators check the blockchain: + +```javascript +// Merchant requests verification +POST /facilitator/verify-payment +{ + "transactionHash": "0x8f3d...", + "expectedAmount": "0.01", + "expectedCurrency": "USDC", + "expectedRecipient": "0x742d35...", + "chain": "avalanche-c-chain" +} + +// Facilitator queries blockchain +const tx = await avalancheClient.getTransaction("0x8f3d..."); + +// Verification checks +✓ Transaction exists on chain +✓ Transaction is confirmed +✓ Amount matches expected +✓ Recipient matches expected +✓ Currency is correct +✓ Transaction not previously used +✓ Block timestamp is recent + +// Response +{ + "verified": true, + "transactionHash": "0x8f3d...", + "blockNumber": 12345678, + "timestamp": "2025-11-03T10:30:02Z", + "confirmations": 1 +} +``` + +### 4. Transaction Submission + +Facilitators can submit transactions on behalf of users: + +```javascript +// User approves payment intent (without submitting) +const intent = { + from: userWallet, + to: merchantWallet, + amount: "0.01", + currency: "USDC" +}; + +const signature = await wallet.signApproval(intent); + +// Facilitator submits transaction +POST /facilitator/submit-payment +{ + "paymentIntent": intent, + "signature": signature, + "gasPriority": "fast" +} + +// Facilitator submits to blockchain +const tx = await usdcContract.transfer( + intent.to, + parseUnits(intent.amount, 6) +); + +// Response +{ + "submitted": true, + "transactionHash": "0x8f3d...", + "estimatedConfirmation": "2025-11-03T10:30:02Z" +} +``` + +**Submission Benefits**: +- Users don't need AVAX for gas +- Optimized gas prices +- Better UX for non-crypto users +- Batched transactions possible + +### 5. Settlement Management + +Facilitators handle payment settlement with merchants: + +```javascript +// Real-time settlement notification +{ + "event": "payment.verified", + "merchantId": "merchant_123", + "transactionHash": "0x8f3d...", + "amount": "0.01", + "currency": "USDC", + "from": "0x1234...", + "timestamp": "2025-11-03T10:30:02Z", + "blockNumber": 12345678 +} + +// Batched settlement (optional) +POST /facilitator/withdraw-balance +{ + "merchantAddress": "0x742d35...", + "currency": "USDC", + "chain": "avalanche-c-chain" +} + +// Response +{ + "pendingBalance": "150.45", + "withdrawalTxHash": "0xabc123...", + "estimatedArrival": "2025-11-03T10:32:00Z" +} +``` + +## Facilitator Architecture + +The facilitator sits between merchants and the blockchain, handling the complex verification and settlement process: + +**Payment Flow**: +1. **Client → Merchant**: Client sends payment authorization via X-PAYMENT header +2. **Merchant → Facilitator**: Merchant forwards the authorization for verification +3. **Facilitator → Blockchain**: Facilitator verifies the signature and submits transaction on-chain +4. **Blockchain → Facilitator**: Transaction is confirmed with hash +5. **Facilitator → Merchant**: Payment confirmation returned to merchant +6. **Merchant → Client**: Content delivered to client with X-PAYMENT-RESPONSE header + +This entire flow completes in ~2 seconds on Avalanche. + +### Multi-Chain Support + +Facilitators often support multiple blockchains: + +```javascript +// Facilitator chain configuration +{ + "chains": [ + { + "id": "avalanche-c-chain", + "rpcUrl": "https://api.avax.network/ext/bc/C/rpc", + "usdcAddress": "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E", + "confirmations": 1, + "averageBlockTime": "2s" + }, + { + "id": "base-sepolia", + "rpcUrl": "https://sepolia.base.org", + "usdcAddress": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "confirmations": 1, + "averageBlockTime": "2s" + } + ] +} +``` + +This allows merchants to accept payments on any supported chain. + +## Facilitator Economics + +Facilitators charge minimal fees compared to traditional payment processors: + +**Typical Fee Structure**: +- Small percentage fee (~0.1-0.5% of transaction) +- Plus blockchain gas costs (~\$0.001 on Avalanche with current network conditions) +- No monthly fees or minimums +- No chargebacks or disputes + +**Example**: On a $0.10 payment: +- Facilitator fee: ~$0.0003 (0.3%) +- Gas cost: ~$0.001 (current network conditions) +- **Total cost: ~$0.0013** + +Compare to traditional payment processors: 2.9% + $0.30 = $0.3029 per transaction! + +Facilitators make micropayments economically viable. + +## Security and Trust + +### Merchant Protection + +Facilitators protect merchants from: +- Replay attacks (transaction hash tracking) +- Insufficient payments (amount verification) +- Wrong currency (token verification) +- Expired payments (timestamp checking) + +### User Protection + +Facilitators protect users from: +- Malicious merchants (whitelisting) +- Unauthorized charges (signature verification) +- Double-spending (on-chain verification) +- Overcharging (amount validation) + +## Summary + +Facilitators are essential infrastructure in the x402 ecosystem, handling payment verification, blockchain settlement, merchant whitelisting, and user approval verification. By abstracting blockchain complexity, facilitators enable merchants to accept cryptocurrency payments with minimal integration while maintaining security, speed, and low costs. + +Facilitators charge minimal fees (~0.1-0.5% + gas) compared to traditional payment processors (2.9% + $0.30), making micropayments economically viable for the first time. + +**Next**: Learn about [Blockchain Settlement](./04-blockchain-settlement) to understand how payments are finalized on-chain, or explore [available facilitators on Avalanche](/academy/x402-payment-infrastructure/04-x402-on-avalanche/03-facilitators) for implementation options. From 55a05bf974f8882c2ebc0697da4acace603293d6 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Sun, 9 Nov 2025 21:56:30 +0100 Subject: [PATCH 11/30] add blockchain settlement --- .../04-blockchain-settlement.mdx | 206 ++++++++++++++++++ 1 file changed, 206 insertions(+) create mode 100644 content/academy/x402-payment-infrastructure/03-technical-architecture/04-blockchain-settlement.mdx diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/04-blockchain-settlement.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/04-blockchain-settlement.mdx new file mode 100644 index 00000000000..bd1ff55f2c2 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/04-blockchain-settlement.mdx @@ -0,0 +1,206 @@ +--- +title: Blockchain Settlement +description: Understanding how payments are settled on-chain with instant finality and cryptographic proof. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: Link +--- + +## On-Chain Settlement Overview + +In the x402 protocol, all payments settle directly on the blockchain, providing transparency, immutability, and instant finality. This contrasts with traditional payment systems where settlement can take days and occurs in opaque, centralized databases. + +## Why Blockchain Settlement? + +### Transparency + +Every payment is publicly verifiable: + +```javascript +// Anyone can verify a payment +const tx = await avalancheClient.getTransaction( + "0x8f3d1a2b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a" +); + +console.log({ + from: tx.from, // Payer address + to: tx.to, // Recipient address + value: tx.value, // Amount paid + blockNumber: tx.blockNumber, + timestamp: tx.timestamp, + status: tx.status // Success/failure +}); +``` + +No need to trust a payment processor—the blockchain is the source of truth. + +### Immutability + +Once a transaction is confirmed, it cannot be: +- Reversed (no chargebacks) +- Modified (tamper-proof) +- Deleted (permanent record) +- Disputed (cryptographically proven) + +This eliminates chargeback fraud and provides definitive proof of payment. + +### Instant Finality + +On Avalanche C-Chain, transactions achieve finality in approximately 2 seconds: + +``` +Traditional ACH: 2-7 days +Credit Card: 24-72 hours +PayPal: 1-3 days +Bitcoin: ~60 minutes (6 confirmations) +Ethereum: ~15 minutes (2 epochs) +Avalanche: ~2 seconds ✓ +``` + +## The Settlement Process + +When a payment authorization is submitted through x402, settlement happens through a streamlined three-phase process leveraging EIP-3009's gasless payment standard. + +### Phase 1: Authorization Verification + +The facilitator receives the signed EIP-712 authorization from the client. This cryptographic signature proves the user approved the payment without requiring them to submit a blockchain transaction themselves. The facilitator validates that: + +- The signature matches the authorization details +- The payment amount doesn't exceed `maxAmountRequired` +- The authorization is within its validity window (`validAfter` to `validBefore`) +- The nonce hasn't been used before (replay protection) + +This verification is trustless—the signature cryptographically guarantees user consent. + +### Phase 2: Blockchain Submission + +The facilitator calls the USDC contract's `transferWithAuthorization` function with the signed authorization. This **gasless payment method** (EIP-3009 standard) allows the facilitator to submit the transaction on behalf of the user. The user doesn't pay gas fees or submit any blockchain transactions—they only provide a signature. + +The USDC contract verifies the signature on-chain and executes the transfer if valid. This ensures the payment cannot be tampered with after the user signs. + +### Phase 3: Confirmation and Finality + +On Avalanche, the transaction is included in a block and reaches finality in approximately **1-2 seconds**. Once finalized, the transaction cannot be reversed—the payment is permanent and immutable. + +The facilitator receives the transaction hash from the blockchain and returns it to the merchant. The USDC balances are permanently updated on-chain, and the payment is complete. + +**Total Time**: The entire x402 process from initial request to settlement takes approximately **2-2.3 seconds**. + +**Reference**: For detailed technical implementation of TransferWithAuthorization, see [x402 Whitepaper](https://www.x402.org/x402-whitepaper.pdf) (Section 9.3). + +## Payment Verification + +Facilitators verify payments by querying the blockchain to ensure the transaction matches the expected payment details. This verification is trustless—anyone can independently confirm the payment by checking the blockchain. + +### What Facilitators Verify + +When a transaction is submitted, facilitators check: + +1. **Transaction Existence**: The transaction hash exists on the blockchain +2. **Transaction Success**: The transaction executed without errors +3. **Correct Recipient**: Funds were sent to the expected `payTo` address +4. **Correct Amount**: The transfer amount matches or exceeds `maxAmountRequired` +5. **Recent Timestamp**: The transaction was created recently (prevents replay of old transactions) +6. **Confirmation Status**: The transaction has reached finality + +### USDC Transfer Events + +USDC transfers emit `Transfer` events on-chain that provide cryptographic proof of payment: + +```solidity +event Transfer(address indexed from, address indexed to, uint256 value); +``` + +These events can be parsed from transaction logs to verify payment details without trusting the facilitator. The blockchain is the source of truth. + +### Trustless Verification + +Because all payment data is on-chain, merchants can independently verify payments without relying on facilitators. Simply query the blockchain with the transaction hash to confirm: +- Who paid (sender address) +- Who received (recipient address) +- How much was paid (token amount) +- When it was paid (block timestamp) + +This transparency eliminates the need to trust payment processors. + +## Gas and Fee Economics + +### Transaction Costs on Avalanche + +x402 payments on Avalanche use EIP-3009's gasless payment model, where the **facilitator sponsors the gas** rather than the payer. This removes the friction of users needing AVAX to pay gas fees. + +Typical transaction costs (based on current network conditions - January 2025): +- **Gas used**: ~77,000 gas units (`transferWithAuthorization`) +- **Gas price**: ~0.575 nAVAX per gas unit (current) +- **Total cost**: ~\$0.001 USD (with AVAX at $20) + +**Who pays gas?** +- In x402, the **facilitator pays gas fees** when submitting the transaction +- The user only signs the authorization—no blockchain transaction needed from their side +- This enables truly gasless payments for end users + +### Cost Comparison + +| Aspect | Traditional Payments | x402 on Avalanche | +|--------|---------------------|-------------------| +| Settlement Time | 2-7 days | ~2 seconds | +| Transaction Fees | 2.9% + \$0.30 | ~\$0.001 gas (facilitator-paid) | +| Chargebacks | Possible | Impossible | +| Transparency | Opaque | Fully transparent | +| Verification | Trust processor | Cryptographic proof | +| Finality | Delayed | Instant | + +**Key Advantage**: For micropayments, x402's flat ~\$0.001 gas cost is dramatically better than traditional payment processing's 2.9% + \$0.30 per transaction. + +## Multi-Chain Settlement Timing + +Different blockchains have different finality characteristics, which affects the total x402 payment process time. It's important to distinguish between **blockchain finality** (how fast the chain confirms transactions) and **full x402 process time** (complete flow from request to response). + +### Timing Comparison + +| Blockchain | Blockchain Finality | Full x402 Process | x402 Support | +|------------|---------------------|-------------------|--------------| +| **Avalanche** | ~1-2 seconds | ~2-2.3 seconds | ✅ Official | +| **Base** | ~2 seconds | ~2-2.5 seconds | ✅ Official | +| **Ethereum** | ~12-15 minutes | ~15-20 minutes | ✅ Official | +| **Polygon** | ~2-5 seconds | ~2-5 seconds | ⚠️ Check facilitator | + +**Note**: The **full x402 process time** includes: +1. Initial request (~100ms) +2. 402 response (~100ms) +3. Payment authorization creation and signing (~500ms) +4. Blockchain settlement (varies by chain) +5. Response delivery (~100ms) + +**Important**: Chains not listed here may not have official x402 support yet. Always verify with your facilitator which networks they support. Check [PayAI documentation](https://docs.payai.network) for their current network list. + +### Choosing a Blockchain + +When selecting a blockchain for x402 payments, consider: + +1. **Settlement Speed**: How fast do you need payment confirmation? +2. **Transaction Costs**: What are the gas fees on this chain? +3. **Facilitator Support**: Does your chosen facilitator support this chain? +4. **User Base**: Which chains do your users already have wallets and tokens on? + +For most micropayment use cases, **Avalanche** and **Base** offer the best combination of speed (\~2 seconds) and cost (~\$0.001 gas). + +## Summary + +Blockchain settlement in x402 provides transparent, immutable, and instant payment finality through EIP-3009's gasless payment standard. The complete x402 process takes approximately **2-2.3 seconds** on Avalanche, with blockchain finality achieved in **1-2 seconds**. + +Key advantages: +- **Gasless for users**: Facilitators sponsor gas fees, eliminating the need for users to hold native tokens +- **Cryptographic proof**: Every payment is verifiable on-chain without trusting intermediaries +- **No chargebacks**: Finality is instant and irreversible +- **Multi-chain support**: Works across Avalanche, Base, Ethereum, and other EVM chains + +Facilitators abstract away the complexity of blockchain interactions, making x402 settlement as simple as traditional payment APIs while delivering superior speed, lower costs, and trustless verification. + +**Next**: Learn about [Security Considerations](./05-security-considerations) including replay attack prevention, signature validation, and settlement monitoring. + +## Additional Resources + +- [x402 Whitepaper - Technical Specifications](https://www.x402.org/x402-whitepaper.pdf) +- [EIP-3009: Transfer With Authorization](https://eips.ethereum.org/EIPS/eip-3009) +- [Avalanche Consensus](https://docs.avax.network/learn/avalanche/avalanche-consensus) From 2568baff0c51e8bcfed4f722815b138538bec8a0 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Sun, 9 Nov 2025 22:03:38 +0100 Subject: [PATCH 12/30] add security considerations --- .../05-security-considerations.mdx | 395 ++++++++++++++++++ 1 file changed, 395 insertions(+) create mode 100644 content/academy/x402-payment-infrastructure/03-technical-architecture/05-security-considerations.mdx diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/05-security-considerations.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/05-security-considerations.mdx new file mode 100644 index 00000000000..2ca82749b94 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/05-security-considerations.mdx @@ -0,0 +1,395 @@ +--- +title: Security Considerations +description: Understanding replay attack prevention, time-bounded authorizations, and settlement monitoring in x402. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: Shield +--- + +## Overview + +The x402 protocol implements multiple layers of security to protect against common attack vectors while maintaining a seamless user experience. These security measures are built on battle-tested Ethereum standards (EIP-712, EIP-3009) and blockchain cryptography. + +## Replay Attack Prevention + +Replay attacks occur when an attacker intercepts a valid payment authorization and attempts to reuse it multiple times. x402 prevents this through three complementary mechanisms: + +### 1. Nonce-Based Protection + +Each payment authorization includes a unique random nonce (32-byte hex string): + +```javascript +const nonce = ethers.randomBytes(32); +// Example: 0x3456789012345678901234567890123456789012345678901234567890123456 +``` + +The USDC contract (following EIP-3009) tracks which nonces have been used on-chain. When a `transferWithAuthorization` is executed: + +1. The contract checks if the nonce has been used before +2. If the nonce is new, the transfer proceeds and the nonce is marked as used +3. If the nonce was already used, the transaction reverts with an error + +**This makes each authorization single-use**. Even if an attacker intercepts the authorization, they cannot reuse it because the nonce is already consumed on-chain. + +### 2. Time-Bounded Authorizations + +Every authorization includes `validAfter` and `validBefore` timestamps (Unix time in seconds): + +```json +{ + "validAfter": "1740672089", // January 7, 2025, 10:00:00 AM UTC + "validBefore": "1740672389" // January 7, 2025, 10:05:00 AM UTC (5 minutes later) +} +``` + +The USDC contract enforces these timing constraints: +- If current time < `validAfter`: Transaction reverts (not yet valid) +- If current time ≥ `validBefore`: Transaction reverts (expired) +- Only between these times: Transaction can execute + +**Best practices**: +- Set short validity windows (5-10 minutes) for most payments +- For delayed/scheduled payments, set appropriate `validAfter` +- Never set `validBefore` too far in the future (increases replay risk if nonce tracking fails) + +**Example timing strategy**: +```javascript +const now = Math.floor(Date.now() / 1000); +const authorization = { + validAfter: now.toString(), // Valid immediately + validBefore: (now + 300).toString(), // Expires in 5 minutes + // ... other fields +}; +``` + +### 3. Transaction Hash Uniqueness + +Each blockchain transaction has a unique hash. Merchants should track received transaction hashes to ensure they don't fulfill the same payment twice: + +```javascript +// Server-side tracking +const processedTransactions = new Set(); + +function fulfillPayment(txHash, resource) { + if (processedTransactions.has(txHash)) { + throw new Error("Payment already fulfilled"); + } + + // Deliver resource to user + deliverResource(resource); + + // Mark transaction as processed + processedTransactions.add(txHash); +} +``` + +**Why this matters**: Even though blockchain nonces prevent double-spending, merchants should track which payments they've already fulfilled. This prevents edge cases where: +- A facilitator sends duplicate settlement notifications +- Network issues cause duplicate webhook deliveries +- Multiple facilitators process the same authorization (if incorrectly configured) + +## Signature Validation + +All payment authorizations use EIP-712 typed structured data signatures, providing cryptographic proof that the user authorized the payment. + +### What EIP-712 Signatures Protect Against + +1. **Forgery**: Only the user's private key can create a valid signature +2. **Tampering**: Changing any field invalidates the signature +3. **Phishing**: The signature includes domain binding (verifyingContract address) +4. **Man-in-the-middle**: The signature covers all payment details + +### Server-Side Signature Verification + +Facilitators must validate signatures before submitting transactions: + +```javascript +import { verifyTypedData } from 'ethers'; + +function validatePaymentSignature(payload) { + const { signature, authorization } = payload.payload; + const { network } = payload; + + // EIP-712 domain for USDC on Avalanche Fuji + const domain = { + name: "USD Coin", + version: "2", + chainId: 43113, // Avalanche Fuji + verifyingContract: "0x5425890298aed601595a70AB815c96711a31Bc65" + }; + + // EIP-712 type definition + const types = { + TransferWithAuthorization: [ + { name: "from", type: "address" }, + { name: "to", type: "address" }, + { name: "value", type: "uint256" }, + { name: "validAfter", type: "uint256" }, + { name: "validBefore", type: "uint256" }, + { name: "nonce", type: "bytes32" } + ] + }; + + // Recover signer address from signature + const recovered = verifyTypedData( + domain, + types, + authorization, + signature + ); + + // Verify the signer matches the 'from' address + if (recovered.toLowerCase() !== authorization.from.toLowerCase()) { + throw new Error("Invalid signature: signer does not match 'from' address"); + } + + return true; +} +``` + +**Key validation steps**: +1. Recover the signer address from the signature +2. Verify it matches the `from` field in the authorization +3. Check all other fields (amount, recipient, timing) +4. Only submit to blockchain if everything validates + +### On-Chain Signature Verification + +The USDC contract performs the same signature validation on-chain when `transferWithAuthorization` is called. This provides **trustless verification**—even if the facilitator is malicious, an invalid signature will cause the transaction to revert. + +## Authorization Timing Validation + +Facilitators should validate timing constraints before submitting transactions to avoid wasting gas on expired authorizations: + +```javascript +function validateTiming(authorization) { + const now = Math.floor(Date.now() / 1000); + const validAfter = parseInt(authorization.validAfter); + const validBefore = parseInt(authorization.validBefore); + + if (now < validAfter) { + throw new Error("Authorization not yet valid"); + } + + if (now >= validBefore) { + throw new Error("Authorization expired"); + } + + // Optional: Warn if expiring soon + if (now + 30 >= validBefore) { + console.warn("Authorization expires in less than 30 seconds"); + } + + return true; +} +``` + +This prevents: +- Submitting transactions that will revert due to timing +- Wasting gas fees on failed transactions +- Poor user experience from delayed settlements + +## Settlement Monitoring + +Facilitators monitor the blockchain in real-time to detect when payments are settled and to verify transaction success. + +### What Facilitators Monitor + +After submitting a `transferWithAuthorization` transaction: + +1. **Transaction Confirmation**: Wait for the transaction to be included in a block +2. **Transaction Success**: Verify the transaction status is `1` (success), not `0` (failure) +3. **Event Emissions**: Check that the `Transfer` event was emitted with correct parameters +4. **Finality**: On Avalanche, wait ~1-2 seconds for finality + +### Webhook Notifications + +Most facilitators provide webhook notifications when settlements complete: + +```javascript +// Merchant server receives webhook +app.post('/webhooks/payment-settled', (req, res) => { + const { transaction, network, payer, amount, success } = req.body; + + if (success) { + // Verify transaction on-chain (trustless) + const verified = await verifyTransactionOnChain(transaction, network); + + if (verified) { + // Fulfill user's order + fulfillOrder(payer, amount); + } + } + + res.status(200).send('OK'); +}); +``` + +**Best practice**: Always verify webhook data by querying the blockchain directly. Don't trust the webhook alone—use it as a notification, then verify on-chain. + +### Independent Monitoring + +Merchants can also monitor the blockchain directly without relying on facilitators: + +```javascript +import { ethers } from 'ethers'; + +// Monitor for Transfer events to your address +const provider = new ethers.JsonRpcProvider('https://api.avax-test.network/ext/bc/C/rpc'); +const usdcContract = new ethers.Contract(usdcAddress, usdcAbi, provider); + +// Listen for incoming payments +usdcContract.on('Transfer', (from, to, value, event) => { + if (to.toLowerCase() === myAddress.toLowerCase()) { + console.log(`Received ${value} USDC from ${from}`); + console.log(`Transaction: ${event.transactionHash}`); + + // Fulfill payment + fulfillPayment(event.transactionHash); + } +}); +``` + +This provides **complete independence** from facilitators for settlement verification. + +## Amount Verification + +Always verify that the payment amount meets your requirements: + +```javascript +function validatePaymentAmount(authorization, maxAmountRequired) { + const authorizedAmount = BigInt(authorization.value); + const requiredAmount = BigInt(maxAmountRequired); + + if (authorizedAmount < requiredAmount) { + throw new Error( + `Insufficient payment: required ${requiredAmount}, got ${authorizedAmount}` + ); + } + + return true; +} +``` + +**Important**: Amounts are in token base units (see [Amount Specification](./02-http-headers#amount-specification) for details). + +Accept payments equal to or greater than `maxAmountRequired` to allow for user generosity (tips). + +## Network Verification + +Verify that the payment is on the expected blockchain network: + +```javascript +function validateNetwork(payload, expectedNetwork) { + if (payload.network !== expectedNetwork) { + throw new Error( + `Wrong network: expected ${expectedNetwork}, got ${payload.network}` + ); + } + + // Also verify the chainId matches the network + const expectedChainId = getChainId(expectedNetwork); + // Signature domain includes chainId, so this is validated in signature verification +} +``` + +This prevents: +- Payments on testnets being accepted as mainnet payments +- Cross-chain replay attacks +- Merchant configuration errors + +## Recipient Address Verification + +Verify that payments are sent to the correct recipient address: + +```javascript +function validateRecipient(authorization, expectedPayTo) { + if (authorization.to.toLowerCase() !== expectedPayTo.toLowerCase()) { + throw new Error( + `Wrong recipient: expected ${expectedPayTo}, got ${authorization.to}` + ); + } +} +``` + +This is especially important when: +- Supporting multiple merchants on one facilitator +- Using different addresses for different services +- Accepting payments to multiple wallets + +## Token Contract Verification + +Verify that the payment uses the expected token (asset): + +```javascript +function validateAsset(paymentRequest, expectedAsset) { + if (paymentRequest.asset.toLowerCase() !== expectedAsset.toLowerCase()) { + throw new Error( + `Wrong token: expected ${expectedAsset}, got ${paymentRequest.asset}` + ); + } +} +``` + +**Why this matters**: Attackers could try to pay with worthless tokens that share similar addresses. Always validate the exact contract address. + +**Example USDC addresses**: +- Avalanche C-Chain: `0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E` +- Avalanche Fuji: `0x5425890298aed601595a70AB815c96711a31Bc65` +- Base Sepolia: `0x036CbD53842c5426634e7929541eC2318f3dCF7e` + +## Rate Limiting and Abuse Prevention + +Implement rate limiting to prevent abuse: + +```javascript +// Simple rate limiting by address +const paymentsByAddress = new Map(); + +function checkRateLimit(from, maxPerHour = 10) { + const now = Date.now(); + const oneHour = 60 * 60 * 1000; + + if (!paymentsByAddress.has(from)) { + paymentsByAddress.set(from, []); + } + + const payments = paymentsByAddress.get(from); + + // Remove old payments outside the window + const recentPayments = payments.filter(time => now - time < oneHour); + + if (recentPayments.length >= maxPerHour) { + throw new Error(`Rate limit exceeded: max ${maxPerHour} payments per hour`); + } + + recentPayments.push(now); + paymentsByAddress.set(from, recentPayments); +} +``` + +This prevents: +- Spam attacks on your API +- Nonce exhaustion attacks +- Resource abuse + +## Summary + +x402 security relies on multiple defense layers: + +1. **Nonce-based replay prevention**: Each authorization is single-use +2. **Time-bounded authorizations**: Payments expire after a set time window +3. **EIP-712 signatures**: Cryptographic proof of user authorization +4. **On-chain validation**: USDC contract verifies all constraints +5. **Transaction hash tracking**: Merchants prevent duplicate fulfillment +6. **Amount, network, and asset verification**: Validate all payment parameters +7. **Settlement monitoring**: Real-time blockchain monitoring for finality + +These mechanisms provide trustless, cryptographically secure payments without requiring users to trust facilitators or merchants. The blockchain enforces all security rules. + +## Additional Resources + +- [EIP-712: Typed Structured Data Signing](https://eips.ethereum.org/EIPS/eip-712) +- [EIP-3009: Transfer With Authorization](https://eips.ethereum.org/EIPS/eip-3009) +- [x402 Whitepaper - Security Model](https://www.x402.org/x402-whitepaper.pdf) +- [PayAI Security Best Practices](https://docs.payai.network/security) From 2e256d4115a73f1716b53f19fa0a1a05a18707c9 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Sun, 9 Nov 2025 22:11:29 +0100 Subject: [PATCH 13/30] added the links for images uploaded on vercel --- .../02-introduction/01-what-is-x402.mdx | 2 +- .../02-introduction/02-payment-problem.mdx | 2 +- .../02-introduction/03-use-cases.mdx | 4 ++-- .../03-technical-architecture/01-payment-flow.mdx | 2 +- .../03-technical-architecture/02-http-headers.mdx | 6 ++---- 5 files changed, 7 insertions(+), 9 deletions(-) diff --git a/content/academy/x402-payment-infrastructure/02-introduction/01-what-is-x402.mdx b/content/academy/x402-payment-infrastructure/02-introduction/01-what-is-x402.mdx index 742732fe597..ddf8bf4fb9b 100644 --- a/content/academy/x402-payment-infrastructure/02-introduction/01-what-is-x402.mdx +++ b/content/academy/x402-payment-infrastructure/02-introduction/01-what-is-x402.mdx @@ -29,7 +29,7 @@ At its core, x402 transforms how payments are requested and fulfilled on the web This entire process happens in approximately 2 seconds, creating a seamless payment experience. -![The x402 payment cycle](/tmpimagesx402/paumentcyclex402.png) +![The x402 payment cycle](https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/course-images/x402-payment-infrastructure/x402PaymentCycle.png) ## Key Characteristics diff --git a/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx b/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx index 326ec52abb8..882ea4ffb3f 100644 --- a/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx +++ b/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx @@ -157,7 +157,7 @@ As AI agents become more prevalent, traditional payment systems create impossibl - No account creation or KYC - Micropayment support (fractions of a cent) -![AI agents blocked by traditional payment systems](/tmpimagesx402/x402_ai_agents.png) +![AI agents blocked by traditional payment systems](https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/course-images/x402-payment-infrastructure/HowAIAgentsMakePayments.png) ## Real-World Impact diff --git a/content/academy/x402-payment-infrastructure/02-introduction/03-use-cases.mdx b/content/academy/x402-payment-infrastructure/02-introduction/03-use-cases.mdx index ec593e6b36a..ef91a46b9cd 100644 --- a/content/academy/x402-payment-infrastructure/02-introduction/03-use-cases.mdx +++ b/content/academy/x402-payment-infrastructure/02-introduction/03-use-cases.mdx @@ -43,7 +43,7 @@ x402 Approach (Seamless): 4. Data returned in 2 seconds ``` -![x402 payment flow for AI agents](/tmpimagesx402/payment%20flow.png) +![x402 payment flow for AI agents](https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/course-images/x402-payment-infrastructure/http402PaymentFlow.png) ### Inter-Agent Commerce @@ -80,7 +80,7 @@ Developers can charge minimal amounts per API call: These micro-amounts are economically viable with x402's ultra-low transaction costs, unlike traditional payment systems where fees exceed the payment value itself. -![Traditional vs x402 payment economics](/tmpimagesx402/problemsolved.png) +![Traditional vs x402 payment economics](https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/course-images/x402-payment-infrastructure/MicropaymentForTheInternet.png) **Economics Comparison**: ``` diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/01-payment-flow.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/01-payment-flow.mdx index 39214bb46c8..2191eba02a7 100644 --- a/content/academy/x402-payment-infrastructure/03-technical-architecture/01-payment-flow.mdx +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/01-payment-flow.mdx @@ -102,7 +102,7 @@ The client now has access to the resource, and the entire cycle completed in app For a deeper understanding, here's the complete technical flow including facilitator interactions: -![Detailed x402 payment flow](/tmpimagesx402/paymentflow2.png) +![Detailed x402 payment flow](https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/course-images/x402-payment-infrastructure/12StepPaymentFlow.png) ### Phase 1: Initial Request diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-headers.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-headers.mdx index acde84fe374..d99ad938019 100644 --- a/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-headers.mdx +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-headers.mdx @@ -89,8 +89,8 @@ The `asset` field contains the smart contract address of the payment token: // USDC on Avalanche C-Chain mainnet "asset": "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E" -// USDC on Ethereum mainnet -"asset": "0xA0b86991C6218b36c1d19D4a2e9Eb0cE3606EB48" +// USDC on Base Sepolia testnet +"asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e" ``` **Note**: The asset is identified by contract address, not by symbol like "USDC". @@ -102,8 +102,6 @@ Standard network identifiers for Avalanche and other chains: ```javascript "network": "avalanche-c-chain" // Avalanche C-Chain Mainnet "network": "avalanche-fuji" // Avalanche Fuji Testnet -"network": "ethereum-mainnet" // Ethereum Mainnet -"network": "base-mainnet" // Base Mainnet "network": "base-sepolia" // Base Sepolia Testnet ``` From 324cf5e75c2b85cd650320a710a05376a1164dc6 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Mon, 10 Nov 2025 13:12:20 +0100 Subject: [PATCH 14/30] add why avalanche for x402 --- .../04-x402-on-avalanche/01-why-avalanche.mdx | 221 ++++++++++++++++++ 1 file changed, 221 insertions(+) create mode 100644 content/academy/x402-payment-infrastructure/04-x402-on-avalanche/01-why-avalanche.mdx diff --git a/content/academy/x402-payment-infrastructure/04-x402-on-avalanche/01-why-avalanche.mdx b/content/academy/x402-payment-infrastructure/04-x402-on-avalanche/01-why-avalanche.mdx new file mode 100644 index 00000000000..7768c4e19c0 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/04-x402-on-avalanche/01-why-avalanche.mdx @@ -0,0 +1,221 @@ +--- +title: Why Avalanche for x402? +description: Understanding why Avalanche C-Chain is ideal for x402 payment infrastructure. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: Zap +--- + +## Avalanche's x402 Advantages + +Avalanche C-Chain provides unique characteristics that make it an ideal platform for x402 payment infrastructure. The combination of low fees, fast finality, high throughput, and EVM compatibility creates the perfect environment for micropayments and AI agent commerce. + +## Sub-2-Second Finality + +Avalanche achieves transaction finality in approximately 1-2 seconds, faster than any other EVM-compatible chain: + +| Blockchain | Blockchain Finality | Full x402 Process | Use Case Fit | +|------------|---------------------|-------------------|--------------| +| **Avalanche** | **~1-2 seconds** | **~2-2.3 seconds** | **✓ Ideal for x402** | +| **Base** | **~2 seconds** | **~2-2.5 seconds** | **✓ Good** | +| Ethereum | ~12-15 minutes | ~15-20 minutes | ✗ Too slow for real-time | + +**Why This Matters for x402**: +- Users wait only ~2 seconds for content delivery +- AI agents can make rapid sequential payments +- High-frequency API calls remain practical +- Real-time payment verification possible + +### Avalanche vs Base for x402 + +While both Avalanche and Base offer fast finality suitable for x402 payments, Avalanche provides key advantages: + +**Finality Guarantees**: +- **Avalanche**: Deterministic finality ~1-2 seconds ([Avalanche Consensus](https://docs.avax.network/learn/avalanche/avalanche-consensus)) +- **Base**: Probabilistic finality [~2 seconds](https://docs.base.org/base-chain/network-information/transaction-finality#under-0-001-probability-of-a-reorg) + +**Gas Costs**: +- **Avalanche**: ~$0.001 for `transferWithAuthorization` (based on current gas prices of 0.575 nAVAX) +- **Base**: ~$0.01-0.10 depending on L1 gas prices (variable) + +For mission-critical x402 applications requiring guaranteed fast settlement and consistent costs, **Avalanche is a strong option**. + +## Ultra-Low Transaction Fees + +Avalanche C-Chain maintains extremely low gas costs, making micropayments economically viable: + +### Fee Comparison + +```javascript +// $0.01 payment cost analysis + +Avalanche C-Chain: +├── Payment value: $0.01 +├── Gas fee: ~$0.001 +├── Total cost: $0.011 +└── Overhead: 10% ✓ + +Base: +├── Payment value: $0.01 +├── Gas fee: ~$0.001 +├── Total cost: $0.011 +└── Overhead: 10% ✓ (acceptable) +``` + +### Real-World Economics + +For a typical x402 API monetization scenario: + +```javascript +// Scenario: Image processing API + +Traditional Payment (Stripe): +├── API request value: $0.01 +├── Processing fee: 2.9% + $0.30 +├── Total fee: $0.30029 +├── Net to merchant: -$0.29029 +└── Result: 3,003% loss ✗ + +Avalanche x402: +├── API request value: $0.01 +├── Gas fee: $0.001 +├── Facilitator fee: $0.00003 (0.3%) +├── Total fees: $0.00103 +├── Net to merchant: $0.00897 +└── Result: 10.3% overhead ✓ +``` + +Only on low-fee chains like Avalanche are micropayments practical. + +## High Throughput + +Avalanche C-Chain provides high throughput, enabling x402 to handle large-scale deployments without network congestion. This means consistent fee levels (no gas price spikes) and scalability for AI agent economies with millions of daily payments. + +## EVM Compatibility + +Avalanche C-Chain is fully EVM-compatible, enabling developers to use familiar tools: +- Web3.js / Ethers.js +- MetaMask +- Hardhat / Foundry +- OpenZeppelin contracts + +### Cross-Chain Facilitator Support + +EVM compatibility means facilitators can support multiple chains with minimal code changes: + +```javascript +// Same facilitator code works across: +- Avalanche C-Chain +- Ethereum +- Base +- Polygon +// ... any EVM chain +``` + +## Native Stablecoin Support + +USDC is native to Avalanche (Circle-issued), providing: + +### Official Circle USDC + +```javascript +{ + name: "USD Coin", + symbol: "USDC", + address: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E", + decimals: 6, + issuer: "Circle", + type: "Native" // Not bridged +} +``` + +**Benefits**: +- No bridge risk +- Direct Circle minting/redemption +- High liquidity +- Institutional trust + +### Deep Liquidity + +Avalanche USDC has substantial liquidity: +- Hundreds of millions in daily volume +- Available on major DEXes (Trader Joe, Pharaoh) +- Integrated with CEXes +- Easy on/off ramping + +## Cost-Effective Development + +### Fuji Testnet + +Avalanche provides a free testnet for development: + +```javascript +// Fuji Testnet Configuration +{ + chainId: 43113, + rpcUrl: "https://api.avax-test.network/ext/bc/C/rpc", + avaxFaucet: "/console/primary-network/faucet", + usdcFaucet: "https://faucet.circle.com/" +} +``` + +**Development Benefits**: +- Free test AVAX and USDC +- Same API as mainnet +- Test facilitators available +- No cost to experiment + +## Real-World Performance + +### Actual x402 Performance on Avalanche + +```javascript +{ + averageConfirmation: "1.8s", + averageGasCost: "$0.001", + uptime: "99.99%", + facilitatorLatency: "~200ms" +} + +// Total payment time breakdown: +│ Component │ Time │ +├──────────────────────────┼─────────┤ +│ HTTP request │ ~50ms │ +│ Server processing │ ~100ms │ +│ Payment submission │ ~200ms │ +│ Blockchain confirmation │ ~1800ms │ +│ Facilitator verification │ ~100ms │ +│ Response delivery │ ~50ms │ +├──────────────────────────┼─────────┤ +│ TOTAL │ ~2.3s │ +``` + +## Economic Sustainability + +### Merchant Economics + +```javascript +// $0.01 API request profitability analysis + +Revenue per request: $0.01 +Costs: +├── Gas fee: $0.001 +├── Facilitator fee: $0.00003 (0.3%) +├── Infrastructure: $0.0001 +└── Total costs: $0.00113 + +Profit margin: $0.00887 (88.7%) ✓ +``` + +On Avalanche, micropayment business models are sustainable. + +## Summary + +Avalanche C-Chain is ideal for x402 because of its \~2-second finality, ultra-low fees (~\$0.001), high throughput, EVM compatibility, and native USDC support. These characteristics make micropayments economically viable and enable the AI agent economy that x402 envisions. With dedicated facilitators and comprehensive tooling, Avalanche provides a strong foundation for x402 payment infrastructure. + +## Next Steps + +In the following lessons, we'll explore: +- Setting up x402 on Avalanche (Fuji testnet) +- Available facilitators and their features +- Integration best practices From 964e7908cc33312c2b45c6e7d1aed308151192d7 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Mon, 10 Nov 2025 13:13:28 +0100 Subject: [PATCH 15/30] add small introduction for network setup and faucet. (it might get integrated in the future implementation demo --- .../04-x402-on-avalanche/02-network-setup.mdx | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 content/academy/x402-payment-infrastructure/04-x402-on-avalanche/02-network-setup.mdx diff --git a/content/academy/x402-payment-infrastructure/04-x402-on-avalanche/02-network-setup.mdx b/content/academy/x402-payment-infrastructure/04-x402-on-avalanche/02-network-setup.mdx new file mode 100644 index 00000000000..791ae1fc5db --- /dev/null +++ b/content/academy/x402-payment-infrastructure/04-x402-on-avalanche/02-network-setup.mdx @@ -0,0 +1,95 @@ +--- +title: Network Setup +description: Setting up x402 on Avalanche C-Chain Mainnet and Fuji Testnet. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: Settings +--- + +## Avalanche Networks Overview + +Avalanche provides two networks for x402 development: + +| Network | Purpose | Chain ID | RPC URL | +|---------|---------|----------|---------| +| **Mainnet** | Production | 43114 | https://api.avax.network/ext/bc/C/rpc | +| **Fuji Testnet** | Development | 43113 | https://api.avax-test.network/ext/bc/C/rpc | + +## Fuji Testnet Setup + +### Step 1: Configure Network in Wallet + +Add Fuji testnet to MetaMask or Core wallet: + +```javascript +// Network configuration +{ + networkName: "Avalanche Fuji Testnet", + rpcUrl: "https://api.avax-test.network/ext/bc/C/rpc", + chainId: 43113, + symbol: "AVAX", + explorerUrl: "https://testnet.snowtrace.io/" +} +``` + +Add Fuji to your wallet using the configuration above. Core Wallet has Fuji pre-configured. + +### Step 2: Get Test AVAX + +Get free test AVAX for gas fees: +1. Navigate to the [Console Faucet](/console/primary-network/faucet) +2. Connect your wallet +3. Request test AVAX + +### Step 3: Get Test USDC + +Get free test USDC from Circle's official faucet: +1. Visit [https://faucet.circle.com/](https://faucet.circle.com/) +2. Select "Avalanche Fuji" +3. Enter your wallet address +4. Receive test USDC + +## Contract Addresses + +### Mainnet Addresses + +```javascript +const AVALANCHE_MAINNET = { + chainId: 43114, + rpc: "https://api.avax.network/ext/bc/C/rpc", + usdc: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E", + usdt: "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7", + wavax: "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7" +}; +``` + +### Fuji Testnet Addresses + +```javascript +const AVALANCHE_FUJI = { + chainId: 43113, + rpc: "https://api.avax-test.network/ext/bc/C/rpc", + usdc: "0x5425890298aed601595a70AB815c96711a31Bc65", +}; +``` + +## Environment Configuration + +For x402 development, configure your environment variables: + +```bash +# .env file +AVALANCHE_RPC_FUJI=https://api.avax-test.network/ext/bc/C/rpc +USDC_FUJI=0x5425890298aed601595a70AB815c96711a31Bc65 +PRIVATE_KEY=your_private_key_here +``` + +For mainnet deployment, use: +```bash +AVALANCHE_RPC_MAINNET=https://api.avax.network/ext/bc/C/rpc +USDC_MAINNET=0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E +``` + +## Summary + +Setting up x402 on Avalanche Fuji testnet requires three steps: configure your wallet with Fuji network, get free test AVAX from Core Wallet console, and get free test USDC from Circle's faucet. With these resources, you're ready to integrate x402 facilitators and start building payment-enabled applications. From bd4bab8d9b461c0bed5fe4e1baeb70359cb7f0b3 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Mon, 10 Nov 2025 13:14:00 +0100 Subject: [PATCH 16/30] add a summary of the 4 current facilitators on avalanche --- .../04-x402-on-avalanche/03-facilitators.mdx | 416 ++++++++++++++++++ 1 file changed, 416 insertions(+) create mode 100644 content/academy/x402-payment-infrastructure/04-x402-on-avalanche/03-facilitators.mdx diff --git a/content/academy/x402-payment-infrastructure/04-x402-on-avalanche/03-facilitators.mdx b/content/academy/x402-payment-infrastructure/04-x402-on-avalanche/03-facilitators.mdx new file mode 100644 index 00000000000..dc296ac2a20 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/04-x402-on-avalanche/03-facilitators.mdx @@ -0,0 +1,416 @@ +--- +title: x402 Facilitators on Avalanche +description: Overview of available x402 facilitators on Avalanche and how to choose the right one. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: Network +--- + +## Available Facilitators + +Avalanche supports multiple x402 facilitators, each with different strengths and use cases. All are available at [build.avax.network/integrations](https://build.avax.network/integrations). + +## Thirdweb x402 + +**Best For**: Enterprise applications, multi-chain support, gasless transactions + +### Overview + +Thirdweb provides enterprise-grade x402 infrastructure with comprehensive SDKs and built-in support for gasless transactions using EIP-7702. + +**Official Documentation**: [portal.thirdweb.com/payments/x402/facilitator](https://portal.thirdweb.com/payments/x402/facilitator) + +### Key Features + +- **Multi-Chain Support**: Works on EVM chains including Avalanche C-Chain +- **Gasless Transactions**: EIP-7702 protocol for cost-free user submissions +- **Framework Integration**: x402-hono, x402-next, x402-express middlewares +- **Dashboard Tracking**: Monitor transactions through thirdweb project dashboard +- **Payment Verification**: Automatic signature validation and on-chain settlement +- **Token Support**: ERC-2612 permit and ERC-3009 authorization (USDC) + +### Installation + +```bash +npm install thirdweb +``` + +### Quick Start + +```typescript +import { facilitator } from "thirdweb/x402"; +import { createThirdwebClient } from "thirdweb"; + +const client = createThirdwebClient({ + secretKey: "your-secret-key", +}); + +const thirdwebFacilitator = facilitator({ + client: client, + serverWalletAddress: "0x1234567890123456789012345678901234567890", +}); +``` + +**Integration with Hono:** + +```javascript +import { Hono } from "hono"; +import { paymentMiddleware } from "x402-hono"; + +const app = new Hono(); + +app.use(paymentMiddleware( + "0xYourWalletAddress", + { + "/api/service": { + price: "$0.01", + network: "avalanche-c-chain", + config: { + description: "Access to your API service" + } + } + }, + { + facilitator: thirdwebFacilitator + } +)); +``` + +### Avalanche Configuration + +- **Mainnet**: Use network string `"avalanche"` (Chain ID: 43114) +- **Fuji Testnet**: Use network string `"avalanche-fuji"` (Chain ID: 43113) + +### Links + +- Integration: [build.avax.network/integrations/thirdweb-x402](https://build.avax.network/integrations/thirdweb-x402) +- Documentation: [portal.thirdweb.com/payments/x402/facilitator](https://portal.thirdweb.com/payments/x402/facilitator) + +### Pricing + +See [thirdweb.com/pricing](https://thirdweb.com/pricing) for current pricing information. + +--- + +## PayAI + +**Best For**: AI agents, autonomous payments, low-latency verification + +### Overview + +PayAI specializes in AI agent payments with optimized APIs for machine-to-machine commerce. Built natively for Avalanche's fast finality and low transaction costs. + +**Official Documentation**: [docs.payai.network/introduction](https://docs.payai.network/introduction) + +### Key Features + +- **AI-First Design**: Specifically built for agent monetization +- **Avalanche Native**: Leverages Avalanche's sub-second finality +- **Simple Integration**: TypeScript and Python SDKs +- **Product Suite**: + - x402 protocol implementation + - Freelance AI marketplace + - CT Agent Monetization + - Token Gateway + +### Installation + +```bash +npm install x402-express # For Express servers +npm install x402-client # For clients +``` + +### Quick Start (Server) + +```javascript +import express from 'express'; +import { paymentMiddleware } from 'x402-express'; + +const app = express(); + +app.use(paymentMiddleware( + "0xYourWalletAddress", + { + "/api/service": { + price: "$0.01", + network: "avalanche", + config: { + description: "Access to AI service" + } + } + } +)); +``` + +### Quick Start (Client) + +```javascript +import { X402Client } from 'x402-client'; + +const client = new X402Client({ + privateKey: process.env.CLIENT_PRIVATE_KEY, + facilitatorUrl: 'https://api.payai.network', + network: 'avalanche' +}); + +const response = await client.post('https://api.example.com/service', { + data: { query: 'your request' } +}); +``` + +### Avalanche Configuration + +- **Mainnet**: Use network string `"avalanche"` +- **Fuji Testnet**: Use network string `"avalanche-fuji"` +- **Payment Tokens**: AVAX and USDC + +### Links + +- Integration: [build.avax.network/integrations/payai](https://build.avax.network/integrations/payai) +- Documentation: [docs.payai.network/introduction](https://docs.payai.network/introduction) +- Website: [payai.network](https://payai.network/) + +### Pricing + +Contact PayAI for pricing information. Developer tier available for testing. + +--- + +## Ultravioleta DAO + +**Best For**: Decentralized applications, gasless payments, community governance + +### Overview + +Ultravioleta is a community-governed facilitator focused on gasless payments and decentralization. Users don't need AVAX tokens for transaction fees—the facilitator covers all costs. + +**Official Documentation**: [facilitator.ultravioletadao.xyz](https://facilitator.ultravioletadao.xyz) + +### Key Features + +- **Gasless Payments**: 100% gas coverage—users pay $0 in transaction fees +- **Stablecoin Settlement**: Transactions use USDC for predictable pricing +- **Sub-second Processing**: ~2-3 second end-to-end settlement on Avalanche +- **Cryptographic Security**: EIP-712 signatures prevent unauthorized transactions +- **Stateless Verification**: On-chain validation eliminates database dependencies +- **Auto-scalable Infrastructure**: High availability and reliability +- **Multi-Network Support**: Avalanche, Base, Celo, Polygon, Solana, and more +- **Community Governance**: Fully decentralized operation + +### Installation + +```bash +npm install x402-hono # For Hono servers +npm install x402-client # For clients +``` + +### Quick Start (Server) + +```javascript +import { Hono } from "hono"; +import { paymentMiddleware } from "x402-hono"; + +const app = new Hono(); + +app.use(paymentMiddleware( + "0xYourWalletAddress", + { + "/api/service": { + price: "$0.01", + network: "avalanche-c-chain", + config: { + description: "Access to your API service" + } + } + }, + { + url: 'https://facilitator.ultravioletadao.xyz' + } +)); +``` + +### Quick Start (Client) + +```javascript +import { X402Client } from "x402-client"; + +const client = new X402Client({ + privateKey: process.env.CLIENT_PRIVATE_KEY, + facilitatorUrl: 'https://facilitator.ultravioletadao.xyz', + network: 'avalanche-c-chain' +}); + +const response = await client.post('https://api.example.com/service', { + data: { query: 'your request' } +}); +``` + +### Avalanche Configuration + +- **Mainnet**: Chain ID 43114, USDC settlement, sub-second finality +- **Fuji Testnet**: Chain ID 43113, sandbox environment + +### API Endpoints + +- `GET /health` - Facilitator health verification +- `GET /supported` - Lists compatible payment schemes and networks +- `POST /verify` - Validates payment signatures and requirements +- `POST /settle` - Executes on-chain transfers via EIP-3009 + +### Links + +- Integration: [build.avax.network/integrations/ultravioletadao](https://build.avax.network/integrations/ultravioletadao) +- Facilitator: [facilitator.ultravioletadao.xyz](https://facilitator.ultravioletadao.xyz) +- Website: [ultravioletadao.xyz](https://ultravioletadao.xyz) + +### Pricing + +- **Gas Fees**: $0 for users (100% covered by facilitator) +- **Facilitator Fees**: See official documentation for current fee structure + +--- + +## x402-rs + +**Best For**: High-performance applications, self-hosted infrastructure, Rust developers + +### Overview + +x402-rs is a high-performance Rust implementation perfect for latency-sensitive applications. Offers complete control with self-hosted deployment and zero facilitator fees. + +**Official Documentation**: [github.com/x402-rs/x402-rs](https://github.com/x402-rs/x402-rs) + +### Key Features + +- **High Performance**: < 50ms verification time +- **Low Resource Usage**: Minimal CPU/memory footprint +- **Self-Hosted**: Full control over infrastructure +- **Rust Implementation**: Memory-safe and fast +- **Zero Facilitator Fees**: Only blockchain gas costs +- **Stateless Design**: Never holds user funds +- **OpenTelemetry Support**: Integrates with Honeycomb, Prometheus, Grafana +- **Multi-Network**: EVM chains (Avalanche, Base, Polygon) and Solana + +### Docker Quick Start + +```bash +docker run --env-file .env -p 8080:8080 ukstv/x402-facilitator +``` + +**Required Environment Variables:** +```bash +HOST=0.0.0.0 +PORT=8080 +RPC_URL_AVALANCHE_FUJI=https://api.avax-test.network/ext/bc/C/rpc +RPC_URL_AVALANCHE=https://api.avax.network/ext/bc/C/rpc +SIGNER_TYPE=private-key +EVM_PRIVATE_KEY=0x... +RUST_LOG=info +``` + +### Installation (Rust) + +```bash +cargo add x402-rs +``` + +Requirements: Rust 1.80+ + +### Quick Start (Axum Server) + +```rust +use x402_axum::X402Middleware; +use x402_rs::{USDCDeployment, Network}; +use axum::{Router, routing::get}; + +let x402 = X402Middleware::try_from("https://x402.org/facilitator/").unwrap(); +let usdc = USDCDeployment::by_network(Network::AvalancheFuji); + +let app = Router::new().route("/paid-content", + get(handler).layer( + x402.with_price_tag( + usdc.amount("0.025").pay_to("0xYourAddress").unwrap() + ) + ) +); +``` + +### Quick Start (Client) + +```rust +use x402_reqwest::X402ClientExt; +use ethers::signers::PrivateKeySigner; + +let signer: PrivateKeySigner = "0x...".parse()?; +let client = reqwest::Client::new() + .with_payments(signer) + .prefer(USDCDeployment::by_network(Network::Avalanche)) + .build(); + +let res = client.get("https://example.com/protected").send().await?; +``` + +### Key Components + +1. **x402-rs core**: Protocol types, facilitator traits, payment verification/settlement +2. **Facilitator binary**: Production HTTP server for verifying and settling payments +3. **x402-axum**: Axum middleware for protecting routes +4. **x402-reqwest**: Wrapper for transparent client-side payment handling + +### Avalanche Configuration + +- **Fuji Testnet**: Set `RPC_URL_AVALANCHE_FUJI` for development +- **C-Chain Mainnet**: Set `RPC_URL_AVALANCHE` for production +- Networks are dynamically enabled based on provided RPC URLs + +### Links + +- Integration: [build.avax.network/integrations/x402-rs](https://build.avax.network/integrations/x402-rs) +- GitHub: [github.com/x402-rs/x402-rs](https://github.com/x402-rs/x402-rs) +- Docker Hub: [hub.docker.com/r/ukstv/x402-facilitator](https://hub.docker.com/r/ukstv/x402-facilitator) + +### Pricing + +- **Open Source**: Free (Apache-2.0 license) +- **Self-Hosted**: Only gas costs (~$0.001/tx on Avalanche) +- **Support**: Community-driven + +--- + +## Facilitator Comparison + +> **Note**: All x402 facilitators enable gasless payments for end users. Users sign payment authorizations; facilitators submit transactions and pay gas. Some facilitators absorb gas costs completely (e.g., Ultravioleta), while others pass costs to merchants. + +| Feature | Thirdweb | PayAI | Ultravioleta | x402-rs | +|---------|----------|-------|--------------|---------| +| **Deployment** | Hosted | Hosted | Hosted | Self-Hosted | +| **Multi-Chain** | ✅ | ✅ | ✅ | ✅ | +| **AI Optimized** | ❌ | ✅ | ❌ | ❌ | +| **DAO Governed** | ❌ | ❌ | ✅ | ❌ | +| **Primary Language** | TypeScript | TypeScript | TypeScript | Rust | +| **Verification Speed** | Fast | Fast | Medium | Very Fast | +| **Dashboard** | ✅ | ✅ | ✅ | ❌ | +| **Best For** | Enterprise | AI Agents | Decentralization | Performance | + +*Check official documentation for latest features, pricing, and capabilities.* + +--- + +## Getting Started + +1. **Choose a Facilitator**: Based on your use case and requirements +2. **Visit Integration Page**: [build.avax.network/integrations](https://build.avax.network/integrations) +3. **Read Official Docs**: Each facilitator has comprehensive documentation +4. **Install SDK**: Follow the installation instructions above +5. **Test on Fuji**: Use Avalanche Fuji testnet for development +6. **Deploy to Mainnet**: Go live on Avalanche C-Chain + +--- + +## Summary + +Avalanche supports four major x402 facilitators: **Thirdweb x402** (enterprise), **PayAI** (AI agents), **Ultravioleta DAO** (gasless payments), and **x402-rs** (high-performance). Each offers different deployment models, features, and optimizations. Choose based on your specific needs—or use multiple facilitators to give users flexibility. + +**All facilitators leverage Avalanche's sub-second finality and low fees (~$0.001) to make micropayments economically viable.** + +For the latest information, pricing, and features, always consult the official documentation linked above. From 6d04330117860b25216b70ee0575f3816a59613f Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Mon, 10 Nov 2025 13:23:10 +0100 Subject: [PATCH 17/30] removed implementation from meta.json because is not implemented yet --- content/academy/x402-payment-infrastructure/meta.json | 1 - 1 file changed, 1 deletion(-) diff --git a/content/academy/x402-payment-infrastructure/meta.json b/content/academy/x402-payment-infrastructure/meta.json index ccc3856d90c..b599d4beb64 100644 --- a/content/academy/x402-payment-infrastructure/meta.json +++ b/content/academy/x402-payment-infrastructure/meta.json @@ -11,7 +11,6 @@ "---x402 on Avalanche---", "...04-x402-on-avalanche", "---Implementation Guide---", - "...05-implementation", "get-certificate" ] } From d9f9cc386b48fe243e5b8517696ca326adfd92fb Mon Sep 17 00:00:00 2001 From: alejandro Date: Tue, 11 Nov 2025 18:22:13 -0300 Subject: [PATCH 18/30] instructors fixed --- content/common/intro/instructors.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/content/common/intro/instructors.tsx b/content/common/intro/instructors.tsx index a262703cdff..5102fa2c2b8 100644 --- a/content/common/intro/instructors.tsx +++ b/content/common/intro/instructors.tsx @@ -112,6 +112,7 @@ const instructors: Instructor[] = [ linkedin: "https://www.linkedin.com/in/federico-nardelli-a2969b26a/", github: "https://github.com/federiconardelli7", }, + { name: "Katherine Sullivan", title: "Developer Relations Intern", image: "https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/instructors/katherine-sullivan.jpeg", From 6b0936a1c51c02b76d165d496ca7654c6df8871e Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Thu, 13 Nov 2025 16:22:21 +0100 Subject: [PATCH 19/30] add x402 integration link --- .../02-introduction/01-what-is-x402.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/academy/x402-payment-infrastructure/02-introduction/01-what-is-x402.mdx b/content/academy/x402-payment-infrastructure/02-introduction/01-what-is-x402.mdx index ddf8bf4fb9b..bb15bb3cb05 100644 --- a/content/academy/x402-payment-infrastructure/02-introduction/01-what-is-x402.mdx +++ b/content/academy/x402-payment-infrastructure/02-introduction/01-what-is-x402.mdx @@ -98,7 +98,7 @@ x402 is supported by an ecosystem of **facilitators**—services that handle pay - Handle settlement with merchants - Provide developer tools and SDKs -Popular facilitators on Avalanche include Thirdweb x402, PayAI, Ultravioleta DAO, and x402-rs. We'll explore these in detail in later lessons. +Popular facilitators on Avalanche include Thirdweb x402, PayAI, Ultravioleta DAO, and x402-rs. [You can explore all available facilitators](/integrations#x402). We'll explore these in detail in later lessons. ## Summary From bf444b9f4e1a14d3aa1c1f1ca4ca32d838fe6ca2 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Thu, 13 Nov 2025 16:23:37 +0100 Subject: [PATCH 20/30] divided the payment problem and make it more clear --- .../02-introduction/02-payment-problem.mdx | 96 ++++--------------- 1 file changed, 17 insertions(+), 79 deletions(-) diff --git a/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx b/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx index 882ea4ffb3f..fc50b2cc82d 100644 --- a/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx +++ b/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx @@ -15,59 +15,29 @@ Traditional payment systems create significant friction for both users and devel Every traditional payment interaction requires users to complete at least five time-consuming steps: ### 1. Create Account - -Before making any payment, users must: -- Sign up for a service account -- Provide personal information -- Verify email addresses -- Set up passwords and security - -**Time Impact**: 5-15 minutes per service
-**User Experience**: High abandonment rates during signup +- Sign up for a service account with personal information +- Verify email addresses and set up passwords +- 5-15 minutes per service with high abandonment rates ### 2. Add Payment Method - -After creating an account, users must: -- Enter credit card details -- Complete bank verification -- Wait for payment method approval +- Enter credit card details and complete bank verification - Navigate complex payment forms - -**Time Impact**: 3-10 minutes
-**User Experience**: Security concerns and data privacy issues +- 3-10 minutes with security and privacy concerns ### 3. Complete KYC (Know Your Customer) - -Many services require additional identity verification: -- Submit government-issued ID -- Provide proof of address -- Complete video verification -- Wait for manual approval - -**Time Impact**: Hours to days
-**User Experience**: Privacy concerns and verification delays +- Submit government-issued ID and proof of address +- Complete verification and wait for approval +- Hours to days with privacy concerns ### 4. Buy Credits or Subscribe - -Traditional payment models force prepayment: -- Purchase credits you may not use -- Subscribe to monthly plans -- Commit to minimum purchases -- Lock in before trying the service - -**Time Impact**: Variable
-**User Experience**: Financial commitment before knowing value +- Purchase credits or subscribe to monthly plans before trying +- Commit to minimum purchases without knowing value +- Forces prepayment for uncertain utility ### 5. Manage API Keys - -For API access, developers must: -- Generate and store API keys -- Implement key rotation policies -- Secure keys in environment variables +- Generate, store, and rotate API keys securely - Monitor for key compromise - -**Time Impact**: Ongoing maintenance
-**User Experience**: Security risk and complexity +- Ongoing maintenance and security risk ## Cost Structure Problems @@ -92,13 +62,7 @@ Payment processors hold funds for 2-7 days, creating cash flow challenges for me ## Barriers to Automation -Traditional payments were designed for human-to-merchant interactions, not for automated systems. This creates fundamental barriers: - -- **Manual Account Setup**: Automated systems cannot complete human-centric signup flows (CAPTCHA, email verification, identity checks) -- **Credential Management**: Storing payment credentials creates security and compliance risks -- **Pre-Approval Requirements**: Automated payments require human authorization, preventing autonomous operation - -These barriers make it impossible for AI agents and automated systems to participate in the payment economy. +Traditional payments were designed for human-to-merchant interactions, not for automated systems. Automated systems cannot complete human-centric signup flows like CAPTCHA or email verification, storing payment credentials creates security risks, and pre-approval requirements prevent autonomous operation. These barriers make it impossible for AI agents and automated systems to participate in the payment economy. ## The Micropayment Impossibility @@ -139,26 +103,6 @@ Developers face a painful choice when monetizing APIs: **None of these options are optimal**, creating a gap in the market for pay-per-use API models. -## The AI Agent Problem - -As AI agents become more prevalent, traditional payment systems create impossible barriers: - -### AI Agents Cannot: -1. **Create Accounts**: Most signup flows require human verification (CAPTCHA, email confirmation) -2. **Complete KYC**: Identity verification is designed for humans, not autonomous agents -3. **Store Credentials Securely**: API keys and payment tokens create security vulnerabilities -4. **Make Autonomous Decisions**: Pre-approved payment methods limit AI flexibility -5. **Handle Micropayments**: Transaction fees make small payments impossible - -### What AI Agents Need: -- Instant, permissionless access to resources -- Pay-per-use pricing with no minimums -- Autonomous payment execution -- No account creation or KYC -- Micropayment support (fractions of a cent) - -![AI agents blocked by traditional payment systems](https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/course-images/x402-payment-infrastructure/HowAIAgentsMakePayments.png) - ## Real-World Impact These limitations have real consequences: @@ -175,19 +119,13 @@ These limitations have real consequences: - Share payment details with many services - Pay for unused capacity -### For AI Builders -- Cannot create autonomous payment systems -- Limited to pre-approved payment rails -- Unable to enable AI-to-AI commerce -- Forced into complex workarounds - ## The Need for a New Approach -Traditional payment systems were designed for a different era—before micropayments, before API economies, and before AI agents. We need a payment protocol that: +Traditional payment systems were designed for a different era—before micropayments and before API economies. We need a payment protocol that: 1. **Eliminates Account Requirements**: Instant, permissionless access 2. **Supports Micropayments**: Economically viable payments of any size -3. **Enables Automation**: AI agents can pay autonomously +3. **Enables Automation**: Autonomous payment execution without human intervention 4. **Settles Instantly**: No 2-7 day delays 5. **Charges Fairly**: No percentage fees or high fixed costs 6. **Works with HTTP**: Native integration with web infrastructure @@ -196,4 +134,4 @@ This is exactly what the x402 protocol provides. ## Summary -Traditional payment systems create insurmountable barriers for modern digital commerce through account requirements, high fees, settlement delays, and automation limitations. These systems make micropayments impossible, force developers into suboptimal business models, and prevent AI agents from participating in the economy. The x402 protocol addresses all of these limitations by providing instant, permissionless, HTTP-native payments with minimal fees. +Traditional payment systems create insurmountable barriers for modern digital commerce through account requirements, high fees, settlement delays, and automation limitations. These systems make micropayments impossible and force developers into suboptimal business models. The x402 protocol addresses all of these limitations by providing instant, permissionless, HTTP-native payments with minimal fees. From 580b428808cb1ceeb6d3bd8e8257f49338784832 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Thu, 13 Nov 2025 16:24:13 +0100 Subject: [PATCH 21/30] add the second part of the problem focus on ai agent --- .../02-introduction/03-ai-agent-problem.mdx | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 content/academy/x402-payment-infrastructure/02-introduction/03-ai-agent-problem.mdx diff --git a/content/academy/x402-payment-infrastructure/02-introduction/03-ai-agent-problem.mdx b/content/academy/x402-payment-infrastructure/02-introduction/03-ai-agent-problem.mdx new file mode 100644 index 00000000000..e7531da487a --- /dev/null +++ b/content/academy/x402-payment-infrastructure/02-introduction/03-ai-agent-problem.mdx @@ -0,0 +1,50 @@ +--- +title: The AI Agent Payment Problem +description: Understanding why AI agents need a new payment paradigm and how x402 enables autonomous commerce. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: Bot +--- + +## Introduction + +AI agents face a fundamental problem: traditional payment systems require human verification and account management, making autonomous machine-to-machine commerce impossible. + +## Why Traditional Payments Block AI Agents + +AI agents cannot participate in traditional payment systems for several critical reasons: + +### Cannot Create Accounts +Most signup flows require human verification through CAPTCHA, email confirmation, or phone verification. AI agents cannot complete these human-centric verification processes, preventing them from even accessing services. + +### Cannot Complete KYC +Identity verification (Know Your Customer) is designed specifically for humans—requiring government-issued IDs, proof of address, and sometimes video verification. AI agents have no legal identity and cannot complete these requirements. + +### Cannot Handle Micropayments +Transaction fees make small payments economically impossible. When an AI agent needs to pay \$0.001 for a single API call, traditional payment fees of $0.30+ make the transaction infeasible. + +### Credential Management Risks +Storing API keys and payment credentials creates security vulnerabilities. AI agents would need to securely manage numerous credentials across services, creating attack vectors and compliance challenges. + +### Limited Autonomy +Pre-approved payment methods and spending limits require human authorization, defeating the purpose of autonomous agents. Agents cannot dynamically adjust their resource usage or respond to changing market conditions. + +## What AI Agents Need + +For AI agents to participate in the digital economy, they need: + +- **Instant, Permissionless Access**: No account creation, KYC verification, or identity requirements +- **Pay-Per-Use Pricing**: No monthly subscriptions or minimum commitments +- **Autonomous Payment Execution**: Agents pay without human intervention +- **Micropayment Support**: Economically viable payments of any size, including fractions of a cent +- **No Credential Management**: Direct payment without managing API keys or sensitive tokens + +![AI agents blocked by traditional payment systems](https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/course-images/x402-payment-infrastructure/HowAIAgentsMakePayments.png) + +## How x402 Solves This + +The x402 protocol addresses these challenges through: + +- **HTTP-Native, No Accounts**: Payment requests work through standard HTTP without requiring account creation or identity verification +- **Instant Micropayments**: Ultra-low transaction costs and ~2-second settlement make payments of any size economically viable +- **Fully Autonomous**: Agents pay automatically based on HTTP 402 responses with no human intervention or credential storage \ No newline at end of file From 66577f47f839223c9c78032ede48b2e30ef23dea Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Thu, 13 Nov 2025 16:25:57 +0100 Subject: [PATCH 22/30] moved the use case chapter. made it less heavy to read and less confusing and less numbers --- .../02-introduction/03-use-cases.mdx | 374 ------------------ .../02-introduction/04-use-cases.mdx | 199 ++++++++++ 2 files changed, 199 insertions(+), 374 deletions(-) delete mode 100644 content/academy/x402-payment-infrastructure/02-introduction/03-use-cases.mdx create mode 100644 content/academy/x402-payment-infrastructure/02-introduction/04-use-cases.mdx diff --git a/content/academy/x402-payment-infrastructure/02-introduction/03-use-cases.mdx b/content/academy/x402-payment-infrastructure/02-introduction/03-use-cases.mdx deleted file mode 100644 index ef91a46b9cd..00000000000 --- a/content/academy/x402-payment-infrastructure/02-introduction/03-use-cases.mdx +++ /dev/null @@ -1,374 +0,0 @@ ---- -title: x402 Use Cases -description: Exploring practical applications of the x402 protocol for AI agents, micropayments, and content monetization. -updated: 2025-11-03 -authors: [Federico Nardelli] -icon: Lightbulb ---- - -## Overview - -The x402 protocol unlocks entirely new business models and use cases that were previously impossible with traditional payment systems. By enabling instant, permissionless micropayments, x402 creates opportunities across AI agents, content creation, API monetization, and more. - -## AI Agent Payments - -AI agents represent one of the most compelling use cases for x402, enabling autonomous machine-to-machine commerce. - -### Autonomous Resource Access - -AI agents can operate autonomously in the x402 economy without human intervention. This enables entirely new capabilities: - -- **Real-Time Data Feeds**: Pay for market data, weather information, or sensor readings on-demand -- **Compute Resources**: Purchase processing power dynamically based on workload needs -- **Premium APIs**: Access services without pre-approval or account creation -- **Training Datasets**: Acquire machine learning data through pay-per-use models -- **Cloud Services**: Utilize infrastructure with simple, transparent pricing - -This fundamentally transforms how AI systems interact with digital resources and services. - -**Example Scenario**: -``` -An AI agent analyzing market trends needs real-time financial data. - -Traditional Approach (Impossible): -1. Agent would need to create account (can't complete CAPTCHA) -2. Agent would need to complete KYC (can't verify identity) -3. Agent would need to subscribe monthly (can't predict usage) -4. Agent needs human intervention for setup - -x402 Approach (Seamless): -1. Agent sends HTTP request for data -2. Server responds with 402 "Payment Required" -3. Agent automatically pays $0.0001 in USDC -4. Data returned in 2 seconds -``` - -![x402 payment flow for AI agents](https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/course-images/x402-payment-infrastructure/http402PaymentFlow.png) - -### Inter-Agent Commerce - -x402 enables a thriving AI-to-AI economy where specialized agents monetize their services to other agents: - -- **Data Agents**: Sell curated datasets to analysis agents -- **Compute Agents**: Rent processing power to resource-constrained systems -- **Specialized Agents**: Offer expert analysis to general-purpose AI -- **Storage Agents**: Provide decentralized storage solutions to data-heavy applications - -This creates an entire autonomous machine-to-machine economy that traditional payment systems—with their KYC requirements and subscription models—could never support. - -### Dynamic Cost Optimization - -AI agents leverage x402's transparent pricing to intelligently manage costs: - -- **Price Comparison**: Compare rates across multiple service providers in real-time -- **Dynamic Switching**: Automatically move to better providers based on pricing and performance -- **Success-Based Payment**: Pay only for successful operations, not failed attempts -- **Value Optimization**: Balance cost and quality autonomously without human oversight -- **Budget Management**: Track spending and adjust resource usage automatically - -## Micropayment Business Models - -x402 makes micropayments economically viable, enabling pay-per-use models that were previously impossible. - -### Pay-Per-API-Request - -Developers can charge minimal amounts per API call: -- \$0.0001 per geocoding request -- \$0.001 per image processing operation -- \$0.01 per AI inference call -- \$0.10 per complex computation - -These micro-amounts are economically viable with x402's ultra-low transaction costs, unlike traditional payment systems where fees exceed the payment value itself. - -![Traditional vs x402 payment economics](https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/course-images/x402-payment-infrastructure/MicropaymentForTheInternet.png) - -**Economics Comparison**: -``` -Traditional Payment: -API request value: $0.001 -Processing fee: $0.30 -Net to merchant: -$0.299 (99,700% loss) - -x402 Payment: -API request value: $0.001 -Gas fee: $0.0001 -Net to merchant: $0.0009 (10% fee, sustainable) -``` - -This dramatic difference makes micropayments economically viable for the first time, enabling entirely new business models that were impossible with traditional payment infrastructure. - -### Usage-Based Infrastructure Pricing - -Services can charge exactly for what users consume: -- Cloud storage: \$0.0001 per MB per day -- Compute time: \$0.001 per CPU-minute -- Network bandwidth: \$0.00001 per MB transferred -- Database queries: \$0.0001 per query - -Users only pay for actual consumption, not estimated capacity. - -## Content Monetization - -x402 enables flexible, granular monetization for content creators through pay-per-content models. - -### Flexible Pricing Models - -Instead of forcing \$10/month subscriptions, creators can implement various pricing strategies: - -**Per-Content Pricing:** -- Articles and blog posts: \$0.05-\$0.25 per read -- Videos and podcasts: \$0.10-\$0.50 per view -- Tutorials and courses: \$0.25-\$2.00 per module -- Research papers: \$0.50-\$5.00 per download - -**Tiered Access:** -- Free tier: Basic content available to all -- Standard tier (\$0.10-\$0.25): Regular premium content -- Premium tier (\$0.50-\$1.00): In-depth analysis and exclusive content -- Expert tier (\$2.00+): Specialized research and consulting - -**Dynamic Pricing:** -- Demand-based: Higher prices for trending or popular content -- Time-based: Lower prices for older content or off-peak access -- User-based: Discounts for frequent readers or bulk purchases -- Value-based: Each piece priced according to depth and complexity - -**Benefits for Users:** -- Pay only for content you actually consume -- Try individual pieces before committing to subscriptions -- No recurring charges or cancellation hassles -- Granular control over spending - -**Benefits for Creators:** -- Monetize every piece of content, not just loyal subscribers -- Lower barrier to first payment increases conversion -- Revenue from casual readers who won't subscribe -- Direct payments without platform fees taking 30-50% - -## API Monetization - -Developers can monetize APIs in ways that were previously impossible. - -### No-Subscription API Access - -Instead of forcing users into monthly plans: -- Pay per request -- No minimum commitment -- No API key management -- No account creation - -**Example**: -``` -Image Processing API - -Traditional Model: -- Free: 100 requests/month (insufficient for many users) -- Pro: $29/month for 10,000 requests (too expensive for casual users) -- Enterprise: Custom pricing (high commitment) - -x402 Model: -- $0.001 per request -- No monthly fee -- Pay exactly for what you use -- Instant activation -``` - -### Tiered Service Quality - -APIs can implement sophisticated tiered pricing based on service quality and performance guarantees: - -- **Standard Tier**: $0.001 per request with best-effort latency -- **Priority Tier**: $0.005 per request with guaranteed sub-100ms response times -- **Exclusive Tier**: $0.01 per request with dedicated resources for critical workloads -- **Dynamic Adjustment**: Users pay precisely for the quality they need -- **Flexible Spending**: Adjust tier based on current requirements and budget - -This flexibility allows users to balance cost and performance dynamically. - -### Metered Resource Access - -Beyond simple per-request pricing, APIs can implement metered charging based on actual consumption: - -- **Computational Complexity**: Heavy computations cost more than simple queries -- **Response Time Guarantees**: Premium pricing for faster processing -- **Data Volume**: Charges scale with amount of data returned -- **Result Accuracy**: Higher precision costs more than approximations -- **Fair Pricing**: Natural market incentives for efficient API design and usage - -## Web3 and DeFi Applications - -x402 integrates seamlessly with blockchain-based applications, enabling new monetization models for decentralized services. - -### Decentralized Data Markets - -Oracle services and price feeds can monetize their infrastructure through granular pricing: - -- **Per-Query Pricing**: Charge for each data request instead of subscriptions -- **Update Billing**: Bill per data refresh or update cycle -- **Historical Data**: Offer pay-per-record access to historical datasets -- **Real-Time Streams**: Price streaming data per second of access -- **Lower Barriers**: Make data accessible to smaller consumers - -This aligns payment directly with value delivered. - -### Account-Free DApp Access - -Decentralized applications can offer premium features through instant micropayments: - -- **Portfolio Tracking**: $0.10 per analysis -- **Trade Simulation**: $0.50 per backtest execution -- **Yield Optimization**: $1.00 per strategy execution -- **Risk Analysis**: $0.25 per assessment -- **No Authentication**: No user accounts or complex authentication required - -Users pay only for the specific analyses they need, when they need them. - -### Cross-Chain Service Access - -x402's payment layer enables seamless cross-chain transactions: - -- **Accept on Multiple Chains**: Receive payments on one blockchain (like Avalanche) -- **Operate on Any Chain**: Run services on a different blockchain -- **No Bridge Complexity**: Avoid complex bridge infrastructure -- **No Wrapped Tokens**: Direct payment without token wrapping -- **Seamless Experience**: Users don't worry about chain compatibility - -## Enterprise Applications - -x402 transforms B2B interactions by enabling frictionless, usage-based commerce between organizations. - -### Inter-Company API Access - -Companies can share APIs across organizational boundaries without complex contracts: - -- **Instant Integration**: Partners connect and start using APIs immediately -- **Exact Usage Billing**: Charge for actual consumption, not estimated capacity -- **Real-Time Settlement**: Payments settle instantly, no invoicing delays -- **No Procurement Cycles**: Eliminate lengthy B2B sales processes -- **Fair Compensation**: Providers paid based on actual value delivered - -This eliminates the overhead of traditional B2B sales cycles. - -### Microservice Monetization - -Internal services can implement chargeback models based on actual consumption: - -- **Department Billing**: Share infrastructure with automatic usage-based billing -- **Accurate Cost Allocation**: Track spending without manual overhead -- **Real-Time Monitoring**: Budget tracking and alerts in real-time -- **Resource Optimization**: Identify cost-saving opportunities automatically -- **Shared Infrastructure**: Business units collaborate efficiently with clear accounting - -Organizations can optimize resource utilization and control costs precisely. - -### Data Marketplace - -Enterprises can monetize proprietary data assets through micropayments: - -- **Real-Time Intelligence**: Sell live business data per query -- **Historical Transactions**: Offer historical data on pay-per-record basis -- **Market Research**: Monetize research findings per download -- **Industry Benchmarks**: Share benchmarks per dataset accessed -- **New Revenue Streams**: Generate income from existing data infrastructure - -## Novel Use Cases - -x402 unlocks entirely new possibilities across emerging technology sectors. - -### Pay-Per-Minute Cloud Resources - -Cloud providers can implement true usage-based pricing with granular billing: - -- **VM Billing**: Per-second billing for virtual machines -- **GPU Access**: On-demand GPU charged by the minute -- **Serverless Functions**: Billed per invocation -- **Storage**: Priced by the millisecond of usage -- **No Over-Provisioning**: Customers pay only for what they consume - -This granular pricing eliminates waste while enabling cost-effective access to expensive compute resources. - -### Knowledge Economy - -AI and knowledge services can monetize at unprecedented granularity: - -- **Expert Systems**: Charge per query for specialized knowledge -- **Language Models**: Bill per token generated -- **Image Generators**: Price per image creation -- **Code Assistants**: Charge per suggestion or completion -- **Accessible AI**: Users get advanced capabilities without expensive subscriptions - -This enables sustainable business models for AI services. - -### Internet of Things (IoT) - -x402 enables autonomous machine-to-machine payments in IoT ecosystems: - -- **Bandwidth Payments**: Devices independently pay for network connectivity -- **Data Processing**: Sensors purchase processing capacity as needed -- **Control Signals**: Actuators pay for control commands -- **Packet Delivery**: Networks charge per packet delivered -- **Self-Sustaining Networks**: Devices manage economic relationships autonomously - -This creates IoT networks that operate without human payment intervention. - -### Gaming and Virtual Worlds - -Virtual economies can implement sophisticated payment models: - -- **Pay-Per-Session**: Gaming charged by time played -- **Item Rentals**: Temporary access to in-game items -- **Virtual Real Estate**: Access fees for digital property -- **NPC Services**: Non-player characters that charge for services -- **Dynamic Markets**: Value exchange mirrors real-world economics - -This creates more realistic and dynamic virtual economies. - -## Economic Impact - -The x402 protocol enables a **true pay-per-use economy**: - -### For Consumers - -Consumers benefit from a payment model that eliminates waste and commitment: - -- **No Unused Capacity**: Pay only for services actually consumed -- **Try Before Committing**: Test services without long-term subscriptions -- **Granular Cost Control**: Track spending at the individual transaction level -- **No Subscription Fatigue**: Eliminate managing multiple recurring payments -- **Flexible Usage**: Scale consumption up or down without penalties - -This creates a truly user-centric payment experience. - -### For Developers - -Developers gain unprecedented flexibility in monetizing their services: - -- **Monetize Any Service**: From tiny APIs to large platforms, any size works -- **No Processing Overhead**: Minimal fees don't eat into profit margins -- **Instant Revenue**: Payments settle in real-time, not days later -- **Flexible Pricing**: Implement any strategy from simple to complex tiered models -- **No Infrastructure Limits**: Payment system doesn't constrain business models - -Revenue recognition happens instantly as payments settle in real-time. - -### For AI Builders - -AI builders can create truly autonomous economic systems: - -- **Autonomous Commerce**: AI agents operate independently without human intervention -- **Self-Sustaining Agents**: Create agents that manage their own budgets -- **AI-to-AI Marketplaces**: Build platforms where specialized services trade automatically -- **No Authorization Friction**: Eliminate human approval from machine transactions -- **Budget-Aware Systems**: AI optimizes spending based on value and constraints - -This enables the first truly autonomous AI economy. - -## Summary - -The x402 protocol unlocks use cases that span AI agent commerce, micropayment business models, content monetization, API access, Web3 applications, enterprise solutions, and novel applications across industries. By making micropayments economically viable and enabling autonomous payments, x402 creates opportunities for entirely new digital economies built on instant, permissionless transactions. - -## Additional Resources - -- [x402 Whitepaper](https://www.x402.org/x402-whitepaper.pdf) - Technical specification and use cases -- [x402 GitHub Repository](https://github.com/coinbase/x402) - Open source implementation and examples -- [PayAI Documentation](https://docs.payai.network) - Facilitator integration guides diff --git a/content/academy/x402-payment-infrastructure/02-introduction/04-use-cases.mdx b/content/academy/x402-payment-infrastructure/02-introduction/04-use-cases.mdx new file mode 100644 index 00000000000..3f460cb3559 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/02-introduction/04-use-cases.mdx @@ -0,0 +1,199 @@ +--- +title: x402 Use Cases +description: Exploring practical applications of the x402 protocol for AI agents, micropayments, and content monetization. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: Lightbulb +--- + +## Overview + +The x402 protocol enables new business models and use cases through instant, permissionless micropayments, creating opportunities across AI agents, content creation, API monetization, and more. + +## AI Agent Payments + +AI agents represent a key use case for x402, enabling autonomous machine-to-machine commerce. + +### Autonomous Resource Access + +AI agents can operate autonomously in the x402 economy without human intervention: + +- **Real-Time Data Feeds**: Pay for market data, weather information, or sensor readings on-demand +- **Compute Resources**: Purchase processing power dynamically based on workload needs +- **Premium APIs**: Access services without pre-approval or account creation +- **Training Datasets**: Acquire machine learning data through pay-per-use models +- **Cloud Services**: Utilize infrastructure with simple, transparent pricing + +This transforms how AI systems interact with digital resources and services. + +**Example Scenario**: +``` +An AI agent analyzing market trends needs real-time financial data. + +Traditional Approach (Impossible): +1. Agent would need to create account (can't complete CAPTCHA) +2. Agent would need to complete KYC (can't verify identity) +3. Agent would need to subscribe monthly (can't predict usage) +4. Agent needs human intervention for setup + +x402 Approach (Seamless): +1. Agent sends HTTP request for data +2. Server responds with 402 "Payment Required" +3. Agent automatically pays a micropayment in USDC +4. Data returned immediately +``` + +![x402 payment flow for AI agents](https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/course-images/x402-payment-infrastructure/http402PaymentFlow.png) + +### Inter-Agent Commerce + +x402 enables an AI-to-AI economy where specialized agents monetize their services to other agents: + +- **Data and Compute Agents**: Sell curated datasets or rent processing power to other agents +- **Specialized Services**: Offer expert analysis, storage solutions, or domain-specific capabilities + +This creates an autonomous machine-to-machine economy that traditional payment systems cannot support. + +### Dynamic Cost Optimization + +AI agents leverage x402's transparent pricing to intelligently manage costs: + +- **Price Comparison and Switching**: Compare rates across providers and automatically move to better options +- **Success-Based Payment**: Pay only for successful operations, not failed attempts +- **Budget Management**: Track spending and adjust resource usage autonomously + +## Micropayment Business Models + +x402 makes micropayments economically viable, enabling pay-per-use models. + +### Pay-Per-API-Request + +Developers can charge minimal amounts per API call, from fractions of a cent to dollars depending on computational complexity. These micro-amounts are economically viable with x402's ultra-low transaction costs, unlike traditional payment systems where fees exceed the payment value itself. + +![Traditional vs x402 payment economics](https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/course-images/x402-payment-infrastructure/MicropaymentForTheInternet.png) + +### Usage-Based Infrastructure Pricing + +Services can charge users exactly for what they consume—whether cloud storage, compute time, network bandwidth, or database queries. Users only pay for actual consumption, not estimated capacity. + +## Content Monetization + +x402 enables flexible, granular monetization for content creators through pay-per-content models. + +### Flexible Pricing Models + +Instead of forcing monthly subscriptions, creators can implement pay-per-content models that better serve both creators and consumers. With x402, creators can charge for individual articles, videos, tutorials, or research papers, allowing users to pay only for what they consume. + +**Benefits for Users:** +- Pay only for content consumed with no recurring charges +- Try individual pieces before committing to subscriptions + +**Benefits for Creators:** +- Monetize every piece of content, including from casual readers +- Direct payments without platform fees taking 30-50% + +## API Monetization + +Developers can monetize APIs through flexible pay-per-use models. + +### No-Subscription API Access + +Instead of forcing users into monthly plans, x402 enables pay-per-request pricing with no minimum commitment, API key management, or account creation. Users pay exactly for what they use with instant activation. + +### Tiered Service Quality + +APIs can implement sophisticated tiered pricing based on service quality and performance guarantees, allowing users to balance cost and performance dynamically based on their needs. Services can charge differently for standard best-effort processing versus priority processing with guaranteed response times. + +### Metered Resource Access + +Beyond simple per-request pricing, APIs can implement metered charging based on actual consumption, such as computational complexity, data volume returned, or result accuracy. This creates natural market incentives for efficient API design and usage. + +## Web3 and DeFi Applications + +x402 integrates seamlessly with blockchain-based applications, enabling new monetization models for decentralized services. + +### Decentralized Data Markets + +Oracle services and price feeds can monetize their infrastructure through granular pricing: + +- **Per-Query and Update Billing**: Charge for each data request or refresh cycle instead of subscriptions +- **Historical and Real-Time Data**: Offer pay-per-record access or stream pricing +- **Lower Barriers**: Make data accessible to smaller consumers + +This aligns payment directly with value delivered. + +### Account-Free DApp Access + +Decentralized applications can offer premium features through instant micropayments for services like portfolio tracking, trade simulation, yield optimization, and risk analysis. No user accounts or complex authentication required—users pay only for the specific analyses they need, when they need them. + +### Cross-Chain Service Access + +x402's payment layer enables seamless cross-chain transactions: + +- **Multi-Chain Compatibility**: Receive payments on one blockchain (like Avalanche) while running services on another +- **No Bridge Complexity**: Direct payment without complex bridge infrastructure or token wrapping +- **Seamless Experience**: Users don't worry about chain compatibility + +## Enterprise Applications + +x402 transforms B2B interactions by enabling frictionless, usage-based commerce between organizations. + +### Inter-Company API Access + +Companies can share APIs across organizational boundaries without complex contracts: + +- **Instant Integration and Billing**: Partners connect immediately with exact usage-based charging +- **No Procurement Cycles**: Eliminate lengthy B2B sales processes +- **Fair Compensation**: Providers paid based on actual value delivered + +### Microservice Monetization + +Internal services can implement chargeback models based on actual consumption: + +- **Department Billing**: Share infrastructure with automatic usage-based billing and accurate cost allocation +- **Real-Time Monitoring**: Budget tracking, alerts, and cost optimization +- **Shared Infrastructure**: Business units collaborate efficiently with clear accounting + +### Data Marketplace + +Enterprises can monetize proprietary data assets through micropayments: + +- **Real-Time and Historical Data**: Sell live business data or historical transactions per query or record +- **Research and Benchmarks**: Monetize research findings and industry benchmarks per access +- **New Revenue Streams**: Generate income from existing data infrastructure + +## Novel Use Cases + +x402 enables new possibilities across emerging technology sectors. + +### Pay-Per-Minute Cloud Resources + +Cloud providers can implement true usage-based pricing with granular billing for virtual machines, GPU access, serverless functions, and storage. This granular pricing eliminates waste while enabling cost-effective access to expensive compute resources. + +### Knowledge Economy + +AI and knowledge services can monetize at unprecedented granularity, such as charging per query for expert systems, per token for language models, or per image for generators. This enables sustainable business models for AI services without expensive subscriptions. + +### Internet of Things (IoT) and Gaming + +x402 enables autonomous machine-to-machine payments in IoT ecosystems, where devices independently pay for network connectivity, data processing, and control signals. Similarly, virtual economies in gaming can implement sophisticated payment models like pay-per-session gaming, item rentals, or NPC services that charge for interactions. + +## Economic Impact + +The x402 protocol enables a **true pay-per-use economy** that benefits all participants: + +**For Consumers:** Pay only for services actually consumed, test services without long-term subscriptions, and eliminate subscription fatigue through granular cost control. + +**For Developers:** Monetize any service regardless of size, avoid processing overhead eating into margins, and implement flexible pricing strategies without infrastructure limitations. + +**For AI Builders:** Create truly autonomous economic systems where AI agents operate independently, manage their own budgets, and participate in AI-to-AI marketplaces without human authorization friction. + +## Summary + +The x402 protocol unlocks use cases that span AI agent commerce, micropayment business models, content monetization, API access, Web3 applications, enterprise solutions, and novel applications across industries. By making micropayments economically viable and enabling autonomous payments, x402 creates opportunities for entirely new digital economies built on instant, permissionless transactions. + +## Additional Resources + +- [x402 Whitepaper](https://www.x402.org/x402-whitepaper.pdf) - Technical specification and use cases +- [x402 GitHub Repository](https://github.com/coinbase/x402) - Open source implementation and examples +- [PayAI Documentation](https://docs.payai.network) - Facilitator integration guides From e5d390c665b89495227f83348998c18c83ef871b Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Fri, 14 Nov 2025 19:15:30 +0100 Subject: [PATCH 23/30] minor modifications --- .../03-technical-architecture/01-payment-flow.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/01-payment-flow.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/01-payment-flow.mdx index 2191eba02a7..e72439fd8ab 100644 --- a/content/academy/x402-payment-infrastructure/03-technical-architecture/01-payment-flow.mdx +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/01-payment-flow.mdx @@ -65,7 +65,7 @@ Host: example.com X-PAYMENT: eyJ4NDAyVmVyc2lvbiI6MSwic2NoZW1lIjoiZXhhY3QiLCJuZXR3b3JrIjoiYXZhbGFuY2hlLWZ1amkiLCJwYXlsb2FkIjp7InNpZ25hdHVyZSI6IjB4MTIzNC4uLiIsImF1dGhvcml6YXRpb24iOnsiZnJvbSI6IjB4MTIzNC4uLiIsInRvIjoiMHg3NDJkMzUuLi4iLCJ2YWx1ZSI6IjEwMDAwIiwidmFsaWRBZnRlciI6IjE3NDA2NzIwODkiLCJ2YWxpZEJlZm9yZSI6IjE3NDA2NzIxNTQiLCJub25jZSI6IjB4MzQ1Ni4uLiJ9fX0= ``` -The client does NOT submit a blockchain transaction. The authorization is gasless—the server or facilitator will submit it. For details on the `X-PAYMENT` header structure, see [HTTP Headers](./02-http-headers#x-payment-header). +The client does NOT submit a blockchain transaction. The authorization is gasless—the server or facilitator will submit it. For details on the `X-PAYMENT` header structure, see [X-PAYMENT Header](./03-x-payment-header). ### Step 4: Server Verifies, Settles, and Returns Resource @@ -345,7 +345,7 @@ Each payment is independent. No sessions, no stored state, no account management Payment proofs can only be used once. Replay attacks are prevented by on-chain verification. -For comprehensive security details, see [Security Considerations](./05-security-considerations). +For comprehensive security details, see [Security Considerations](./07-security-considerations). ## Summary From f1a0f3be5991a7b3d810d5ce7518eceb08e91d1d Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Fri, 14 Nov 2025 19:18:28 +0100 Subject: [PATCH 24/30] deliver the same content with less words and be more focus on the most important topics --- .../05-security-considerations.mdx | 395 ------------------ .../07-security-considerations.mdx | 171 ++++++++ 2 files changed, 171 insertions(+), 395 deletions(-) delete mode 100644 content/academy/x402-payment-infrastructure/03-technical-architecture/05-security-considerations.mdx create mode 100644 content/academy/x402-payment-infrastructure/03-technical-architecture/07-security-considerations.mdx diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/05-security-considerations.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/05-security-considerations.mdx deleted file mode 100644 index 2ca82749b94..00000000000 --- a/content/academy/x402-payment-infrastructure/03-technical-architecture/05-security-considerations.mdx +++ /dev/null @@ -1,395 +0,0 @@ ---- -title: Security Considerations -description: Understanding replay attack prevention, time-bounded authorizations, and settlement monitoring in x402. -updated: 2025-11-03 -authors: [Federico Nardelli] -icon: Shield ---- - -## Overview - -The x402 protocol implements multiple layers of security to protect against common attack vectors while maintaining a seamless user experience. These security measures are built on battle-tested Ethereum standards (EIP-712, EIP-3009) and blockchain cryptography. - -## Replay Attack Prevention - -Replay attacks occur when an attacker intercepts a valid payment authorization and attempts to reuse it multiple times. x402 prevents this through three complementary mechanisms: - -### 1. Nonce-Based Protection - -Each payment authorization includes a unique random nonce (32-byte hex string): - -```javascript -const nonce = ethers.randomBytes(32); -// Example: 0x3456789012345678901234567890123456789012345678901234567890123456 -``` - -The USDC contract (following EIP-3009) tracks which nonces have been used on-chain. When a `transferWithAuthorization` is executed: - -1. The contract checks if the nonce has been used before -2. If the nonce is new, the transfer proceeds and the nonce is marked as used -3. If the nonce was already used, the transaction reverts with an error - -**This makes each authorization single-use**. Even if an attacker intercepts the authorization, they cannot reuse it because the nonce is already consumed on-chain. - -### 2. Time-Bounded Authorizations - -Every authorization includes `validAfter` and `validBefore` timestamps (Unix time in seconds): - -```json -{ - "validAfter": "1740672089", // January 7, 2025, 10:00:00 AM UTC - "validBefore": "1740672389" // January 7, 2025, 10:05:00 AM UTC (5 minutes later) -} -``` - -The USDC contract enforces these timing constraints: -- If current time < `validAfter`: Transaction reverts (not yet valid) -- If current time ≥ `validBefore`: Transaction reverts (expired) -- Only between these times: Transaction can execute - -**Best practices**: -- Set short validity windows (5-10 minutes) for most payments -- For delayed/scheduled payments, set appropriate `validAfter` -- Never set `validBefore` too far in the future (increases replay risk if nonce tracking fails) - -**Example timing strategy**: -```javascript -const now = Math.floor(Date.now() / 1000); -const authorization = { - validAfter: now.toString(), // Valid immediately - validBefore: (now + 300).toString(), // Expires in 5 minutes - // ... other fields -}; -``` - -### 3. Transaction Hash Uniqueness - -Each blockchain transaction has a unique hash. Merchants should track received transaction hashes to ensure they don't fulfill the same payment twice: - -```javascript -// Server-side tracking -const processedTransactions = new Set(); - -function fulfillPayment(txHash, resource) { - if (processedTransactions.has(txHash)) { - throw new Error("Payment already fulfilled"); - } - - // Deliver resource to user - deliverResource(resource); - - // Mark transaction as processed - processedTransactions.add(txHash); -} -``` - -**Why this matters**: Even though blockchain nonces prevent double-spending, merchants should track which payments they've already fulfilled. This prevents edge cases where: -- A facilitator sends duplicate settlement notifications -- Network issues cause duplicate webhook deliveries -- Multiple facilitators process the same authorization (if incorrectly configured) - -## Signature Validation - -All payment authorizations use EIP-712 typed structured data signatures, providing cryptographic proof that the user authorized the payment. - -### What EIP-712 Signatures Protect Against - -1. **Forgery**: Only the user's private key can create a valid signature -2. **Tampering**: Changing any field invalidates the signature -3. **Phishing**: The signature includes domain binding (verifyingContract address) -4. **Man-in-the-middle**: The signature covers all payment details - -### Server-Side Signature Verification - -Facilitators must validate signatures before submitting transactions: - -```javascript -import { verifyTypedData } from 'ethers'; - -function validatePaymentSignature(payload) { - const { signature, authorization } = payload.payload; - const { network } = payload; - - // EIP-712 domain for USDC on Avalanche Fuji - const domain = { - name: "USD Coin", - version: "2", - chainId: 43113, // Avalanche Fuji - verifyingContract: "0x5425890298aed601595a70AB815c96711a31Bc65" - }; - - // EIP-712 type definition - const types = { - TransferWithAuthorization: [ - { name: "from", type: "address" }, - { name: "to", type: "address" }, - { name: "value", type: "uint256" }, - { name: "validAfter", type: "uint256" }, - { name: "validBefore", type: "uint256" }, - { name: "nonce", type: "bytes32" } - ] - }; - - // Recover signer address from signature - const recovered = verifyTypedData( - domain, - types, - authorization, - signature - ); - - // Verify the signer matches the 'from' address - if (recovered.toLowerCase() !== authorization.from.toLowerCase()) { - throw new Error("Invalid signature: signer does not match 'from' address"); - } - - return true; -} -``` - -**Key validation steps**: -1. Recover the signer address from the signature -2. Verify it matches the `from` field in the authorization -3. Check all other fields (amount, recipient, timing) -4. Only submit to blockchain if everything validates - -### On-Chain Signature Verification - -The USDC contract performs the same signature validation on-chain when `transferWithAuthorization` is called. This provides **trustless verification**—even if the facilitator is malicious, an invalid signature will cause the transaction to revert. - -## Authorization Timing Validation - -Facilitators should validate timing constraints before submitting transactions to avoid wasting gas on expired authorizations: - -```javascript -function validateTiming(authorization) { - const now = Math.floor(Date.now() / 1000); - const validAfter = parseInt(authorization.validAfter); - const validBefore = parseInt(authorization.validBefore); - - if (now < validAfter) { - throw new Error("Authorization not yet valid"); - } - - if (now >= validBefore) { - throw new Error("Authorization expired"); - } - - // Optional: Warn if expiring soon - if (now + 30 >= validBefore) { - console.warn("Authorization expires in less than 30 seconds"); - } - - return true; -} -``` - -This prevents: -- Submitting transactions that will revert due to timing -- Wasting gas fees on failed transactions -- Poor user experience from delayed settlements - -## Settlement Monitoring - -Facilitators monitor the blockchain in real-time to detect when payments are settled and to verify transaction success. - -### What Facilitators Monitor - -After submitting a `transferWithAuthorization` transaction: - -1. **Transaction Confirmation**: Wait for the transaction to be included in a block -2. **Transaction Success**: Verify the transaction status is `1` (success), not `0` (failure) -3. **Event Emissions**: Check that the `Transfer` event was emitted with correct parameters -4. **Finality**: On Avalanche, wait ~1-2 seconds for finality - -### Webhook Notifications - -Most facilitators provide webhook notifications when settlements complete: - -```javascript -// Merchant server receives webhook -app.post('/webhooks/payment-settled', (req, res) => { - const { transaction, network, payer, amount, success } = req.body; - - if (success) { - // Verify transaction on-chain (trustless) - const verified = await verifyTransactionOnChain(transaction, network); - - if (verified) { - // Fulfill user's order - fulfillOrder(payer, amount); - } - } - - res.status(200).send('OK'); -}); -``` - -**Best practice**: Always verify webhook data by querying the blockchain directly. Don't trust the webhook alone—use it as a notification, then verify on-chain. - -### Independent Monitoring - -Merchants can also monitor the blockchain directly without relying on facilitators: - -```javascript -import { ethers } from 'ethers'; - -// Monitor for Transfer events to your address -const provider = new ethers.JsonRpcProvider('https://api.avax-test.network/ext/bc/C/rpc'); -const usdcContract = new ethers.Contract(usdcAddress, usdcAbi, provider); - -// Listen for incoming payments -usdcContract.on('Transfer', (from, to, value, event) => { - if (to.toLowerCase() === myAddress.toLowerCase()) { - console.log(`Received ${value} USDC from ${from}`); - console.log(`Transaction: ${event.transactionHash}`); - - // Fulfill payment - fulfillPayment(event.transactionHash); - } -}); -``` - -This provides **complete independence** from facilitators for settlement verification. - -## Amount Verification - -Always verify that the payment amount meets your requirements: - -```javascript -function validatePaymentAmount(authorization, maxAmountRequired) { - const authorizedAmount = BigInt(authorization.value); - const requiredAmount = BigInt(maxAmountRequired); - - if (authorizedAmount < requiredAmount) { - throw new Error( - `Insufficient payment: required ${requiredAmount}, got ${authorizedAmount}` - ); - } - - return true; -} -``` - -**Important**: Amounts are in token base units (see [Amount Specification](./02-http-headers#amount-specification) for details). - -Accept payments equal to or greater than `maxAmountRequired` to allow for user generosity (tips). - -## Network Verification - -Verify that the payment is on the expected blockchain network: - -```javascript -function validateNetwork(payload, expectedNetwork) { - if (payload.network !== expectedNetwork) { - throw new Error( - `Wrong network: expected ${expectedNetwork}, got ${payload.network}` - ); - } - - // Also verify the chainId matches the network - const expectedChainId = getChainId(expectedNetwork); - // Signature domain includes chainId, so this is validated in signature verification -} -``` - -This prevents: -- Payments on testnets being accepted as mainnet payments -- Cross-chain replay attacks -- Merchant configuration errors - -## Recipient Address Verification - -Verify that payments are sent to the correct recipient address: - -```javascript -function validateRecipient(authorization, expectedPayTo) { - if (authorization.to.toLowerCase() !== expectedPayTo.toLowerCase()) { - throw new Error( - `Wrong recipient: expected ${expectedPayTo}, got ${authorization.to}` - ); - } -} -``` - -This is especially important when: -- Supporting multiple merchants on one facilitator -- Using different addresses for different services -- Accepting payments to multiple wallets - -## Token Contract Verification - -Verify that the payment uses the expected token (asset): - -```javascript -function validateAsset(paymentRequest, expectedAsset) { - if (paymentRequest.asset.toLowerCase() !== expectedAsset.toLowerCase()) { - throw new Error( - `Wrong token: expected ${expectedAsset}, got ${paymentRequest.asset}` - ); - } -} -``` - -**Why this matters**: Attackers could try to pay with worthless tokens that share similar addresses. Always validate the exact contract address. - -**Example USDC addresses**: -- Avalanche C-Chain: `0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E` -- Avalanche Fuji: `0x5425890298aed601595a70AB815c96711a31Bc65` -- Base Sepolia: `0x036CbD53842c5426634e7929541eC2318f3dCF7e` - -## Rate Limiting and Abuse Prevention - -Implement rate limiting to prevent abuse: - -```javascript -// Simple rate limiting by address -const paymentsByAddress = new Map(); - -function checkRateLimit(from, maxPerHour = 10) { - const now = Date.now(); - const oneHour = 60 * 60 * 1000; - - if (!paymentsByAddress.has(from)) { - paymentsByAddress.set(from, []); - } - - const payments = paymentsByAddress.get(from); - - // Remove old payments outside the window - const recentPayments = payments.filter(time => now - time < oneHour); - - if (recentPayments.length >= maxPerHour) { - throw new Error(`Rate limit exceeded: max ${maxPerHour} payments per hour`); - } - - recentPayments.push(now); - paymentsByAddress.set(from, recentPayments); -} -``` - -This prevents: -- Spam attacks on your API -- Nonce exhaustion attacks -- Resource abuse - -## Summary - -x402 security relies on multiple defense layers: - -1. **Nonce-based replay prevention**: Each authorization is single-use -2. **Time-bounded authorizations**: Payments expire after a set time window -3. **EIP-712 signatures**: Cryptographic proof of user authorization -4. **On-chain validation**: USDC contract verifies all constraints -5. **Transaction hash tracking**: Merchants prevent duplicate fulfillment -6. **Amount, network, and asset verification**: Validate all payment parameters -7. **Settlement monitoring**: Real-time blockchain monitoring for finality - -These mechanisms provide trustless, cryptographically secure payments without requiring users to trust facilitators or merchants. The blockchain enforces all security rules. - -## Additional Resources - -- [EIP-712: Typed Structured Data Signing](https://eips.ethereum.org/EIPS/eip-712) -- [EIP-3009: Transfer With Authorization](https://eips.ethereum.org/EIPS/eip-3009) -- [x402 Whitepaper - Security Model](https://www.x402.org/x402-whitepaper.pdf) -- [PayAI Security Best Practices](https://docs.payai.network/security) diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/07-security-considerations.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/07-security-considerations.mdx new file mode 100644 index 00000000000..d40e6b78e7a --- /dev/null +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/07-security-considerations.mdx @@ -0,0 +1,171 @@ +--- +title: Security Considerations +description: Understanding replay attack prevention, time-bounded authorizations, and settlement monitoring in x402. +updated: 2025-11-03 +authors: [Federico Nardelli] +icon: Shield +--- + +## Overview + +The x402 protocol implements multiple layers of security to protect against common attack vectors while maintaining a seamless user experience. These security measures are built on battle-tested Ethereum standards (EIP-712, EIP-3009) and blockchain cryptography. + +## Replay Attack Prevention + +Replay attacks occur when an attacker intercepts a valid payment authorization and attempts to reuse it multiple times. x402 prevents this through three complementary mechanisms: + +### 1. Nonce-Based Protection + +Each payment authorization includes a unique random nonce (32-byte hex string): + +```javascript +const nonce = ethers.hexlify(ethers.randomBytes(32)); +// Example: 0x3456789012345678901234567890123456789012345678901234567890123456 +``` + +The USDC contract (following EIP-3009) tracks which nonces have been used on-chain. When a `transferWithAuthorization` is executed: + +1. The contract checks if the nonce has been used before +2. If the nonce is new, the transfer proceeds and the nonce is marked as used +3. If the nonce was already used, the transaction reverts with an error + +**This makes each authorization single-use**. Even if an attacker intercepts the authorization, they cannot reuse it because the nonce is already consumed on-chain. + +### 2. Time-Bounded Authorizations + +Every authorization includes `validAfter` and `validBefore` timestamps (Unix time in seconds): + +```json +{ + "validAfter": "1740672089", // January 7, 2025, 10:00:00 AM UTC + "validBefore": "1740672389" // January 7, 2025, 10:05:00 AM UTC (5 minutes later) +} +``` + +The USDC contract enforces these timing constraints: +- If current time < `validAfter`: Transaction reverts (not yet valid) +- If current time ≥ `validBefore`: Transaction reverts (expired) +- Only between these times: Transaction can execute + +**Best practices**: +- Set short validity windows (5-10 minutes) for most payments +- For delayed/scheduled payments, set appropriate `validAfter` +- Never set `validBefore` too far in the future (increases replay risk if nonce tracking fails) + +### 3. Transaction Hash Uniqueness + +Each blockchain transaction has a unique hash. Merchants should track received transaction hashes to ensure they don't fulfill the same payment twice. Even though blockchain nonces prevent double-spending, tracking fulfilled payments prevents edge cases like duplicate facilitator notifications or network issues causing duplicate webhook deliveries. + +## Signature Validation + +All payment authorizations use EIP-712 typed structured data signatures, providing cryptographic proof that the user authorized the payment. + +### Server-Side Signature Verification + +Facilitators must validate signatures before submitting transactions: + +```javascript +import { verifyTypedData } from 'ethers'; + +function validatePaymentSignature(payload) { + const { signature, authorization } = payload.payload; + const { network } = payload; + + // EIP-712 domain for USDC on Avalanche Fuji + const domain = { + name: "USD Coin", + version: "2", + chainId: 43113, // Avalanche Fuji + verifyingContract: "0x5425890298aed601595a70AB815c96711a31Bc65" + }; + + // EIP-712 type definition + const types = { + TransferWithAuthorization: [ + { name: "from", type: "address" }, + { name: "to", type: "address" }, + { name: "value", type: "uint256" }, + { name: "validAfter", type: "uint256" }, + { name: "validBefore", type: "uint256" }, + { name: "nonce", type: "bytes32" } + ] + }; + + // Recover signer address from signature + const recovered = verifyTypedData( + domain, + types, + authorization, + signature + ); + + // Verify the signer matches the 'from' address + if (recovered.toLowerCase() !== authorization.from.toLowerCase()) { + throw new Error("Invalid signature: signer does not match 'from' address"); + } + + return true; +} +``` + +**Key validation steps**: +1. Recover the signer address from the signature +2. Verify it matches the `from` field in the authorization +3. Check all other fields (amount, recipient, timing) +4. Only submit to blockchain if everything validates + +The USDC contract also validates signatures on-chain, providing trustless verification even if the facilitator is malicious. + +## Authorization Timing Validation + +Facilitators validate timing constraints before submitting transactions to avoid wasting gas on expired authorizations. This prevents submitting transactions that will revert, wasting gas fees, or creating poor user experience from delayed settlements. + +## Settlement Monitoring + +Facilitators monitor the blockchain in real-time to detect when payments are settled and verify transaction success. Most facilitators provide webhook notifications when settlements complete. + +**Best practice**: Always verify webhook data by querying the blockchain directly. Don't trust the webhook alone—use it as a notification, then verify on-chain. Merchants can also monitor blockchain events independently without relying on facilitator notifications. + +## Amount Verification + +Verify that the payment amount meets your requirements. Amounts are in token base units (see [Amount Specification](./02-http-payment-required#amount-specification) for details). Accept payments equal to or greater than `maxAmountRequired`. + +## Network Verification + +Verify that the payment is on the expected blockchain network. This prevents: +- Payments on testnets being accepted as mainnet payments +- Cross-chain replay attacks +- Merchant configuration errors + +## Recipient Address Verification + +Verify that payments are sent to the correct recipient address. This is especially important when supporting multiple merchants, using different addresses for different services, or accepting payments to multiple wallets. + +## Token Contract Verification + +Verify that the payment uses the expected token (asset) by validating the exact contract address. Attackers could try to pay with worthless tokens that share similar addresses. + +## Rate Limiting and Abuse Prevention + +Implement rate limiting to prevent spam attacks, nonce exhaustion, and resource abuse. Track payment frequency by address and enforce reasonable limits per time window. + +## Summary + +x402 security relies on multiple defense layers: + +1. **Nonce-based replay prevention**: Each authorization is single-use +2. **Time-bounded authorizations**: Payments expire after a set time window +3. **EIP-712 signatures**: Cryptographic proof of user authorization +4. **On-chain validation**: USDC contract verifies all constraints +5. **Transaction hash tracking**: Merchants prevent duplicate fulfillment +6. **Amount, network, and asset verification**: Validate all payment parameters +7. **Settlement monitoring**: Real-time blockchain monitoring for finality + +These mechanisms provide trustless, cryptographically secure payments without requiring users to trust facilitators or merchants. The blockchain enforces all security rules. + +## Additional Resources + +- [EIP-712: Typed Structured Data Signing](https://eips.ethereum.org/EIPS/eip-712) +- [EIP-3009: Transfer With Authorization](https://eips.ethereum.org/EIPS/eip-3009) +- [x402 Whitepaper - Security Model](https://www.x402.org/x402-whitepaper.pdf) +- [PayAI Security Best Practices](https://docs.payai.network/security) From d76db808c65c33edac0559ef159b0dd7e4a87dda Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Fri, 14 Nov 2025 19:19:49 +0100 Subject: [PATCH 25/30] make the blockchain settlement chapter more readable --- ...ement.mdx => 06-blockchain-settlement.mdx} | 24 +------------------ 1 file changed, 1 insertion(+), 23 deletions(-) rename content/academy/x402-payment-infrastructure/03-technical-architecture/{04-blockchain-settlement.mdx => 06-blockchain-settlement.mdx} (88%) diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/04-blockchain-settlement.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/06-blockchain-settlement.mdx similarity index 88% rename from content/academy/x402-payment-infrastructure/03-technical-architecture/04-blockchain-settlement.mdx rename to content/academy/x402-payment-infrastructure/03-technical-architecture/06-blockchain-settlement.mdx index bd1ff55f2c2..eb13314dcc6 100644 --- a/content/academy/x402-payment-infrastructure/03-technical-architecture/04-blockchain-settlement.mdx +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/06-blockchain-settlement.mdx @@ -92,17 +92,6 @@ The facilitator receives the transaction hash from the blockchain and returns it Facilitators verify payments by querying the blockchain to ensure the transaction matches the expected payment details. This verification is trustless—anyone can independently confirm the payment by checking the blockchain. -### What Facilitators Verify - -When a transaction is submitted, facilitators check: - -1. **Transaction Existence**: The transaction hash exists on the blockchain -2. **Transaction Success**: The transaction executed without errors -3. **Correct Recipient**: Funds were sent to the expected `payTo` address -4. **Correct Amount**: The transfer amount matches or exceeds `maxAmountRequired` -5. **Recent Timestamp**: The transaction was created recently (prevents replay of old transactions) -6. **Confirmation Status**: The transaction has reached finality - ### USDC Transfer Events USDC transfers emit `Transfer` events on-chain that provide cryptographic proof of payment: @@ -174,17 +163,6 @@ Different blockchains have different finality characteristics, which affects the **Important**: Chains not listed here may not have official x402 support yet. Always verify with your facilitator which networks they support. Check [PayAI documentation](https://docs.payai.network) for their current network list. -### Choosing a Blockchain - -When selecting a blockchain for x402 payments, consider: - -1. **Settlement Speed**: How fast do you need payment confirmation? -2. **Transaction Costs**: What are the gas fees on this chain? -3. **Facilitator Support**: Does your chosen facilitator support this chain? -4. **User Base**: Which chains do your users already have wallets and tokens on? - -For most micropayment use cases, **Avalanche** and **Base** offer the best combination of speed (\~2 seconds) and cost (~\$0.001 gas). - ## Summary Blockchain settlement in x402 provides transparent, immutable, and instant payment finality through EIP-3009's gasless payment standard. The complete x402 process takes approximately **2-2.3 seconds** on Avalanche, with blockchain finality achieved in **1-2 seconds**. @@ -197,7 +175,7 @@ Key advantages: Facilitators abstract away the complexity of blockchain interactions, making x402 settlement as simple as traditional payment APIs while delivering superior speed, lower costs, and trustless verification. -**Next**: Learn about [Security Considerations](./05-security-considerations) including replay attack prevention, signature validation, and settlement monitoring. +**Next**: Learn about [Security Considerations](./07-security-considerations) including replay attack prevention, signature validation, and settlement monitoring. ## Additional Resources From 1942ad5e14f0867a4ac20068b00e4dc7cd862892 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Fri, 14 Nov 2025 19:21:36 +0100 Subject: [PATCH 26/30] made the difference with/without facilitator more viewable with a table --- ...tator-role.mdx => 05-facilitator-role.mdx} | 49 +++++++------------ 1 file changed, 19 insertions(+), 30 deletions(-) rename content/academy/x402-payment-infrastructure/03-technical-architecture/{03-facilitator-role.mdx => 05-facilitator-role.mdx} (86%) diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/03-facilitator-role.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/05-facilitator-role.mdx similarity index 86% rename from content/academy/x402-payment-infrastructure/03-technical-architecture/03-facilitator-role.mdx rename to content/academy/x402-payment-infrastructure/03-technical-architecture/05-facilitator-role.mdx index 0c10621130d..23f07b12bbf 100644 --- a/content/academy/x402-payment-infrastructure/03-technical-architecture/03-facilitator-role.mdx +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/05-facilitator-role.mdx @@ -20,28 +20,17 @@ Think of facilitators as the "payment processors" of the x402 ecosystem—but un ## Why Facilitators Are Necessary -While blockchain payments are permissionless, integrating them directly creates challenges: - -### Without Facilitators - -Merchants would need to: -- ❌ Run blockchain nodes -- ❌ Monitor transactions in real-time -- ❌ Handle gas price optimization -- ❌ Manage wallet infrastructure -- ❌ Implement replay attack prevention -- ❌ Build payment verification logic -- ❌ Handle multi-chain complexity - -### With Facilitators - -Merchants simply: -- ✅ Add one line of middleware code -- ✅ Configure payment amounts -- ✅ Receive instant verification -- ✅ Get automatic settlement -- ✅ Access multi-chain support -- ✅ Use simple REST APIs +While blockchain payments are permissionless, integrating them directly into applications requires handling significant infrastructure complexity. + +| Without Facilitators | With Facilitators | +|----------------------|-------------------| +| Run blockchain nodes (maintain infrastructure, handle failures, sync state) | Add middleware to your application | +| Monitor transactions in real-time (query blocks, parse logs, handle reorgs) | Receive instant verification responses | +| Optimize gas prices and manage transaction confirmation | Automatic settlement handling | +| Secure wallet infrastructure (key storage, signing operations) | Use simple REST APIs | +| Implement replay attack prevention (nonce tracking, databases) | Built-in security features | +| Build payment verification (parse EIP-3009 signatures, validate parameters) | Payment validation handled automatically | +| Deploy infrastructure for each blockchain separately | Multi-chain support included | Facilitators abstract away blockchain complexity while maintaining the benefits of permissionless payments. @@ -131,13 +120,13 @@ POST /facilitator/verify-payment const tx = await avalancheClient.getTransaction("0x8f3d..."); // Verification checks -✓ Transaction exists on chain -✓ Transaction is confirmed -✓ Amount matches expected -✓ Recipient matches expected -✓ Currency is correct -✓ Transaction not previously used -✓ Block timestamp is recent +- Transaction exists on chain +- Transaction is confirmed +- Amount matches expected +- Recipient matches expected +- Currency is correct +- Transaction not previously used +- Block timestamp is recent // Response { @@ -310,4 +299,4 @@ Facilitators are essential infrastructure in the x402 ecosystem, handling paymen Facilitators charge minimal fees (~0.1-0.5% + gas) compared to traditional payment processors (2.9% + $0.30), making micropayments economically viable for the first time. -**Next**: Learn about [Blockchain Settlement](./04-blockchain-settlement) to understand how payments are finalized on-chain, or explore [available facilitators on Avalanche](/academy/x402-payment-infrastructure/04-x402-on-avalanche/03-facilitators) for implementation options. +**Next**: Learn about [Blockchain Settlement](./06-blockchain-settlement) to understand how payments are finalized on-chain, or explore [available facilitators on Avalanche](/academy/x402-payment-infrastructure/04-x402-on-avalanche/03-facilitators) for implementation options. From 08e285733825e1dba60d671369e5239eb52f4b23 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Fri, 14 Nov 2025 21:02:03 +0100 Subject: [PATCH 27/30] divided the http header section into 3 steps. payment requiered, x-payment, x-payment-response. Improve readability in general --- .../02-http-headers.mdx | 415 ------------------ .../02-http-payment-required.mdx | 156 +++++++ .../03-x-payment-header.mdx | 164 +++++++ .../04-x-payment-response-header.mdx | 128 ++++++ 4 files changed, 448 insertions(+), 415 deletions(-) delete mode 100644 content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-headers.mdx create mode 100644 content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-payment-required.mdx create mode 100644 content/academy/x402-payment-infrastructure/03-technical-architecture/03-x-payment-header.mdx create mode 100644 content/academy/x402-payment-infrastructure/03-technical-architecture/04-x-payment-response-header.mdx diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-headers.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-headers.mdx deleted file mode 100644 index d99ad938019..00000000000 --- a/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-headers.mdx +++ /dev/null @@ -1,415 +0,0 @@ ---- -title: HTTP Headers in x402 -description: Understanding X-PAYMENT and X-PAYMENT-RESPONSE headers for payment communication. -updated: 2025-11-03 -authors: [Federico Nardelli] -icon: Code ---- - -## Overview - -The x402 protocol uses custom HTTP headers to communicate payment requirements and verification between clients and servers. These headers make payments a native part of HTTP communication. - -## HTTP 402 Payment Required Response - -When a server requires payment for a resource, it responds with **HTTP 402 Payment Required** and includes payment details in the **response body** as JSON (not in a custom header). - -### Response Structure - -```http -HTTP/1.1 402 Payment Required -Content-Type: application/json - -{ - "x402Version": 1, - "accepts": [ - { - "scheme": "exact", - "network": "avalanche-fuji", - "maxAmountRequired": "10000", - "resource": "/api/premium-data", - "description": "Real-time market analysis", - "payTo": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", - "asset": "0x5425890298aed601595a70AB815c96711a31Bc65", - "maxTimeoutSeconds": 60 - } - ], - "error": "X-PAYMENT header is required" -} -``` - -### Field Definitions - -| Field | Type | Required | Description | -|-------|------|----------|-------------| -| `x402Version` | number | Yes | Protocol version (currently 1) | -| `accepts` | array | Yes | Array of accepted payment options | -| `error` | string | No | Error message explaining why payment is required | - -### Payment Requirements Object (`accepts` array) - -Each payment option in the `accepts` array contains: - -| Field | Type | Required | Description | -|-------|------|----------|-------------| -| `scheme` | string | Yes | Payment scheme | -| `network` | string | Yes | Blockchain network identifier | -| `maxAmountRequired` | string | Yes | Maximum payment amount required (in token base units) | -| `resource` | string | Yes | Resource path being requested | -| `payTo` | string | Yes | Recipient blockchain address | -| `asset` | string | Yes | Token contract address | -| `maxTimeoutSeconds` | number | No | Maximum time to complete payment | -| `description` | string | No | Human-readable description | - -### Amount Specification - -Amounts are always strings representing **base units** (smallest denomination): - -```javascript -// For USDC (6 decimals): 10000 = 0.01 USDC -"maxAmountRequired": "10000" - -// For USDC (6 decimals): 1000000 = 1.0 USDC -"maxAmountRequired": "1000000" -``` - -**Important**: USDC has 6 decimals, so: -- 1 USDC = 1,000,000 base units -- 0.01 USDC = 10,000 base units -- 0.0001 USDC = 100 base units - -### Asset (Token Contract Address) - -The `asset` field contains the smart contract address of the payment token: - -```javascript -// USDC on Avalanche Fuji testnet -"asset": "0x5425890298aed601595a70AB815c96711a31Bc65" - -// USDC on Avalanche C-Chain mainnet -"asset": "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E" - -// USDC on Base Sepolia testnet -"asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e" -``` - -**Note**: The asset is identified by contract address, not by symbol like "USDC". - -### Network Identifiers - -Standard network identifiers for Avalanche and other chains: - -```javascript -"network": "avalanche-c-chain" // Avalanche C-Chain Mainnet -"network": "avalanche-fuji" // Avalanche Fuji Testnet -"network": "base-sepolia" // Base Sepolia Testnet -``` - -### Payment Schemes - -The `scheme` field specifies how payments are settled. x402 supports multiple schemes to handle different payment models: - -**`exact` Scheme (Implemented)**: -- Fixed payment amount known upfront -- Use cases: Pay $0.10 to read an article, fixed-price API calls -- Implementations: EVM (EIP-3009), Solana, Sui -- Example: `"scheme": "exact", "maxAmountRequired": "100000"` - -**`up-to` Scheme (Proposed)**: -- Variable payment based on resource consumption -- Use cases: LLM token-based pricing, pay-per-token generation, usage-metered services -- Status: Not yet implemented - under development -- Example use: Pay up to $1.00, actual charge depends on tokens consumed - -The protocol is designed to be extensible, allowing new schemes to be added as payment models evolve. Current implementations focus on the `exact` scheme across multiple blockchains. - -**Reference**: See [x402 Schemes Specification](https://github.com/coinbase/x402/tree/main/specs/schemes) for technical details. - -### Multiple Payment Options - -Servers can offer multiple payment options (different networks or tokens): - -```json -{ - "x402Version": 1, - "accepts": [ - { - "scheme": "exact", - "network": "avalanche-fuji", - "maxAmountRequired": "10000", - "payTo": "0x742d35...", - "asset": "0x5425890...", - "resource": "/api/data" - }, - { - "scheme": "exact", - "network": "base-sepolia", - "maxAmountRequired": "10000", - "payTo": "0x742d35...", - "asset": "0x036CbD...", - "resource": "/api/data" - } - ] -} -``` - -## X-PAYMENT Header - -When making a payment, the client includes the `X-PAYMENT` header with the request. This header contains a **base64-encoded JSON payload** with the payment authorization. - -### Header Structure - -```http -GET /api/premium-data HTTP/1.1 -Host: example.com -X-PAYMENT: -``` - -### Payment Payload Structure (before base64 encoding) - -```json -{ - "x402Version": 1, - "scheme": "exact", - "network": "avalanche-fuji", - "payload": { - "signature": "0x1234567890abcdef...", - "authorization": { - "from": "0x1234567890abcdef1234567890abcdef12345678", - "to": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", - "value": "10000", - "validAfter": "1740672089", - "validBefore": "1740672154", - "nonce": "0x3456789012345678901234567890123456789012345678901234567890123456" - } - } -} -``` - -### Field Definitions - -| Field | Type | Required | Description | -|-------|------|----------|-------------| -| `x402Version` | number | Yes | Protocol version (currently 1) | -| `scheme` | string | Yes | Payment scheme ("exact" for EVM) | -| `network` | string | Yes | Blockchain network used | -| `payload` | object | Yes | Scheme-specific payment data | - -### Payload for "exact" Scheme (EVM Chains) - -The payload for EVM chains using the "exact" scheme contains: - -| Field | Type | Required | Description | -|-------|------|----------|-------------| -| `signature` | string | Yes | EIP-712 signature of the authorization | -| `authorization` | object | Yes | Payment authorization details | - -### Authorization Object - -The authorization object follows EIP-3009 TransferWithAuthorization: - -| Field | Type | Required | Description | -|-------|------|----------|-------------| -| `from` | string | Yes | Payer's wallet address | -| `to` | string | Yes | Recipient's wallet address | -| `value` | string | Yes | Amount in token base units | -| `validAfter` | string | Yes | Unix timestamp (seconds) - payment valid after this time | -| `validBefore` | string | Yes | Unix timestamp (seconds) - payment expires after this time | -| `nonce` | string | Yes | Unique 32-byte hex string for replay protection | - -### EIP-712 Signature - -The signature field contains an EIP-712 signature of the authorization object: - -```javascript -// The user's wallet signs the authorization using EIP-712 -const signature = await wallet.signTypedData({ - domain: { - name: "USD Coin", - version: "2", - chainId: 43113, // Avalanche Fuji - verifyingContract: "0x5425890298aed601595a70AB815c96711a31Bc65" - }, - types: { - TransferWithAuthorization: [ - { name: "from", type: "address" }, - { name: "to", type: "address" }, - { name: "value", type: "uint256" }, - { name: "validAfter", type: "uint256" }, - { name: "validBefore", type: "uint256" }, - { name: "nonce", type: "bytes32" } - ] - }, - primaryType: "TransferWithAuthorization", - message: authorization -}); -``` - -This signature: -- ✓ Proves user consent without requiring a transaction -- ✓ Cannot be forged (cryptographically secure) -- ✓ Includes all payment details in the signature -- ✓ Enables gasless payments (server submits the transaction) - -### Complete Example - -```javascript -// 1. Client receives 402 response with payment requirements -const paymentReq = response.data.accepts[0]; - -// 2. Client creates authorization object -const authorization = { - from: userAddress, - to: paymentReq.payTo, - value: paymentReq.maxAmountRequired, - validAfter: Math.floor(Date.now() / 1000).toString(), - validBefore: (Math.floor(Date.now() / 1000) + 300).toString(), // 5 minutes - nonce: ethers.randomBytes(32) -}; - -// 3. User signs authorization -const signature = await wallet.signTypedData(...); - -// 4. Client creates payment payload -const paymentPayload = { - x402Version: 1, - scheme: paymentReq.scheme, - network: paymentReq.network, - payload: { - signature: signature, - authorization: authorization - } -}; - -// 5. Base64 encode and send -const encoded = btoa(JSON.stringify(paymentPayload)); -await fetch('/api/premium-data', { - headers: { - 'X-PAYMENT': encoded - } -}); -``` - -## X-PAYMENT-RESPONSE Header - -After verifying and settling payment, the server includes the `X-PAYMENT-RESPONSE` header in its response. This header is also **base64-encoded JSON**. - -### Header Structure - -```http -HTTP/1.1 200 OK -Content-Type: application/json -X-PAYMENT-RESPONSE: -``` - -### Settlement Response Structure (before base64 encoding) - -```json -{ - "success": true, - "transaction": "0x8f3d1a2b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a", - "network": "avalanche-fuji", - "payer": "0x1234567890abcdef1234567890abcdef12345678", - "errorReason": null -} -``` - -### Field Definitions - -| Field | Type | Required | Description | -|-------|------|----------|-------------| -| `success` | boolean | Yes | Whether settlement was successful | -| `transaction` | string | Yes (if success) | Transaction hash on blockchain | -| `network` | string | Yes | Network where transaction was settled | -| `payer` | string | Yes | Address of the payer | -| `errorReason` | string | Yes (if failed) | Error message if settlement failed | - -### Success Response - -When payment is successfully verified and settled: - -```json -{ - "success": true, - "transaction": "0x8f3d1a2b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a", - "network": "avalanche-fuji", - "payer": "0x1234567890abcdef1234567890abcdef12345678", - "errorReason": null -} -``` - -The transaction hash can be used to: -- ✓ Verify the transaction on a block explorer -- ✓ Check transaction details (amount, timestamp, block number) -- ✓ Provide proof of payment to users -- ✓ Audit payment history - -### Payment Failure Response - -When payment verification or settlement fails, the server returns **HTTP 402 Payment Required** with both a JSON body containing payment requirements and an `X-PAYMENT-RESPONSE` header with failure details: - -```http -HTTP/1.1 402 Payment Required -Content-Type: application/json -X-PAYMENT-RESPONSE: eyJzdWNjZXNzIjpmYWxzZSwidHJhbnNhY3Rpb24iOm51bGwsIm5ldHdvcmsiOiJhdmFsYW5jaGUtZnVqaSIsInBheWVyIjoiMHgxMjM0NTY3ODkwYWJjZGVmMTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4IiwiZXJyb3JSZWFzb24iOiJJbnN1ZmZpY2llbnQgYXV0aG9yaXphdGlvbiBhbW91bnQifQ== - -{ - "x402Version": 1, - "accepts": [{ - "scheme": "exact", - "network": "avalanche-fuji", - "maxAmountRequired": "10000", - "payTo": "0x742d35...", - "asset": "0x5425890...", - "resource": "/api/data" - }], - "error": "Insufficient payment: required 10000, received 5000" -} -``` - -The `X-PAYMENT-RESPONSE` header (when decoded) contains: - -```json -{ - "success": false, - "transaction": null, - "network": "avalanche-fuji", - "payer": "0x1234567890abcdef1234567890abcdef12345678", - "errorReason": "Insufficient authorization amount" -} -``` - -**Common error reasons**: -- `"Insufficient authorization amount"` - Payment amount too low -- `"Authorization expired"` - validBefore timestamp passed -- `"Invalid signature"` - Signature verification failed -- `"Nonce already used"` - Replay attack detected -- `"Insufficient balance"` - Payer doesn't have enough tokens - -**Why both body and header?** -- **JSON body**: Provides new payment requirements so the client can retry -- **X-PAYMENT-RESPONSE header**: Communicates what went wrong with the settlement attempt - -## Header Best Practices - -### For Servers - -1. **Support multiple networks**: Include options for different blockchains in `accepts` array -2. **Set reasonable timeouts**: Use `maxTimeoutSeconds` to prevent stale payments -3. **Use base units consistently**: Always specify amounts in smallest token denomination -4. **Validate signatures carefully**: Use EIP-712 verification libraries -5. **Implement replay protection**: Track used nonces to prevent double-spending - -### For Clients - -1. **Decode and parse carefully**: Base64 decode and JSON parse all headers -2. **Check authorization expiry**: Don't sign authorizations with past `validBefore` timestamps -3. **Generate unique nonces**: Use cryptographically secure random 32-byte values -4. **Store transaction receipts**: Keep `X-PAYMENT-RESPONSE` data for proof of payment -5. **Handle errors gracefully**: Implement retry logic with exponential backoff - -For detailed security considerations including signature validation, nonce-based replay prevention, and authorization timing validation, see [Security Considerations](./05-security-considerations) - -## Summary - -The x402 protocol uses HTTP 402 responses with JSON bodies and two custom HTTP headers (`X-PAYMENT` and `X-PAYMENT-RESPONSE`) to enable payment communication. When a payment is required, the server responds with HTTP 402 and a JSON body containing payment requirements. The client submits a signed authorization in the base64-encoded `X-PAYMENT` header. After settlement, the server returns the resource with an `X-PAYMENT-RESPONSE` header containing the transaction hash. All payloads are base64-encoded JSON structures following the EIP-3009 TransferWithAuthorization standard for secure, verifiable blockchain payments. diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-payment-required.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-payment-required.mdx new file mode 100644 index 00000000000..30811dd78c2 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-payment-required.mdx @@ -0,0 +1,156 @@ +--- +title: HTTP 402 Payment Required +description: How servers request payment using HTTP 402 status code and structured payment requirements. +updated: 2025-11-14 +authors: [Federico Nardelli] +icon: Code +--- + +## HTTP 402 Payment Required Response + +When a server requires payment for a resource, it responds with the HTTP 402 Payment Required status code. This standard HTTP response includes a JSON body containing structured payment requirements that specify exactly what payment is needed, where it should go, and how it should be made. + +### Response Structure + +```http +HTTP/1.1 402 Payment Required +Content-Type: application/json + +{ + "x402Version": 1, + "accepts": [ + { + "scheme": "exact", + "network": "avalanche-fuji", + "maxAmountRequired": "10000", + "resource": "/api/premium-data", + "description": "Real-time market analysis", + "payTo": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", + "asset": "0x5425890298aed601595a70AB815c96711a31Bc65", + "maxTimeoutSeconds": 60 + } + ], + "error": "X-PAYMENT header is required" +} +``` + +### Field Definitions + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `x402Version` | number | Yes | Protocol version (currently 1) | +| `accepts` | array | Yes | Array of accepted payment options | +| `error` | string | No | Error message explaining why payment is required | + +### Payment Requirements Object (`accepts` array) + +Each payment option in the `accepts` array contains: + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `scheme` | string | Yes | Payment scheme | +| `network` | string | Yes | Blockchain network identifier | +| `maxAmountRequired` | string | Yes | Maximum payment amount required (in token base units) | +| `resource` | string | Yes | Resource path being requested | +| `payTo` | string | Yes | Recipient blockchain address | +| `asset` | string | Yes | Token contract address | +| `maxTimeoutSeconds` | number | No | Maximum time to complete payment | +| `description` | string | No | Human-readable description | + +### Amount Specification + +Amounts are always strings representing **base units** (smallest denomination): + +```javascript +// For USDC (6 decimals): 10000 = 0.01 USDC +"maxAmountRequired": "10000" + +// For USDC (6 decimals): 1000000 = 1.0 USDC +"maxAmountRequired": "1000000" +``` + +**Important**: USDC has 6 decimals, so: +- 1 USDC = 1,000,000 base units +- 0.01 USDC = 10,000 base units +- 0.0001 USDC = 100 base units + +### Asset (Token Contract Address) + +The `asset` field contains the smart contract address of the payment token: + +```javascript +// USDC on Avalanche Fuji testnet +"asset": "0x5425890298aed601595a70AB815c96711a31Bc65" + +// USDC on Avalanche C-Chain mainnet +"asset": "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E" + +// USDC on Base Sepolia testnet +"asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e" +``` + +**Note**: The asset is identified by contract address, not by symbol like "USDC". + +### Network Identifiers + +Standard network identifiers for Avalanche and other chains: + +```javascript +"network": "avalanche-c-chain" // Avalanche C-Chain Mainnet +"network": "avalanche-fuji" // Avalanche Fuji Testnet +"network": "base-sepolia" // Base Sepolia Testnet +``` + +### Payment Schemes + +The `scheme` field specifies how payments are settled. x402 supports multiple schemes to handle different payment models: + +**`exact` Scheme (Implemented)**: +- Fixed payment amount known upfront +- Use cases: Pay $0.10 to read an article, fixed-price API calls +- Implementations: EVM (EIP-3009), Solana, Sui +- Example: `"scheme": "exact", "maxAmountRequired": "100000"` + +**`up-to` Scheme (Proposed)**: +- Variable payment based on resource consumption +- Use cases: LLM token-based pricing, pay-per-token generation, usage-metered services +- Status: Not yet implemented - under development +- Example use: Pay up to $1.00, actual charge depends on tokens consumed + +The protocol is designed to be extensible, allowing new schemes to be added as payment models evolve. Current implementations focus on the `exact` scheme across multiple blockchains. + +**Reference**: See [x402 Schemes Specification](https://github.com/coinbase/x402/tree/main/specs/schemes) for technical details. + +### Multiple Payment Options + +Servers can offer multiple payment options (different networks or tokens): + +```json +{ + "x402Version": 1, + "accepts": [ + { + "scheme": "exact", + "network": "avalanche-fuji", + "maxAmountRequired": "10000", + "payTo": "0x742d35...", + "asset": "0x5425890...", + "resource": "/api/data" + }, + { + "scheme": "exact", + "network": "base-sepolia", + "maxAmountRequired": "10000", + "payTo": "0x742d35...", + "asset": "0x036CbD...", + "resource": "/api/data" + } + ] +} +``` + +## Summary + +The HTTP 402 Payment Required response is the server's way of requesting payment from clients. It includes a JSON body with an `accepts` array that lists one or more payment options, each specifying the payment scheme, blockchain network, token contract address, maximum amount required, recipient address, and optional timeout. + +Servers can offer multiple payment options across different networks or with different tokens, giving clients flexibility in how they pay. Amounts are always specified in token base units (e.g., 10000 = 0.01 USDC with 6 decimals). diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/03-x-payment-header.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/03-x-payment-header.mdx new file mode 100644 index 00000000000..b450e44bb19 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/03-x-payment-header.mdx @@ -0,0 +1,164 @@ +--- +title: X-PAYMENT +description: How clients authorize payments using signed EIP-3009 authorizations in the X-PAYMENT header. +updated: 2025-11-14 +authors: [Federico Nardelli] +icon: Code +--- + +## X-PAYMENT Header + +After receiving an HTTP 402 response, clients authorize payment by including the `X-PAYMENT` header in their retry request. This header contains a **base64-encoded JSON** payload with a cryptographically signed payment authorization that proves user consent without requiring a blockchain transaction. + +The authorization follows the EIP-3009 TransferWithAuthorization standard, enabling gasless payments where the server or facilitator submits the transaction on behalf of the user. + +### Header Structure + +```http +GET /api/premium-data HTTP/1.1 +Host: example.com +X-PAYMENT: +``` + +### Payment Payload Structure (before base64 encoding) + +```json +{ + "x402Version": 1, + "scheme": "exact", + "network": "avalanche-fuji", + "payload": { + "signature": "0x1234567890abcdef...", + "authorization": { + "from": "0x1234567890abcdef1234567890abcdef12345678", + "to": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", + "value": "10000", + "validAfter": "1740672089", + "validBefore": "1740672154", + "nonce": "0x3456789012345678901234567890123456789012345678901234567890123456" + } + } +} +``` + +### Field Definitions + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `x402Version` | number | Yes | Protocol version (currently 1) | +| `scheme` | string | Yes | Payment scheme ("exact" for EVM) | +| `network` | string | Yes | Blockchain network used | +| `payload` | object | Yes | Scheme-specific payment data | + +### Payload for "exact" Scheme (EVM Chains) + +The payload for EVM chains using the "exact" scheme contains: + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `signature` | string | Yes | EIP-712 signature of the authorization | +| `authorization` | object | Yes | Payment authorization details | + +### Authorization Object + +The authorization object follows EIP-3009 TransferWithAuthorization: + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `from` | string | Yes | Payer's wallet address | +| `to` | string | Yes | Recipient's wallet address | +| `value` | string | Yes | Amount in token base units | +| `validAfter` | string | Yes | Unix timestamp (seconds) - payment valid after this time | +| `validBefore` | string | Yes | Unix timestamp (seconds) - payment expires after this time | +| `nonce` | string | Yes | Unique 32-byte hex string for replay protection (randomly generated, not the sequential wallet nonce) | + +### EIP-712 Signature + +The signature field contains an EIP-712 signature of the authorization object: + +```javascript +// The user's wallet signs the authorization using EIP-712 +const signature = await wallet.signTypedData({ + domain: { + name: "USD Coin", + version: "2", + chainId: 43113, // Avalanche Fuji + verifyingContract: "0x5425890298aed601595a70AB815c96711a31Bc65" + }, + types: { + TransferWithAuthorization: [ + { name: "from", type: "address" }, + { name: "to", type: "address" }, + { name: "value", type: "uint256" }, + { name: "validAfter", type: "uint256" }, + { name: "validBefore", type: "uint256" }, + { name: "nonce", type: "bytes32" } + ] + }, + primaryType: "TransferWithAuthorization", + message: authorization +}); +``` + +This signature: +- Proves user consent without requiring a transaction +- Cannot be forged (cryptographically secure) +- Includes all payment details in the signature +- Enables gasless payments (server submits the transaction) + +### Complete Example + +```javascript +// 1. Client receives 402 response with payment requirements +const paymentReq = response.data.accepts[0]; + +// 2. Client creates authorization object +const authorization = { + from: userAddress, + to: paymentReq.payTo, + value: paymentReq.maxAmountRequired, + validAfter: Math.floor(Date.now() / 1000).toString(), + validBefore: (Math.floor(Date.now() / 1000) + 300).toString(), // 5 minutes + nonce: ethers.hexlify(ethers.randomBytes(32)) +}; + +// 3. User signs authorization +const signature = await wallet.signTypedData(...); + +// 4. Client creates payment payload +const paymentPayload = { + x402Version: 1, + scheme: paymentReq.scheme, + network: paymentReq.network, + payload: { + signature: signature, + authorization: authorization + } +}; + +// 5. Base64 encode and send +const encoded = btoa(JSON.stringify(paymentPayload)); +await fetch('/api/premium-data', { + headers: { + 'X-PAYMENT': encoded + } +}); +``` + +## Client Best Practices + +When implementing X-PAYMENT headers, clients should follow these guidelines: + +1. **Decode and parse carefully**: Base64 decode and JSON parse all headers +2. **Check authorization expiry**: Don't sign authorizations with past `validBefore` timestamps +3. **Generate unique nonces**: Use cryptographically secure random 32-byte values +4. **Store transaction receipts**: Keep `X-PAYMENT-RESPONSE` data for proof of payment +5. **Handle errors gracefully**: Implement retry logic with exponential backoff + +For detailed security considerations including signature validation, nonce-based replay prevention, and authorization timing validation, see [Security Considerations](./07-security-considerations). + +## Summary + +The X-PAYMENT header enables clients to authorize payments through cryptographically signed EIP-3009 authorizations. Clients create an authorization object containing payment details (from, to, value, validity window, nonce), sign it using EIP-712, and encode the complete payload as base64 before including it in the X-PAYMENT header. + +This gasless payment model means users only sign an authorization—they don't submit blockchain transactions or pay gas fees. The server or facilitator handles transaction submission, making the payment experience seamless while maintaining cryptographic proof of user consent. \ No newline at end of file diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/04-x-payment-response-header.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/04-x-payment-response-header.mdx new file mode 100644 index 00000000000..a3176916546 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/04-x-payment-response-header.mdx @@ -0,0 +1,128 @@ +--- +title: X-PAYMENT-RESPONSE +description: How servers communicate payment settlement results with transaction hashes and error details. +updated: 2025-11-14 +authors: [Federico Nardelli] +icon: Code +--- + +## X-PAYMENT-RESPONSE Header + +After verifying and settling a payment from an X-PAYMENT header, the server communicates the settlement result back to the client through the `X-PAYMENT-RESPONSE` header. This header contains critical information about the blockchain transaction, including the transaction hash for on-chain verification. + +Like the `X-PAYMENT` header, the `X-PAYMENT-RESPONSE` is **base64-encoded JSON** that provides cryptographic proof of payment settlement. + +### Header Structure + +```http +HTTP/1.1 200 OK +Content-Type: application/json +X-PAYMENT-RESPONSE: +``` + +### Settlement Response Structure (before base64 encoding) + +```json +{ + "success": true, + "transaction": "0x8f3d1a2b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a", + "network": "avalanche-fuji", + "payer": "0x1234567890abcdef1234567890abcdef12345678", + "errorReason": null +} +``` + +### Field Definitions + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `success` | boolean | Yes | Whether settlement was successful | +| `transaction` | string | Yes (if success) | Transaction hash on blockchain | +| `network` | string | Yes | Network where transaction was settled | +| `payer` | string | Yes | Address of the payer | +| `errorReason` | string | Yes (if failed) | Error message if settlement failed | + +### Success Response + +When payment is successfully verified and settled: + +```json +{ + "success": true, + "transaction": "0x8f3d1a2b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a", + "network": "avalanche-fuji", + "payer": "0x1234567890abcdef1234567890abcdef12345678", + "errorReason": null +} +``` + +The transaction hash can be used to: +- Verify the transaction on a block explorer +- Check transaction details (amount, timestamp, block number) +- Provide proof of payment to users +- Audit payment history + +### Payment Failure Response + +When payment verification or settlement fails, the server returns **HTTP 402 Payment Required** with both a JSON body containing payment requirements and an `X-PAYMENT-RESPONSE` header with failure details: + +```http +HTTP/1.1 402 Payment Required +Content-Type: application/json +X-PAYMENT-RESPONSE: eyJzdWNjZXNzIjpmYWxzZSwidHJhbnNhY3Rpb24iOm51bGwsIm5ldHdvcmsiOiJhdmFsYW5jaGUtZnVqaSIsInBheWVyIjoiMHgxMjM0NTY3ODkwYWJjZGVmMTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4IiwiZXJyb3JSZWFzb24iOiJJbnN1ZmZpY2llbnQgYXV0aG9yaXphdGlvbiBhbW91bnQifQ== + +{ + "x402Version": 1, + "accepts": [{ + "scheme": "exact", + "network": "avalanche-fuji", + "maxAmountRequired": "10000", + "payTo": "0x742d35...", + "asset": "0x5425890...", + "resource": "/api/data" + }], + "error": "Insufficient payment: required 10000, received 5000" +} +``` + +The `X-PAYMENT-RESPONSE` header (when decoded) contains: + +```json +{ + "success": false, + "transaction": null, + "network": "avalanche-fuji", + "payer": "0x1234567890abcdef1234567890abcdef12345678", + "errorReason": "Insufficient authorization amount" +} +``` + +**Common error reasons**: +- `"Insufficient authorization amount"` - Payment amount too low +- `"Authorization expired"` - validBefore timestamp passed +- `"Invalid signature"` - Signature verification failed +- `"Nonce already used"` - Replay attack detected +- `"Insufficient balance"` - Payer doesn't have enough tokens + +**Why both body and header?** +- **JSON body**: Provides new payment requirements so the client can retry +- **X-PAYMENT-RESPONSE header**: Communicates what went wrong with the settlement attempt + +## Server Best Practices + +When implementing X-PAYMENT-RESPONSE headers, servers should follow these guidelines: + +1. **Support multiple networks**: Include options for different blockchains in `accepts` array when returning 402 failures +2. **Set reasonable timeouts**: Use `maxTimeoutSeconds` to prevent stale payments +3. **Use base units consistently**: Always specify amounts in smallest token denomination +4. **Validate signatures carefully**: Use EIP-712 verification libraries +5. **Implement replay protection**: Track used nonces to prevent double-spending +6. **Return transaction hashes**: Always include the on-chain transaction hash in success responses +7. **Provide clear error messages**: Use descriptive `errorReason` values for failure cases +8. **Store transaction receipts**: Keep settlement records for audit and dispute resolution + +For comprehensive security considerations including signature validation and nonce-based replay prevention, see [Security Considerations](./07-security-considerations). + +## Summary + +The `X-PAYMENT-RESPONSE` header provides settlement confirmation with blockchain transaction details. Success responses include the transaction hash for on-chain verification, while failure responses explain what went wrong and are accompanied by new payment requirements in the HTTP 402 body. \ No newline at end of file From 26badb90d0d4959e819b771ffc09760ee2a9be85 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Mon, 17 Nov 2025 14:37:31 -0500 Subject: [PATCH 28/30] add small changes to the payment requierement file --- .../02-http-payment-required.mdx | 72 +++++++++---------- 1 file changed, 34 insertions(+), 38 deletions(-) diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-payment-required.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-payment-required.mdx index 30811dd78c2..183066b5cd7 100644 --- a/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-payment-required.mdx +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-payment-required.mdx @@ -57,23 +57,49 @@ Each payment option in the `accepts` array contains: | `maxTimeoutSeconds` | number | No | Maximum time to complete payment | | `description` | string | No | Human-readable description | +### Payment Schemes + +The `scheme` field specifies how payments are settled. x402 supports multiple schemes to handle different payment models: + +**`exact` Scheme (Implemented)**: +- Fixed payment amount known upfront +- Use cases: Pay $0.10 to read an article, fixed-price API calls +- Implementations: EVM (EIP-3009), Solana, Sui +- Example: `"scheme": "exact", "maxAmountRequired": "100000"` + +**`up-to` Scheme (Proposed)**: +- Variable payment based on resource consumption +- Use cases: LLM token-based pricing, pay-per-token generation, usage-metered services +- Status: Not yet implemented - under development +- Example use: Pay up to $1.00, actual charge depends on tokens consumed + +The protocol is designed to be extensible, allowing new schemes to be added as payment models evolve. Current implementations focus on the `exact` scheme across multiple blockchains. + +**Reference**: See [x402 Schemes Specification](https://github.com/coinbase/x402/tree/main/specs/schemes) for technical details. + +### Network Identifiers + +Standard network identifiers for Avalanche and other chains: + +```javascript +"network": "avalanche-c-chain" // Avalanche C-Chain Mainnet +"network": "avalanche-fuji" // Avalanche Fuji Testnet +"network": "base-sepolia" // Base Sepolia Testnet +``` + ### Amount Specification -Amounts are always strings representing **base units** (smallest denomination): +Amounts are always strings representing **base units** (smallest denomination).
+**Important**: USDC has 6 decimals, so: ```javascript -// For USDC (6 decimals): 10000 = 0.01 USDC +// For USDC: 10000 = 0.01 USDC "maxAmountRequired": "10000" -// For USDC (6 decimals): 1000000 = 1.0 USDC +// For USDC: 1000000 = 1.0 USDC "maxAmountRequired": "1000000" ``` -**Important**: USDC has 6 decimals, so: -- 1 USDC = 1,000,000 base units -- 0.01 USDC = 10,000 base units -- 0.0001 USDC = 100 base units - ### Asset (Token Contract Address) The `asset` field contains the smart contract address of the payment token: @@ -91,36 +117,6 @@ The `asset` field contains the smart contract address of the payment token: **Note**: The asset is identified by contract address, not by symbol like "USDC". -### Network Identifiers - -Standard network identifiers for Avalanche and other chains: - -```javascript -"network": "avalanche-c-chain" // Avalanche C-Chain Mainnet -"network": "avalanche-fuji" // Avalanche Fuji Testnet -"network": "base-sepolia" // Base Sepolia Testnet -``` - -### Payment Schemes - -The `scheme` field specifies how payments are settled. x402 supports multiple schemes to handle different payment models: - -**`exact` Scheme (Implemented)**: -- Fixed payment amount known upfront -- Use cases: Pay $0.10 to read an article, fixed-price API calls -- Implementations: EVM (EIP-3009), Solana, Sui -- Example: `"scheme": "exact", "maxAmountRequired": "100000"` - -**`up-to` Scheme (Proposed)**: -- Variable payment based on resource consumption -- Use cases: LLM token-based pricing, pay-per-token generation, usage-metered services -- Status: Not yet implemented - under development -- Example use: Pay up to $1.00, actual charge depends on tokens consumed - -The protocol is designed to be extensible, allowing new schemes to be added as payment models evolve. Current implementations focus on the `exact` scheme across multiple blockchains. - -**Reference**: See [x402 Schemes Specification](https://github.com/coinbase/x402/tree/main/specs/schemes) for technical details. - ### Multiple Payment Options Servers can offer multiple payment options (different networks or tokens): From 580a220cac666c77f1c769f52dcde30500a5b381 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Mon, 17 Nov 2025 15:12:39 -0500 Subject: [PATCH 29/30] compressed in 4 shorter points --- .../02-introduction/03-ai-agent-problem.mdx | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/content/academy/x402-payment-infrastructure/02-introduction/03-ai-agent-problem.mdx b/content/academy/x402-payment-infrastructure/02-introduction/03-ai-agent-problem.mdx index e7531da487a..334a66fa2b2 100644 --- a/content/academy/x402-payment-infrastructure/02-introduction/03-ai-agent-problem.mdx +++ b/content/academy/x402-payment-infrastructure/02-introduction/03-ai-agent-problem.mdx @@ -14,20 +14,10 @@ AI agents face a fundamental problem: traditional payment systems require human AI agents cannot participate in traditional payment systems for several critical reasons: -### Cannot Create Accounts -Most signup flows require human verification through CAPTCHA, email confirmation, or phone verification. AI agents cannot complete these human-centric verification processes, preventing them from even accessing services. - -### Cannot Complete KYC -Identity verification (Know Your Customer) is designed specifically for humans—requiring government-issued IDs, proof of address, and sometimes video verification. AI agents have no legal identity and cannot complete these requirements. - -### Cannot Handle Micropayments -Transaction fees make small payments economically impossible. When an AI agent needs to pay \$0.001 for a single API call, traditional payment fees of $0.30+ make the transaction infeasible. - -### Credential Management Risks -Storing API keys and payment credentials creates security vulnerabilities. AI agents would need to securely manage numerous credentials across services, creating attack vectors and compliance challenges. - -### Limited Autonomy -Pre-approved payment methods and spending limits require human authorization, defeating the purpose of autonomous agents. Agents cannot dynamically adjust their resource usage or respond to changing market conditions. +- **Can't Create Accounts**: signup flows require human verification (CAPTCHA, email, phone) and KYC processes that AI agents cannot complete +- **Can't Handle Micropayments**: transaction fees make small payments economically infeasible when fees exceed the payment amount itself +- **Credential Management Risks**: storing API keys and payment credentials creates security vulnerabilities and compliance challenges across services +- **Limited Autonomy**: pre-approved payment methods and spending limits require human authorization, defeating autonomous agent operation ## What AI Agents Need From 0245593f465f91ab6525a5dcf9490284e4432327 Mon Sep 17 00:00:00 2001 From: federiconardelli7 Date: Mon, 17 Nov 2025 15:39:47 -0500 Subject: [PATCH 30/30] changes to the payment problem to make it more coincise --- .../02-introduction/02-payment-problem.mdx | 52 +++---------------- 1 file changed, 7 insertions(+), 45 deletions(-) diff --git a/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx b/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx index fc50b2cc82d..8ab95b82598 100644 --- a/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx +++ b/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx @@ -14,30 +14,11 @@ Traditional payment systems create significant friction for both users and devel Every traditional payment interaction requires users to complete at least five time-consuming steps: -### 1. Create Account -- Sign up for a service account with personal information -- Verify email addresses and set up passwords -- 5-15 minutes per service with high abandonment rates - -### 2. Add Payment Method -- Enter credit card details and complete bank verification -- Navigate complex payment forms -- 3-10 minutes with security and privacy concerns - -### 3. Complete KYC (Know Your Customer) -- Submit government-issued ID and proof of address -- Complete verification and wait for approval -- Hours to days with privacy concerns - -### 4. Buy Credits or Subscribe -- Purchase credits or subscribe to monthly plans before trying -- Commit to minimum purchases without knowing value -- Forces prepayment for uncertain utility - -### 5. Manage API Keys -- Generate, store, and rotate API keys securely -- Monitor for key compromise -- Ongoing maintenance and security risk +- **Creating Account**: requires signing up, verifying email address and setting up password (eta 5-15 minutes) +- **Add Payment Methods**: enter credit card details and complete bank verification (eta 3-10 minutes) +- **Complete KYC**: submit government-issued ID, proof of address and wait for approval (eta hours to days) +- **Buy Credits or Subscribe**: commit to minimum purchases or monthly plans without knowing value, forcing prepayment +- **Manage API Keys**: generate, store and rotate API keys securely with ongoing maintenance and security risk ## Cost Structure Problems @@ -50,7 +31,7 @@ Traditional payment processors impose significant fees that make micropayments i - Stripe: 2.9% + \$0.30 per transaction **Impact on Micropayments**: -For a \$0.01 API request, traditional fees would be \$0.32 (3,200% overhead) +For a \$0.01 API request, traditional fees would be \$0.30 (3,000% overhead), making the transaction economically impossible and forcing developers into subscription models even when pay-per-use would better serve users ### Fixed Fee Floor @@ -64,21 +45,6 @@ Payment processors hold funds for 2-7 days, creating cash flow challenges for me Traditional payments were designed for human-to-merchant interactions, not for automated systems. Automated systems cannot complete human-centric signup flows like CAPTCHA or email verification, storing payment credentials creates security risks, and pre-approval requirements prevent autonomous operation. These barriers make it impossible for AI agents and automated systems to participate in the payment economy. -## The Micropayment Impossibility - -Traditional payment systems make micropayments economically impossible: - -``` -Transaction Value: $0.01 (1 cent API request) -Processing Fee: 2.9% + $0.30 -Total Fee: $0.30029 -Net to Merchant: -$0.29029 (loss of 2,903%) - -Result: Merchant loses money on every transaction -``` - -This economic reality forces developers into subscription models even when pay-per-use would better serve users. - ## The API Monetization Challenge Developers face a painful choice when monetizing APIs: @@ -130,8 +96,4 @@ Traditional payment systems were designed for a different era—before micropaym 5. **Charges Fairly**: No percentage fees or high fixed costs 6. **Works with HTTP**: Native integration with web infrastructure -This is exactly what the x402 protocol provides. - -## Summary - -Traditional payment systems create insurmountable barriers for modern digital commerce through account requirements, high fees, settlement delays, and automation limitations. These systems make micropayments impossible and force developers into suboptimal business models. The x402 protocol addresses all of these limitations by providing instant, permissionless, HTTP-native payments with minimal fees. +This is exactly what the x402 protocol provides. \ No newline at end of file