diff --git a/components/academy/learning-path-configs/avalanche-developer.config.ts b/components/academy/learning-path-configs/avalanche-developer.config.ts index 020dc5d5b0a..87024e67ef3 100644 --- a/components/academy/learning-path-configs/avalanche-developer.config.ts +++ b/components/academy/learning-path-configs/avalanche-developer.config.ts @@ -56,6 +56,18 @@ export const avalancheLearningPaths: CourseNode[] = [ position: { x: 20, y: 450 }, mobileOrder: 11 }, + { + 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 { id: "interchain-messaging", name: "Interchain Messaging", diff --git a/content/academy/meta.json b/content/academy/meta.json index 91ac594ef96..8239f8ec784 100644 --- a/content/academy/meta.json +++ b/content/academy/meta.json @@ -11,6 +11,7 @@ "interchain-token-transfer", "icm-chainlink", "avacloudapis", - "encrypted-erc" + "encrypted-erc", + "x402-payment-infrastructure" ] } \ No newline at end of file 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..bb15bb3cb05 --- /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](https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/course-images/x402-payment-infrastructure/x402PaymentCycle.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. [You can explore all available facilitators](/integrations#x402). 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..8ab95b82598 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/02-introduction/02-payment-problem.mdx @@ -0,0 +1,99 @@ +--- +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: + +- **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 + +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.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 + +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. 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 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. + +## 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 + +## The Need for a New Approach + +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**: 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 + +This is exactly what the x402 protocol provides. \ No newline at end of file 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..334a66fa2b2 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/02-introduction/03-ai-agent-problem.mdx @@ -0,0 +1,40 @@ +--- +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: + +- **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 + +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 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 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..e72439fd8ab --- /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 [X-PAYMENT Header](./03-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](https://qizat5l3bwvomkny.public.blob.vercel-storage.com/builders-hub/course-images/x402-payment-infrastructure/12StepPaymentFlow.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](./07-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 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..183066b5cd7 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/02-http-payment-required.mdx @@ -0,0 +1,152 @@ +--- +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 | + +### 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).
+**Important**: USDC has 6 decimals, so: + +```javascript +// For USDC: 10000 = 0.01 USDC +"maxAmountRequired": "10000" + +// For USDC: 1000000 = 1.0 USDC +"maxAmountRequired": "1000000" +``` + +### 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". + +### 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 diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/05-facilitator-role.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/05-facilitator-role.mdx new file mode 100644 index 00000000000..23f07b12bbf --- /dev/null +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/05-facilitator-role.mdx @@ -0,0 +1,302 @@ +--- +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 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. + +## 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](./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. diff --git a/content/academy/x402-payment-infrastructure/03-technical-architecture/06-blockchain-settlement.mdx b/content/academy/x402-payment-infrastructure/03-technical-architecture/06-blockchain-settlement.mdx new file mode 100644 index 00000000000..eb13314dcc6 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/03-technical-architecture/06-blockchain-settlement.mdx @@ -0,0 +1,184 @@ +--- +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. + +### 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. + +## 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](./07-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) 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) 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 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. 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. 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. 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..b599d4beb64 --- /dev/null +++ b/content/academy/x402-payment-infrastructure/meta.json @@ -0,0 +1,16 @@ +{ + "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---", + "get-certificate" + ] +} diff --git a/content/common/intro/instructors.tsx b/content/common/intro/instructors.tsx index 7d91c31df30..5102fa2c2b8 100644 --- a/content/common/intro/instructors.tsx +++ b/content/common/intro/instructors.tsx @@ -104,6 +104,14 @@ const instructors: Instructor[] = [ 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", + }, { name: "Katherine Sullivan", title: "Developer Relations Intern", diff --git a/content/courses.tsx b/content/courses.tsx index b85c03cc1e2..b6491fc3b81 100644 --- a/content/courses.tsx +++ b/content/courses.tsx @@ -53,6 +53,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",