xPay2
. xPay2 is a proxy service that adds payment functionality to any existing AP
Problem Statement
This project extends the native capabilities of x402 by adding features like credit, early resource returns, and seamless monetization of any Web2 API β with any integration effort. xPay2 is a proxy service that adds payment functionality to any existing API without requiring code changes. Developers paste their backend URL, set a price, and get a paid public endpoint powered by the x402 protocol and USDC payments on Base.https://github.com/Ashar2shahid/xPay2
Solution
xPay2 - HTTP 402 Payment Gatewayhttps://github.com/Ashar2shahid/xPay2Turn any API into a paid service instantly with HTTP 402 Payment Required protocolxPay2 is a proxy service that adds payment functionality to any existing API without requiring code changes. Developers paste their backend URL, set a price, and get a paid public endpoint powered by the x402 protocol and USDC payments on Base.π Featuresπ Zero Backend Integration- Works with any HTTP API, no code changes neededπ³ HTTP 402 Protocol- Standards-compliant payment-required responsesβ‘ Credit System- Prepaid API usage with instant, gasless requestsπ EIP-712 Signatures- Cryptographically secure authenticationπ Usage Analytics- Track all requests, payments, and settlementsπ Multi-Chain Support- Base, Optimism, Arbitrum, Polygonπ° USDC Payments- Stable, predictable pricingπ― Quick StartPrerequisitesNode.js 18+USDC on Base networkPrivate key with USDC balanceInstallation# Clone the repository git clone <repo-url> cd ethindia-xPay2 # Install dependencies npm install # Set up environment variables cp .env.example .env # Add your EVM_PRIVATE_KEY and ADDRESS to .env # Initialize the database npm run init-db # Start the development server npm run devCreate Your First Paid Endpoint# 1. Create a project with a paid endpoint curl -X POST http://localhost:3000/api/projects \ -H "Content-Type: application/json" \ -d '{ "name": "My API", "description": "My paid API service", "defaultPrice": 0.01, "currency": "USD", "payTo": "0xYourAddress", "paymentChains": ["base"], "endpoints": [{ "url": "https://api.example.com", "path": "/data", "method": "GET", "price": 0.01, "description": "Get data endpoint" }] }' # 2. Your proxy URL is now live! # http://localhost:3000/api/proxy/{project-slug}/data # 3. Requests without payment return 402 curl http://localhost:3000/api/proxy/{project-slug}/data # Returns: 402 Payment Required with payment instructions # 4. Use x402-fetch to make paid requests # See examples/ directory for client codeπ‘ Credit SystemThe credit system enables prepaid API usage with instant, gasless requests:How It WorksOverpay once- Pay $0.05 for a $0.01 endpointGet $0.04 in credits- Automatically stored in your accountUse credits instantly- Make requests with zero-value signaturesNo gas fees- Credit usage skips on-chain settlementExample Flow// First request: Pay $0.05 for $0.01 endpoint // β Creates $0.04 in credits // Subsequent requests: Use zero-value authentication // β Deducts $0.01 from credits (now $0.03) // β Instant response, no on-chain transaction // β No gas fees // Continue until credits depleted // β System returns 402 asking for paymentEnable Credits# Enable credits for an endpoint curl -X PATCH http://localhost:3000/api/endpoints/{endpoint-id} \ -H "Content-Type: application/json" \ -d '{ "creditsEnabled": true, "minTopupAmount": 0.01 }'π§ͺ TestingRun the comprehensive test suite:node e2e-test.jsTest Coverage:β 20/20 tests passingBasic payment flowCredit creation via overpaymentZero-value authenticationCredit exhaustion handlingEdge cases (invalid signatures, expired timestamps)ποΈ Architectureβββββββββββββββ β Client β β (x402-fetch)β ββββββββ¬βββββββ β X-Payment: <signature> βΌ βββββββββββββββββββββββββββββββββββ β xPay2 Proxy β β ββββββββββββββββββββββββββββ β β β 1. Verify Payment β β β β - EIP-712 signature β β β β - Credit balance β β β ββββββββββββββββββββββββββββ β β ββββββββββββββββββββββββββββ β β β 2. Forward Request β β β β - Add headers β β β β - Proxy to backend β β β ββββββββββββββββββββββββββββ β β ββββββββββββββββββββββββββββ β β β 3. Settle Payment β β β β - On-chain (if paid) β β β β - Skip (if credits) β β β ββββββββββββββββββββββββββββ β ββββββββββ¬βββββββββββββββββββββββββ β Response + Receipt βΌ βββββββββββββββββββ β Your Backend β β (no changes!) β βββββββββββββββββββπ§ API ReferenceCreate ProjectPOST /api/projects Content-Type: application/json { "name": "My API", "description": "API description", "defaultPrice": 0.02, "currency": "USD", "payTo": "0xYourAddress", "paymentChains": ["base"], "endpoints": [...] }Enable CreditsPATCH /api/endpoints/{endpointId} Content-Type: application/json { "creditsEnabled": true, "minTopupAmount": 0.01 }Make Paid RequestGET /api/proxy/{project-slug}/{endpoint-path} X-Payment: <base64-encoded-x402-payment>π Response HeadersAll proxied requests include tracking headers:X-Proxy-Payment-Status- Payment verification statusX-Proxy-Settlement-Status- On-chain settlement statusX-Credit-Balance- Remaining credit balance (if credits enabled)X-Credit-Used- Whether credits were used for this requestX-Credit-Total-Deposited- Total credits ever depositedX-Credit-Total-Spent- Total credits ever spentπ οΈ Tech StackNext.js- Pages Router for API routesSQLite + Drizzle ORM- Lightweight databaseviem- Ethereum interactions and EIP-712 signingx402- HTTP 402 protocol implementationBigNumber.js- Precise decimal arithmeticBase Network- Layer 2 for cheap USDC transfersπ Security FeaturesEIP-712 Signature VerificationFull cryptographic verification of all signaturesValidates against USDC's EIP-712 domainTimestamp validation (validAfter/validBefore)Nonce-based replay protectionBigNumber ArithmeticEliminates JavaScript floating-point errorsEnsures exact credit calculationsPrevents balance discrepanciesExample:// Without BigNumber β 0.03 - 0.01 = 0.019999999999999997 // With BigNumber β new BigNumber(0.03).minus(0.01) = 0.02π Environment Variables# Required EVM_PRIVATE_KEY=0x... # Private key for settlement ADDRESS=0x... # Address to receive payments # Optional FACILITATOR_URL=https://facilitator.coinbase.com ENABLE_SETTLEMENT=true # Enable on-chain settlement NEXT_PUBLIC_APP_URL=http://localhost:3000π Deployment# Build for production npm run build # Start production server npm start # Or deploy to Vercel vercel deployπ ExamplesSee theexamples/directory for:Client implementation with x402-fetchCredit usage patternsError handlingMulti-endpoint projectsπ€ ContributingContributions welcome! Please readCfor development guidelines.π LicenseMITπ LinksxBUEBuilt with β€οΈ for ETHIndia 2024
Hackathon
ETHGlobal New Delhi
2025
Contributors
- Ashar2shahid
21 contributions
- beejsbj
18 contributions